| 1 |
:mod:`!threading` --- Thread-based parallelism |
| 2 |
============================================== |
| 3 |
|
| 4 |
.. module:: threading |
| 5 |
:synopsis: Thread-based parallelism. |
| 6 |
|
| 7 |
**Source code:** :source:`Lib/threading.py` |
| 8 |
|
| 9 |
-------------- |
| 10 |
|
| 11 |
This module constructs higher-level threading interfaces on top of the lower |
| 12 |
level :mod:`_thread` module. |
| 13 |
|
| 14 |
.. include:: ../includes/wasm-notavail.rst |
| 15 |
|
| 16 |
Introduction |
| 17 |
------------ |
| 18 |
|
| 19 |
The :mod:`!threading` module provides a way to run multiple `threads |
| 20 |
<https://en.wikipedia.org/wiki/Thread_(computing)>`_ (smaller |
| 21 |
units of a process) concurrently within a single process. It allows for the |
| 22 |
creation and management of threads, making it possible to execute tasks in |
| 23 |
parallel, sharing memory space. Threads are particularly useful when tasks are |
| 24 |
I/O bound, such as file operations or making network requests, |
| 25 |
where much of the time is spent waiting for external resources. |
| 26 |
|
| 27 |
A typical use case for :mod:`!threading` includes managing a pool of worker |
| 28 |
threads that can process multiple tasks concurrently. Here's a basic example of |
| 29 |
creating and starting threads using :class:`~threading.Thread`:: |
| 30 |
|
| 31 |
import threading |
| 32 |
import time |
| 33 |
|
| 34 |
def crawl(link, delay=3): |
| 35 |
print(f"crawl started for {link}") |
| 36 |
time.sleep(delay) # Blocking I/O (simulating a network request) |
| 37 |
print(f"crawl ended for {link}") |
| 38 |
|
| 39 |
links = [ |
| 40 |
"https://python.org", |
| 41 |
"https://docs.python.org", |
| 42 |
"https://peps.python.org", |
| 43 |
] |
| 44 |
|
| 45 |
# Start threads for each link |
| 46 |
threads = [] |
| 47 |
for link in links: |
| 48 |
# Using `args` to pass positional arguments and `kwargs` for keyword arguments |
| 49 |
t = threading.Thread(target=crawl, args=(link,), kwargs={"delay": 2}) |
| 50 |
threads.append(t) |
| 51 |
|
| 52 |
# Start each thread |
| 53 |
for t in threads: |
| 54 |
t.start() |
| 55 |
|
| 56 |
# Wait for all threads to finish |
| 57 |
for t in threads: |
| 58 |
t.join() |
| 59 |
|
| 60 |
.. versionchanged:: 3.7 |
| 61 |
This module used to be optional, it is now always available. |
| 62 |
|
| 63 |
.. seealso:: |
| 64 |
|
| 65 |
:class:`concurrent.futures.ThreadPoolExecutor` offers a higher level interface |
| 66 |
to push tasks to a background thread without blocking execution of the |
| 67 |
calling thread, while still being able to retrieve their results when needed. |
| 68 |
|
| 69 |
:mod:`queue` provides a thread-safe interface for exchanging data between |
| 70 |
running threads. |
| 71 |
|
| 72 |
:mod:`asyncio` offers an alternative approach to achieving task level |
| 73 |
concurrency without requiring the use of multiple operating system threads. |
| 74 |
|
| 75 |
.. note:: |
| 76 |
|
| 77 |
In the Python 2.x series, this module contained ``camelCase`` names |
| 78 |
for some methods and functions. These are deprecated as of Python 3.10, |
| 79 |
but they are still supported for compatibility with Python 2.5 and lower. |
| 80 |
|
| 81 |
|
| 82 |
.. impl-detail:: |
| 83 |
|
| 84 |
In CPython, due to the :term:`Global Interpreter Lock |
| 85 |
<global interpreter lock>`, only one thread |
| 86 |
can execute Python code at once (even though certain performance-oriented |
| 87 |
libraries might overcome this limitation). |
| 88 |
If you want your application to make better use of the computational |
| 89 |
resources of multi-core machines, you are advised to use |
| 90 |
:mod:`multiprocessing` or :class:`concurrent.futures.ProcessPoolExecutor`. |
| 91 |
However, threading is still an appropriate model if you want to run |
| 92 |
multiple I/O-bound tasks simultaneously. |
| 93 |
|
| 94 |
GIL and performance considerations |
| 95 |
---------------------------------- |
| 96 |
|
| 97 |
Unlike the :mod:`multiprocessing` module, which uses separate processes to |
| 98 |
bypass the :term:`global interpreter lock` (GIL), the threading module operates |
| 99 |
within a single process, meaning that all threads share the same memory space. |
| 100 |
However, the GIL limits the performance gains of threading when it comes to |
| 101 |
CPU-bound tasks, as only one thread can execute Python bytecode at a time. |
| 102 |
Despite this, threads remain a useful tool for achieving concurrency in many |
| 103 |
scenarios. |
| 104 |
|
| 105 |
As of Python 3.13, :term:`free-threaded <free threading>` builds |
| 106 |
can disable the GIL, enabling true parallel execution of threads, but this |
| 107 |
feature is not available by default (see :pep:`703`). |
| 108 |
|
| 109 |
.. TODO: At some point this feature will become available by default. |
| 110 |
|
| 111 |
Reference |
| 112 |
--------- |
| 113 |
|
| 114 |
This module defines the following functions: |
| 115 |
|
| 116 |
|
| 117 |
.. function:: active_count() |
| 118 |
|
| 119 |
Return the number of :class:`Thread` objects currently alive. The returned |
| 120 |
count is equal to the length of the list returned by :func:`.enumerate`. |
| 121 |
|
| 122 |
The function ``activeCount`` is a deprecated alias for this function. |
| 123 |
|
| 124 |
|
| 125 |
.. function:: current_thread() |
| 126 |
|
| 127 |
Return the current :class:`Thread` object, corresponding to the caller's thread |
| 128 |
of control. If the caller's thread of control was not created through the |
| 129 |
:mod:`!threading` module, a dummy thread object with limited functionality is |
| 130 |
returned. |
| 131 |
|
| 132 |
The function ``currentThread`` is a deprecated alias for this function. |
| 133 |
|
| 134 |
|
| 135 |
.. function:: excepthook(args, /) |
| 136 |
|
| 137 |
Handle uncaught exception raised by :func:`Thread.run`. |
| 138 |
|
| 139 |
The *args* argument has the following attributes: |
| 140 |
|
| 141 |
* *exc_type*: Exception type. |
| 142 |
* *exc_value*: Exception value, can be ``None``. |
| 143 |
* *exc_traceback*: Exception traceback, can be ``None``. |
| 144 |
* *thread*: Thread which raised the exception, can be ``None``. |
| 145 |
|
| 146 |
If *exc_type* is :exc:`SystemExit`, the exception is silently ignored. |
| 147 |
Otherwise, the exception is printed out on :data:`sys.stderr`. |
| 148 |
|
| 149 |
If this function raises an exception, :func:`sys.excepthook` is called to |
| 150 |
handle it. |
| 151 |
|
| 152 |
:func:`threading.excepthook` can be overridden to control how uncaught |
| 153 |
exceptions raised by :func:`Thread.run` are handled. |
| 154 |
|
| 155 |
Storing *exc_value* using a custom hook can create a reference cycle. It |
| 156 |
should be cleared explicitly to break the reference cycle when the |
| 157 |
exception is no longer needed. |
| 158 |
|
| 159 |
Storing *thread* using a custom hook can resurrect it if it is set to an |
| 160 |
object which is being finalized. Avoid storing *thread* after the custom |
| 161 |
hook completes to avoid resurrecting objects. |
| 162 |
|
| 163 |
.. seealso:: |
| 164 |
:func:`sys.excepthook` handles uncaught exceptions. |
| 165 |
|
| 166 |
.. versionadded:: 3.8 |
| 167 |
|
| 168 |
.. data:: __excepthook__ |
| 169 |
|
| 170 |
Holds the original value of :func:`threading.excepthook`. It is saved so that the |
| 171 |
original value can be restored in case they happen to get replaced with |
| 172 |
broken or alternative objects. |
| 173 |
|
| 174 |
.. versionadded:: 3.10 |
| 175 |
|
| 176 |
.. function:: get_ident() |
| 177 |
|
| 178 |
Return the 'thread identifier' of the current thread. This is a nonzero |
| 179 |
integer. Its value has no direct meaning; it is intended as a magic cookie |
| 180 |
to be used e.g. to index a dictionary of thread-specific data. Thread |
| 181 |
identifiers may be recycled when a thread exits and another thread is |
| 182 |
created. |
| 183 |
|
| 184 |
.. versionadded:: 3.3 |
| 185 |
|
| 186 |
|
| 187 |
.. function:: get_native_id() |
| 188 |
|
| 189 |
Return the native integral Thread ID of the current thread assigned by the kernel. |
| 190 |
This is a non-negative integer. |
| 191 |
Its value may be used to uniquely identify this particular thread system-wide |
| 192 |
(until the thread terminates, after which the value may be recycled by the OS). |
| 193 |
|
| 194 |
.. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD. |
| 195 |
|
| 196 |
.. versionadded:: 3.8 |
| 197 |
|
| 198 |
.. versionchanged:: 3.13 |
| 199 |
Added support for GNU/kFreeBSD. |
| 200 |
|
| 201 |
|
| 202 |
.. function:: enumerate() |
| 203 |
|
| 204 |
Return a list of all :class:`Thread` objects currently active. The list |
| 205 |
includes daemonic threads and dummy thread objects created by |
| 206 |
:func:`current_thread`. It excludes terminated threads and threads |
| 207 |
that have not yet been started. However, the main thread is always part |
| 208 |
of the result, even when terminated. |
| 209 |
|
| 210 |
|
| 211 |
.. function:: main_thread() |
| 212 |
|
| 213 |
Return the main :class:`Thread` object. In normal conditions, the |
| 214 |
main thread is the thread from which the Python interpreter was |
| 215 |
started. |
| 216 |
|
| 217 |
.. versionadded:: 3.4 |
| 218 |
|
| 219 |
|
| 220 |
.. function:: settrace(func) |
| 221 |
|
| 222 |
.. index:: single: trace function |
| 223 |
|
| 224 |
Set a trace function for all threads started from the :mod:`!threading` module. |
| 225 |
The *func* will be passed to :func:`sys.settrace` for each thread, before its |
| 226 |
:meth:`~Thread.run` method is called. |
| 227 |
|
| 228 |
.. function:: settrace_all_threads(func) |
| 229 |
|
| 230 |
Set a trace function for all threads started from the :mod:`!threading` module |
| 231 |
and all Python threads that are currently executing. |
| 232 |
|
| 233 |
The *func* will be passed to :func:`sys.settrace` for each thread, before its |
| 234 |
:meth:`~Thread.run` method is called. |
| 235 |
|
| 236 |
.. versionadded:: 3.12 |
| 237 |
|
| 238 |
.. function:: gettrace() |
| 239 |
|
| 240 |
.. index:: |
| 241 |
single: trace function |
| 242 |
single: debugger |
| 243 |
|
| 244 |
Get the trace function as set by :func:`settrace`. |
| 245 |
|
| 246 |
.. versionadded:: 3.10 |
| 247 |
|
| 248 |
|
| 249 |
.. function:: setprofile(func) |
| 250 |
|
| 251 |
.. index:: single: profile function |
| 252 |
|
| 253 |
Set a profile function for all threads started from the :mod:`!threading` module. |
| 254 |
The *func* will be passed to :func:`sys.setprofile` for each thread, before its |
| 255 |
:meth:`~Thread.run` method is called. |
| 256 |
|
| 257 |
.. function:: setprofile_all_threads(func) |
| 258 |
|
| 259 |
Set a profile function for all threads started from the :mod:`!threading` module |
| 260 |
and all Python threads that are currently executing. |
| 261 |
|
| 262 |
The *func* will be passed to :func:`sys.setprofile` for each thread, before its |
| 263 |
:meth:`~Thread.run` method is called. |
| 264 |
|
| 265 |
.. versionadded:: 3.12 |
| 266 |
|
| 267 |
.. function:: getprofile() |
| 268 |
|
| 269 |
.. index:: single: profile function |
| 270 |
|
| 271 |
Get the profiler function as set by :func:`setprofile`. |
| 272 |
|
| 273 |
.. versionadded:: 3.10 |
| 274 |
|
| 275 |
|
| 276 |
.. function:: stack_size([size]) |
| 277 |
|
| 278 |
Return the thread stack size used when creating new threads. The optional |
| 279 |
*size* argument specifies the stack size to be used for subsequently created |
| 280 |
threads, and must be 0 (use platform or configured default) or a positive |
| 281 |
integer value of at least 32,768 (32 KiB). If *size* is not specified, |
| 282 |
0 is used. If changing the thread stack size is |
| 283 |
unsupported, a :exc:`RuntimeError` is raised. If the specified stack size is |
| 284 |
invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32 KiB |
| 285 |
is currently the minimum supported stack size value to guarantee sufficient |
| 286 |
stack space for the interpreter itself. Note that some platforms may have |
| 287 |
particular restrictions on values for the stack size, such as requiring a |
| 288 |
minimum stack size > 32 KiB or requiring allocation in multiples of the system |
| 289 |
memory page size - platform documentation should be referred to for more |
| 290 |
information (4 KiB pages are common; using multiples of 4096 for the stack size is |
| 291 |
the suggested approach in the absence of more specific information). |
| 292 |
|
| 293 |
.. availability:: Windows, pthreads. |
| 294 |
|
| 295 |
Unix platforms with POSIX threads support. |
| 296 |
|
| 297 |
|
| 298 |
This module also defines the following constant: |
| 299 |
|
| 300 |
.. data:: TIMEOUT_MAX |
| 301 |
|
| 302 |
The maximum value allowed for the *timeout* parameter of blocking functions |
| 303 |
(:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.). |
| 304 |
Specifying a timeout greater than this value will raise an |
| 305 |
:exc:`OverflowError`. |
| 306 |
|
| 307 |
.. versionadded:: 3.2 |
| 308 |
|
| 309 |
|
| 310 |
This module defines a number of classes, which are detailed in the sections |
| 311 |
below. |
| 312 |
|
| 313 |
The design of this module is loosely based on Java's threading model. However, |
| 314 |
where Java makes locks and condition variables basic behavior of every object, |
| 315 |
they are separate objects in Python. Python's :class:`Thread` class supports a |
| 316 |
subset of the behavior of Java's Thread class; currently, there are no |
| 317 |
priorities, no thread groups, and threads cannot be destroyed, stopped, |
| 318 |
suspended, resumed, or interrupted. The static methods of Java's Thread class, |
| 319 |
when implemented, are mapped to module-level functions. |
| 320 |
|
| 321 |
All of the methods described below are executed atomically. |
| 322 |
|
| 323 |
|
| 324 |
Thread-local data |
| 325 |
^^^^^^^^^^^^^^^^^ |
| 326 |
|
| 327 |
Thread-local data is data whose values are thread specific. If you |
| 328 |
have data that you want to be local to a thread, create a |
| 329 |
:class:`local` object and use its attributes:: |
| 330 |
|
| 331 |
>>> mydata = local() |
| 332 |
>>> mydata.number = 42 |
| 333 |
>>> mydata.number |
| 334 |
42 |
| 335 |
|
| 336 |
You can also access the :class:`local`-object's dictionary:: |
| 337 |
|
| 338 |
>>> mydata.__dict__ |
| 339 |
{'number': 42} |
| 340 |
>>> mydata.__dict__.setdefault('widgets', []) |
| 341 |
[] |
| 342 |
>>> mydata.widgets |
| 343 |
[] |
| 344 |
|
| 345 |
If we access the data in a different thread:: |
| 346 |
|
| 347 |
>>> log = [] |
| 348 |
>>> def f(): |
| 349 |
... items = sorted(mydata.__dict__.items()) |
| 350 |
... log.append(items) |
| 351 |
... mydata.number = 11 |
| 352 |
... log.append(mydata.number) |
| 353 |
|
| 354 |
>>> import threading |
| 355 |
>>> thread = threading.Thread(target=f) |
| 356 |
>>> thread.start() |
| 357 |
>>> thread.join() |
| 358 |
>>> log |
| 359 |
[[], 11] |
| 360 |
|
| 361 |
we get different data. Furthermore, changes made in the other thread |
| 362 |
don't affect data seen in this thread:: |
| 363 |
|
| 364 |
>>> mydata.number |
| 365 |
42 |
| 366 |
|
| 367 |
Of course, values you get from a :class:`local` object, including their |
| 368 |
:attr:`~object.__dict__` attribute, are for whatever thread was current |
| 369 |
at the time the attribute was read. For that reason, you generally |
| 370 |
don't want to save these values across threads, as they apply only to |
| 371 |
the thread they came from. |
| 372 |
|
| 373 |
You can create custom :class:`local` objects by subclassing the |
| 374 |
:class:`local` class:: |
| 375 |
|
| 376 |
>>> class MyLocal(local): |
| 377 |
... number = 2 |
| 378 |
... def __init__(self, /, **kw): |
| 379 |
... self.__dict__.update(kw) |
| 380 |
... def squared(self): |
| 381 |
... return self.number ** 2 |
| 382 |
|
| 383 |
This can be useful to support default values, methods and |
| 384 |
initialization. Note that if you define an :py:meth:`~object.__init__` |
| 385 |
method, it will be called each time the :class:`local` object is used |
| 386 |
in a separate thread. This is necessary to initialize each thread's |
| 387 |
dictionary. |
| 388 |
|
| 389 |
Now if we create a :class:`local` object:: |
| 390 |
|
| 391 |
>>> mydata = MyLocal(color='red') |
| 392 |
|
| 393 |
we have a default number:: |
| 394 |
|
| 395 |
>>> mydata.number |
| 396 |
2 |
| 397 |
|
| 398 |
an initial color:: |
| 399 |
|
| 400 |
>>> mydata.color |
| 401 |
'red' |
| 402 |
>>> del mydata.color |
| 403 |
|
| 404 |
And a method that operates on the data:: |
| 405 |
|
| 406 |
>>> mydata.squared() |
| 407 |
4 |
| 408 |
|
| 409 |
As before, we can access the data in a separate thread:: |
| 410 |
|
| 411 |
>>> log = [] |
| 412 |
>>> thread = threading.Thread(target=f) |
| 413 |
>>> thread.start() |
| 414 |
>>> thread.join() |
| 415 |
>>> log |
| 416 |
[[('color', 'red')], 11] |
| 417 |
|
| 418 |
without affecting this thread's data:: |
| 419 |
|
| 420 |
>>> mydata.number |
| 421 |
2 |
| 422 |
>>> mydata.color |
| 423 |
Traceback (most recent call last): |
| 424 |
... |
| 425 |
AttributeError: 'MyLocal' object has no attribute 'color' |
| 426 |
|
| 427 |
Note that subclasses can define :term:`__slots__`, but they are not |
| 428 |
thread local. They are shared across threads:: |
| 429 |
|
| 430 |
>>> class MyLocal(local): |
| 431 |
... __slots__ = 'number' |
| 432 |
|
| 433 |
>>> mydata = MyLocal() |
| 434 |
>>> mydata.number = 42 |
| 435 |
>>> mydata.color = 'red' |
| 436 |
|
| 437 |
So, the separate thread:: |
| 438 |
|
| 439 |
>>> thread = threading.Thread(target=f) |
| 440 |
>>> thread.start() |
| 441 |
>>> thread.join() |
| 442 |
|
| 443 |
affects what we see:: |
| 444 |
|
| 445 |
>>> mydata.number |
| 446 |
11 |
| 447 |
|
| 448 |
|
| 449 |
.. class:: local() |
| 450 |
|
| 451 |
A class that represents thread-local data. |
| 452 |
|
| 453 |
|
| 454 |
.. _thread-objects: |
| 455 |
|
| 456 |
Thread objects |
| 457 |
^^^^^^^^^^^^^^ |
| 458 |
|
| 459 |
The :class:`Thread` class represents an activity that is run in a separate |
| 460 |
thread of control. There are two ways to specify the activity: by passing a |
| 461 |
callable object to the constructor, or by overriding the :meth:`~Thread.run` |
| 462 |
method in a subclass. No other methods (except for the constructor) should be |
| 463 |
overridden in a subclass. In other words, *only* override the |
| 464 |
``__init__()`` and :meth:`~Thread.run` methods of this class. |
| 465 |
|
| 466 |
Once a thread object is created, its activity must be started by calling the |
| 467 |
thread's :meth:`~Thread.start` method. This invokes the :meth:`~Thread.run` |
| 468 |
method in a separate thread of control. |
| 469 |
|
| 470 |
Once the thread's activity is started, the thread is considered 'alive'. It |
| 471 |
stops being alive when its :meth:`~Thread.run` method terminates -- either |
| 472 |
normally, or by raising an unhandled exception. The :meth:`~Thread.is_alive` |
| 473 |
method tests whether the thread is alive. |
| 474 |
|
| 475 |
Other threads can call a thread's :meth:`~Thread.join` method. This blocks |
| 476 |
the calling thread until the thread whose :meth:`~Thread.join` method is |
| 477 |
called is terminated. |
| 478 |
|
| 479 |
A thread has a name. The name can be passed to the constructor, and read or |
| 480 |
changed through the :attr:`~Thread.name` attribute. |
| 481 |
|
| 482 |
If the :meth:`~Thread.run` method raises an exception, |
| 483 |
:func:`threading.excepthook` is called to handle it. By default, |
| 484 |
:func:`threading.excepthook` ignores silently :exc:`SystemExit`. |
| 485 |
|
| 486 |
A thread can be flagged as a "daemon thread". The significance of this flag is |
| 487 |
that the entire Python program exits when only daemon threads are left. The |
| 488 |
initial value is inherited from the creating thread. The flag can be set |
| 489 |
through the :attr:`~Thread.daemon` property or the *daemon* constructor |
| 490 |
argument. |
| 491 |
|
| 492 |
.. note:: |
| 493 |
Daemon threads are abruptly stopped at shutdown. Their resources (such |
| 494 |
as open files, database transactions, etc.) may not be released properly. |
| 495 |
If you want your threads to stop gracefully, make them non-daemonic and |
| 496 |
use a suitable signalling mechanism such as an :class:`Event`. |
| 497 |
|
| 498 |
There is a "main thread" object; this corresponds to the initial thread of |
| 499 |
control in the Python program. It is not a daemon thread. |
| 500 |
|
| 501 |
There is the possibility that "dummy thread objects" are created. These are |
| 502 |
thread objects corresponding to "alien threads", which are threads of control |
| 503 |
started outside the threading module, such as directly from C code. Dummy |
| 504 |
thread objects have limited functionality; they are always considered alive and |
| 505 |
daemonic, and cannot be :ref:`joined <meth-thread-join>`. They are never deleted, |
| 506 |
since it is impossible to detect the termination of alien threads. |
| 507 |
|
| 508 |
|
| 509 |
.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, *, \ |
| 510 |
daemon=None, context=None) |
| 511 |
|
| 512 |
This constructor should always be called with keyword arguments. Arguments |
| 513 |
are: |
| 514 |
|
| 515 |
*group* must be ``None`` as it is reserved for future extension when a |
| 516 |
:class:`!ThreadGroup` class is implemented. |
| 517 |
|
| 518 |
*target* is the callable object to be invoked by the :meth:`run` method. |
| 519 |
Defaults to ``None``, meaning nothing is called. |
| 520 |
|
| 521 |
*name* is the thread name. By default, a unique name is constructed |
| 522 |
of the form "Thread-*N*" where *N* is a small decimal number, |
| 523 |
or "Thread-*N* (target)" where "target" is ``target.__name__`` if the |
| 524 |
*target* argument is specified. |
| 525 |
|
| 526 |
*args* is a list or tuple of arguments for the target invocation. Defaults to ``()``. |
| 527 |
|
| 528 |
*kwargs* is a dictionary of keyword arguments for the target invocation. |
| 529 |
Defaults to ``{}``. |
| 530 |
|
| 531 |
If not ``None``, *daemon* explicitly sets whether the thread is daemonic. |
| 532 |
If ``None`` (the default), the daemonic property is inherited from the |
| 533 |
current thread. |
| 534 |
|
| 535 |
*context* is the :class:`~contextvars.Context` value to use when starting |
| 536 |
the thread. The default value is ``None`` which indicates that the |
| 537 |
:data:`sys.flags.thread_inherit_context` flag controls the behaviour. If |
| 538 |
the flag is true, threads will start with a copy of the context of the |
| 539 |
caller of :meth:`~Thread.start`. If false, they will start with an empty |
| 540 |
context. To explicitly start with an empty context, pass a new instance of |
| 541 |
:class:`~contextvars.Context()`. To explicitly start with a copy of the |
| 542 |
current context, pass the value from :func:`~contextvars.copy_context`. The |
| 543 |
flag defaults true on free-threaded builds and false otherwise. |
| 544 |
|
| 545 |
If the subclass overrides the constructor, it must make sure to invoke the |
| 546 |
base class constructor (``Thread.__init__()``) before doing anything else to |
| 547 |
the thread. |
| 548 |
|
| 549 |
.. versionchanged:: 3.3 |
| 550 |
Added the *daemon* parameter. |
| 551 |
|
| 552 |
.. versionchanged:: 3.10 |
| 553 |
Use the *target* name if *name* argument is omitted. |
| 554 |
|
| 555 |
.. versionchanged:: 3.14 |
| 556 |
Added the *context* parameter. |
| 557 |
|
| 558 |
.. method:: start() |
| 559 |
|
| 560 |
Start the thread's activity. |
| 561 |
|
| 562 |
It must be called at most once per thread object. It arranges for the |
| 563 |
object's :meth:`~Thread.run` method to be invoked in a separate thread |
| 564 |
of control. |
| 565 |
|
| 566 |
This method will raise a :exc:`RuntimeError` if called more than once |
| 567 |
on the same thread object. |
| 568 |
|
| 569 |
If supported, set the operating system thread name to |
| 570 |
:attr:`threading.Thread.name`. The name can be truncated depending on the |
| 571 |
operating system thread name limits. |
| 572 |
|
| 573 |
.. versionchanged:: 3.14 |
| 574 |
Set the operating system thread name. |
| 575 |
|
| 576 |
.. method:: run() |
| 577 |
|
| 578 |
Method representing the thread's activity. |
| 579 |
|
| 580 |
You may override this method in a subclass. The standard :meth:`run` |
| 581 |
method invokes the callable object passed to the object's constructor as |
| 582 |
the *target* argument, if any, with positional and keyword arguments taken |
| 583 |
from the *args* and *kwargs* arguments, respectively. |
| 584 |
|
| 585 |
Using list or tuple as the *args* argument which passed to the :class:`Thread` |
| 586 |
could achieve the same effect. |
| 587 |
|
| 588 |
Example:: |
| 589 |
|
| 590 |
>>> from threading import Thread |
| 591 |
>>> t = Thread(target=print, args=[1]) |
| 592 |
>>> t.run() |
| 593 |
1 |
| 594 |
>>> t = Thread(target=print, args=(1,)) |
| 595 |
>>> t.run() |
| 596 |
1 |
| 597 |
|
| 598 |
.. _meth-thread-join: |
| 599 |
|
| 600 |
.. method:: join(timeout=None) |
| 601 |
|
| 602 |
Wait until the thread terminates. This blocks the calling thread until |
| 603 |
the thread whose :meth:`~Thread.join` method is called terminates -- either |
| 604 |
normally or through an unhandled exception -- or until the optional |
| 605 |
timeout occurs. |
| 606 |
|
| 607 |
When the *timeout* argument is present and not ``None``, it should be a |
| 608 |
floating-point number specifying a timeout for the operation in seconds |
| 609 |
(or fractions thereof). As :meth:`~Thread.join` always returns ``None``, |
| 610 |
you must call :meth:`~Thread.is_alive` after :meth:`~Thread.join` to |
| 611 |
decide whether a timeout happened -- if the thread is still alive, the |
| 612 |
:meth:`~Thread.join` call timed out. |
| 613 |
|
| 614 |
When the *timeout* argument is not present or ``None``, the operation will |
| 615 |
block until the thread terminates. |
| 616 |
|
| 617 |
A thread can be joined many times. |
| 618 |
|
| 619 |
:meth:`~Thread.join` raises a :exc:`RuntimeError` if an attempt is made |
| 620 |
to join the current thread as that would cause a deadlock. It is also |
| 621 |
an error to :meth:`~Thread.join` a thread before it has been started |
| 622 |
and attempts to do so raise the same exception. |
| 623 |
|
| 624 |
If an attempt is made to join a running daemonic thread in late stages |
| 625 |
of :term:`Python finalization <interpreter shutdown>` :meth:`!join` |
| 626 |
raises a :exc:`PythonFinalizationError`. |
| 627 |
|
| 628 |
.. versionchanged:: 3.14 |
| 629 |
|
| 630 |
May raise :exc:`PythonFinalizationError`. |
| 631 |
|
| 632 |
.. attribute:: name |
| 633 |
|
| 634 |
A string used for identification purposes only. It has no semantics. |
| 635 |
Multiple threads may be given the same name. The initial name is set by |
| 636 |
the constructor. |
| 637 |
|
| 638 |
On some platforms, the thread name is set at the operating system level |
| 639 |
when the thread starts, so that it is visible in task managers. |
| 640 |
This name may be truncated to fit in a system-specific limit (for example, |
| 641 |
15 bytes on Linux or 63 bytes on macOS). |
| 642 |
|
| 643 |
Changes to *name* are only reflected at the OS level when the currently |
| 644 |
running thread is renamed. (Setting the *name* attribute of a |
| 645 |
different thread only updates the Python Thread object.) |
| 646 |
|
| 647 |
.. method:: getName() |
| 648 |
setName() |
| 649 |
|
| 650 |
Deprecated getter/setter API for :attr:`~Thread.name`; use it directly as a |
| 651 |
property instead. |
| 652 |
|
| 653 |
.. deprecated:: 3.10 |
| 654 |
|
| 655 |
.. attribute:: ident |
| 656 |
|
| 657 |
The 'thread identifier' of this thread or ``None`` if the thread has not |
| 658 |
been started. This is a nonzero integer. See the :func:`get_ident` |
| 659 |
function. Thread identifiers may be recycled when a thread exits and |
| 660 |
another thread is created. The identifier is available even after the |
| 661 |
thread has exited. |
| 662 |
|
| 663 |
.. attribute:: native_id |
| 664 |
|
| 665 |
The Thread ID (``TID``) of this thread, as assigned by the OS (kernel). |
| 666 |
This is a non-negative integer, or ``None`` if the thread has not |
| 667 |
been started. See the :func:`get_native_id` function. |
| 668 |
This value may be used to uniquely identify this particular thread |
| 669 |
system-wide (until the thread terminates, after which the value |
| 670 |
may be recycled by the OS). |
| 671 |
|
| 672 |
.. note:: |
| 673 |
|
| 674 |
Similar to Process IDs, Thread IDs are only valid (guaranteed unique |
| 675 |
system-wide) from the time the thread is created until the thread |
| 676 |
has been terminated. |
| 677 |
|
| 678 |
.. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD. |
| 679 |
|
| 680 |
.. versionadded:: 3.8 |
| 681 |
|
| 682 |
.. method:: is_alive() |
| 683 |
|
| 684 |
Return whether the thread is alive. |
| 685 |
|
| 686 |
This method returns ``True`` just before the :meth:`~Thread.run` method |
| 687 |
starts until just after the :meth:`~Thread.run` method terminates. The |
| 688 |
module function :func:`.enumerate` returns a list of all alive threads. |
| 689 |
|
| 690 |
.. attribute:: daemon |
| 691 |
|
| 692 |
A boolean value indicating whether this thread is a daemon thread (``True``) |
| 693 |
or not (``False``). This must be set before :meth:`~Thread.start` is called, |
| 694 |
otherwise :exc:`RuntimeError` is raised. Its initial value is inherited |
| 695 |
from the creating thread; the main thread is not a daemon thread and |
| 696 |
therefore all threads created in the main thread default to |
| 697 |
:attr:`~Thread.daemon` = ``False``. |
| 698 |
|
| 699 |
The entire Python program exits when no alive non-daemon threads are left. |
| 700 |
|
| 701 |
.. method:: isDaemon() |
| 702 |
setDaemon() |
| 703 |
|
| 704 |
Deprecated getter/setter API for :attr:`~Thread.daemon`; use it directly as a |
| 705 |
property instead. |
| 706 |
|
| 707 |
.. deprecated:: 3.10 |
| 708 |
|
| 709 |
|
| 710 |
.. _lock-objects: |
| 711 |
|
| 712 |
Lock objects |
| 713 |
^^^^^^^^^^^^ |
| 714 |
|
| 715 |
A primitive lock is a synchronization primitive that is not owned by a |
| 716 |
particular thread when locked. In Python, it is currently the lowest level |
| 717 |
synchronization primitive available, implemented directly by the :mod:`_thread` |
| 718 |
extension module. |
| 719 |
|
| 720 |
A primitive lock is in one of two states, "locked" or "unlocked". It is created |
| 721 |
in the unlocked state. It has two basic methods, :meth:`~Lock.acquire` and |
| 722 |
:meth:`~Lock.release`. When the state is unlocked, :meth:`~Lock.acquire` |
| 723 |
changes the state to locked and returns immediately. When the state is locked, |
| 724 |
:meth:`~Lock.acquire` blocks until a call to :meth:`~Lock.release` in another |
| 725 |
thread changes it to unlocked, then the :meth:`~Lock.acquire` call resets it |
| 726 |
to locked and returns. The :meth:`~Lock.release` method should only be |
| 727 |
called in the locked state; it changes the state to unlocked and returns |
| 728 |
immediately. If an attempt is made to release an unlocked lock, a |
| 729 |
:exc:`RuntimeError` will be raised. |
| 730 |
|
| 731 |
Locks also support the :ref:`context management protocol <with-locks>`. |
| 732 |
|
| 733 |
When more than one thread is blocked in :meth:`~Lock.acquire` waiting for the |
| 734 |
state to turn to unlocked, only one thread proceeds when a :meth:`~Lock.release` |
| 735 |
call resets the state to unlocked; which one of the waiting threads proceeds |
| 736 |
is not defined, and may vary across implementations. |
| 737 |
|
| 738 |
All methods are executed atomically. |
| 739 |
|
| 740 |
|
| 741 |
.. class:: Lock() |
| 742 |
|
| 743 |
The class implementing primitive lock objects. Once a thread has acquired a |
| 744 |
lock, subsequent attempts to acquire it block, until it is released; any |
| 745 |
thread may release it. |
| 746 |
|
| 747 |
.. versionchanged:: 3.13 |
| 748 |
``Lock`` is now a class. In earlier Pythons, ``Lock`` was a factory |
| 749 |
function which returned an instance of the underlying private lock |
| 750 |
type. |
| 751 |
|
| 752 |
|
| 753 |
.. method:: acquire(blocking=True, timeout=-1) |
| 754 |
|
| 755 |
Acquire a lock, blocking or non-blocking. |
| 756 |
|
| 757 |
When invoked with the *blocking* argument set to ``True`` (the default), |
| 758 |
block until the lock is unlocked, then set it to locked and return ``True``. |
| 759 |
|
| 760 |
When invoked with the *blocking* argument set to ``False``, do not block. |
| 761 |
If a call with *blocking* set to ``True`` would block, return ``False`` |
| 762 |
immediately; otherwise, set the lock to locked and return ``True``. |
| 763 |
|
| 764 |
When invoked with the floating-point *timeout* argument set to a positive |
| 765 |
value, block for at most the number of seconds specified by *timeout* |
| 766 |
and as long as the lock cannot be acquired. A *timeout* argument of ``-1`` |
| 767 |
specifies an unbounded wait. It is forbidden to specify a *timeout* |
| 768 |
when *blocking* is ``False``. |
| 769 |
|
| 770 |
The return value is ``True`` if the lock is acquired successfully, |
| 771 |
``False`` if not (for example if the *timeout* expired). |
| 772 |
|
| 773 |
.. versionchanged:: 3.2 |
| 774 |
The *timeout* parameter is new. |
| 775 |
|
| 776 |
.. versionchanged:: 3.2 |
| 777 |
Lock acquisition can now be interrupted by signals on POSIX if the |
| 778 |
underlying threading implementation supports it. |
| 779 |
|
| 780 |
.. versionchanged:: 3.14 |
| 781 |
Lock acquisition can now be interrupted by signals on Windows. |
| 782 |
|
| 783 |
|
| 784 |
.. method:: release() |
| 785 |
|
| 786 |
Release a lock. This can be called from any thread, not only the thread |
| 787 |
which has acquired the lock. |
| 788 |
|
| 789 |
When the lock is locked, reset it to unlocked, and return. If any other threads |
| 790 |
are blocked waiting for the lock to become unlocked, allow exactly one of them |
| 791 |
to proceed. |
| 792 |
|
| 793 |
When invoked on an unlocked lock, a :exc:`RuntimeError` is raised. |
| 794 |
|
| 795 |
There is no return value. |
| 796 |
|
| 797 |
.. method:: locked() |
| 798 |
|
| 799 |
Return ``True`` if the lock is acquired. |
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
.. _rlock-objects: |
| 804 |
|
| 805 |
RLock objects |
| 806 |
^^^^^^^^^^^^^ |
| 807 |
|
| 808 |
A reentrant lock is a synchronization primitive that may be acquired multiple |
| 809 |
times by the same thread. Internally, it uses the concepts of "owning thread" |
| 810 |
and "recursion level" in addition to the locked/unlocked state used by primitive |
| 811 |
locks. In the locked state, some thread owns the lock; in the unlocked state, |
| 812 |
no thread owns it. |
| 813 |
|
| 814 |
Threads call a lock's :meth:`~RLock.acquire` method to lock it, |
| 815 |
and its :meth:`~Lock.release` method to unlock it. |
| 816 |
|
| 817 |
.. note:: |
| 818 |
|
| 819 |
Reentrant locks support the :ref:`context management protocol <with-locks>`, |
| 820 |
so it is recommended to use :keyword:`with` instead of manually calling |
| 821 |
:meth:`~RLock.acquire` and :meth:`~RLock.release` |
| 822 |
to handle acquiring and releasing the lock for a block of code. |
| 823 |
|
| 824 |
RLock's :meth:`~RLock.acquire`/:meth:`~RLock.release` call pairs may be nested, |
| 825 |
unlike Lock's :meth:`~Lock.acquire`/:meth:`~Lock.release`. Only the final |
| 826 |
:meth:`~RLock.release` (the :meth:`~Lock.release` of the outermost pair) resets |
| 827 |
the lock to an unlocked state and allows another thread blocked in |
| 828 |
:meth:`~RLock.acquire` to proceed. |
| 829 |
|
| 830 |
:meth:`~RLock.acquire`/:meth:`~RLock.release` must be used in pairs: each acquire |
| 831 |
must have a release in the thread that has acquired the lock. Failing to |
| 832 |
call release as many times the lock has been acquired can lead to deadlock. |
| 833 |
|
| 834 |
|
| 835 |
.. class:: RLock() |
| 836 |
|
| 837 |
This class implements reentrant lock objects. A reentrant lock must be |
| 838 |
released by the thread that acquired it. Once a thread has acquired a |
| 839 |
reentrant lock, the same thread may acquire it again without blocking; the |
| 840 |
thread must release it once for each time it has acquired it. |
| 841 |
|
| 842 |
Note that ``RLock`` is actually a factory function which returns an instance |
| 843 |
of the most efficient version of the concrete RLock class that is supported |
| 844 |
by the platform. |
| 845 |
|
| 846 |
|
| 847 |
.. method:: acquire(blocking=True, timeout=-1) |
| 848 |
|
| 849 |
Acquire a lock, blocking or non-blocking. |
| 850 |
|
| 851 |
.. seealso:: |
| 852 |
|
| 853 |
:ref:`Using RLock as a context manager <with-locks>` |
| 854 |
Recommended over manual :meth:`!acquire` and :meth:`release` calls |
| 855 |
whenever practical. |
| 856 |
|
| 857 |
|
| 858 |
When invoked with the *blocking* argument set to ``True`` (the default): |
| 859 |
|
| 860 |
* If no thread owns the lock, acquire the lock and return immediately. |
| 861 |
|
| 862 |
* If another thread owns the lock, block until we are able to acquire |
| 863 |
lock, or *timeout*, if set to a positive float value. |
| 864 |
|
| 865 |
* If the same thread owns the lock, acquire the lock again, and |
| 866 |
return immediately. This is the difference between :class:`Lock` and |
| 867 |
:class:`!RLock`; :class:`Lock` handles this case the same as the previous, |
| 868 |
blocking until the lock can be acquired. |
| 869 |
|
| 870 |
When invoked with the *blocking* argument set to ``False``: |
| 871 |
|
| 872 |
* If no thread owns the lock, acquire the lock and return immediately. |
| 873 |
|
| 874 |
* If another thread owns the lock, return immediately. |
| 875 |
|
| 876 |
* If the same thread owns the lock, acquire the lock again and return |
| 877 |
immediately. |
| 878 |
|
| 879 |
In all cases, if the thread was able to acquire the lock, return ``True``. |
| 880 |
If the thread was unable to acquire the lock (i.e. if not blocking or |
| 881 |
the timeout was reached) return ``False``. |
| 882 |
|
| 883 |
If called multiple times, failing to call :meth:`~RLock.release` as many times |
| 884 |
may lead to deadlock. Consider using :class:`!RLock` as a context manager rather than |
| 885 |
calling acquire/release directly. |
| 886 |
|
| 887 |
.. versionchanged:: 3.2 |
| 888 |
The *timeout* parameter is new. |
| 889 |
|
| 890 |
|
| 891 |
.. method:: release() |
| 892 |
|
| 893 |
Release a lock, decrementing the recursion level. If after the decrement it is |
| 894 |
zero, reset the lock to unlocked (not owned by any thread), and if any other |
| 895 |
threads are blocked waiting for the lock to become unlocked, allow exactly one |
| 896 |
of them to proceed. If after the decrement the recursion level is still |
| 897 |
nonzero, the lock remains locked and owned by the calling thread. |
| 898 |
|
| 899 |
Only call this method when the calling thread owns the lock. A |
| 900 |
:exc:`RuntimeError` is raised if this method is called when the lock is |
| 901 |
not acquired. |
| 902 |
|
| 903 |
There is no return value. |
| 904 |
|
| 905 |
|
| 906 |
.. method:: locked() |
| 907 |
|
| 908 |
Return a boolean indicating whether this object is locked right now. |
| 909 |
|
| 910 |
.. versionadded:: 3.14 |
| 911 |
|
| 912 |
|
| 913 |
.. _condition-objects: |
| 914 |
|
| 915 |
Condition objects |
| 916 |
^^^^^^^^^^^^^^^^^ |
| 917 |
|
| 918 |
A condition variable is always associated with some kind of lock; this can be |
| 919 |
passed in or one will be created by default. Passing one in is useful when |
| 920 |
several condition variables must share the same lock. The lock is part of |
| 921 |
the condition object: you don't have to track it separately. |
| 922 |
|
| 923 |
A condition variable obeys the :ref:`context management protocol <with-locks>`: |
| 924 |
using the ``with`` statement acquires the associated lock for the duration of |
| 925 |
the enclosed block. The :meth:`~Condition.acquire` and |
| 926 |
:meth:`~Condition.release` methods also call the corresponding methods of |
| 927 |
the associated lock. |
| 928 |
|
| 929 |
Other methods must be called with the associated lock held. The |
| 930 |
:meth:`~Condition.wait` method releases the lock, and then blocks until |
| 931 |
another thread awakens it by calling :meth:`~Condition.notify` or |
| 932 |
:meth:`~Condition.notify_all`. Once awakened, :meth:`~Condition.wait` |
| 933 |
re-acquires the lock and returns. It is also possible to specify a timeout. |
| 934 |
|
| 935 |
The :meth:`~Condition.notify` method wakes up one of the threads waiting for |
| 936 |
the condition variable, if any are waiting. The :meth:`~Condition.notify_all` |
| 937 |
method wakes up all threads waiting for the condition variable. |
| 938 |
|
| 939 |
Note: the :meth:`~Condition.notify` and :meth:`~Condition.notify_all` methods |
| 940 |
don't release the lock; this means that the thread or threads awakened will |
| 941 |
not return from their :meth:`~Condition.wait` call immediately, but only when |
| 942 |
the thread that called :meth:`~Condition.notify` or :meth:`~Condition.notify_all` |
| 943 |
finally relinquishes ownership of the lock. |
| 944 |
|
| 945 |
The typical programming style using condition variables uses the lock to |
| 946 |
synchronize access to some shared state; threads that are interested in a |
| 947 |
particular change of state call :meth:`~Condition.wait` repeatedly until they |
| 948 |
see the desired state, while threads that modify the state call |
| 949 |
:meth:`~Condition.notify` or :meth:`~Condition.notify_all` when they change |
| 950 |
the state in such a way that it could possibly be a desired state for one |
| 951 |
of the waiters. For example, the following code is a generic |
| 952 |
producer-consumer situation with unlimited buffer capacity:: |
| 953 |
|
| 954 |
# Consume one item |
| 955 |
with cv: |
| 956 |
while not an_item_is_available(): |
| 957 |
cv.wait() |
| 958 |
get_an_available_item() |
| 959 |
|
| 960 |
# Produce one item |
| 961 |
with cv: |
| 962 |
make_an_item_available() |
| 963 |
cv.notify() |
| 964 |
|
| 965 |
The ``while`` loop checking for the application's condition is necessary |
| 966 |
because :meth:`~Condition.wait` can return after an arbitrary long time, |
| 967 |
and the condition which prompted the :meth:`~Condition.notify` call may |
| 968 |
no longer hold true. This is inherent to multi-threaded programming. The |
| 969 |
:meth:`~Condition.wait_for` method can be used to automate the condition |
| 970 |
checking, and eases the computation of timeouts:: |
| 971 |
|
| 972 |
# Consume an item |
| 973 |
with cv: |
| 974 |
cv.wait_for(an_item_is_available) |
| 975 |
get_an_available_item() |
| 976 |
|
| 977 |
To choose between :meth:`~Condition.notify` and :meth:`~Condition.notify_all`, |
| 978 |
consider whether one state change can be interesting for only one or several |
| 979 |
waiting threads. E.g. in a typical producer-consumer situation, adding one |
| 980 |
item to the buffer only needs to wake up one consumer thread. |
| 981 |
|
| 982 |
|
| 983 |
.. class:: Condition(lock=None) |
| 984 |
|
| 985 |
This class implements condition variable objects. A condition variable |
| 986 |
allows one or more threads to wait until they are notified by another thread. |
| 987 |
|
| 988 |
If the *lock* argument is given and not ``None``, it must be a :class:`Lock` |
| 989 |
or :class:`RLock` object, and it is used as the underlying lock. Otherwise, |
| 990 |
a new :class:`RLock` object is created and used as the underlying lock. |
| 991 |
|
| 992 |
.. versionchanged:: 3.3 |
| 993 |
changed from a factory function to a class. |
| 994 |
|
| 995 |
.. method:: acquire(*args) |
| 996 |
|
| 997 |
Acquire the underlying lock. This method calls the corresponding method on |
| 998 |
the underlying lock; the return value is whatever that method returns. |
| 999 |
|
| 1000 |
.. method:: release() |
| 1001 |
|
| 1002 |
Release the underlying lock. This method calls the corresponding method on |
| 1003 |
the underlying lock; there is no return value. |
| 1004 |
|
| 1005 |
.. method:: locked() |
| 1006 |
|
| 1007 |
Return a boolean indicating whether this object is locked right now. |
| 1008 |
|
| 1009 |
.. versionadded:: 3.14 |
| 1010 |
|
| 1011 |
.. method:: wait(timeout=None) |
| 1012 |
|
| 1013 |
Wait until notified or until a timeout occurs. If the calling thread has |
| 1014 |
not acquired the lock when this method is called, a :exc:`RuntimeError` is |
| 1015 |
raised. |
| 1016 |
|
| 1017 |
This method releases the underlying lock, and then blocks until it is |
| 1018 |
awakened by a :meth:`notify` or :meth:`notify_all` call for the same |
| 1019 |
condition variable in another thread, or until the optional timeout |
| 1020 |
occurs. Once awakened or timed out, it re-acquires the lock and returns. |
| 1021 |
|
| 1022 |
When the *timeout* argument is present and not ``None``, it should be a |
| 1023 |
floating-point number specifying a timeout for the operation in seconds |
| 1024 |
(or fractions thereof). |
| 1025 |
|
| 1026 |
When the underlying lock is an :class:`RLock`, it is not released using |
| 1027 |
its :meth:`release` method, since this may not actually unlock the lock |
| 1028 |
when it was acquired multiple times recursively. Instead, an internal |
| 1029 |
interface of the :class:`RLock` class is used, which really unlocks it |
| 1030 |
even when it has been recursively acquired several times. Another internal |
| 1031 |
interface is then used to restore the recursion level when the lock is |
| 1032 |
reacquired. |
| 1033 |
|
| 1034 |
The return value is ``True`` unless a given *timeout* expired, in which |
| 1035 |
case it is ``False``. |
| 1036 |
|
| 1037 |
.. versionchanged:: 3.2 |
| 1038 |
Previously, the method always returned ``None``. |
| 1039 |
|
| 1040 |
.. method:: wait_for(predicate, timeout=None) |
| 1041 |
|
| 1042 |
Wait until a condition evaluates to true. *predicate* should be a |
| 1043 |
callable which result will be interpreted as a boolean value. |
| 1044 |
A *timeout* may be provided giving the maximum time to wait. |
| 1045 |
|
| 1046 |
This utility method may call :meth:`wait` repeatedly until the predicate |
| 1047 |
is satisfied, or until a timeout occurs. The return value is |
| 1048 |
the last return value of the predicate and will evaluate to |
| 1049 |
``False`` if the method timed out. |
| 1050 |
|
| 1051 |
Ignoring the timeout feature, calling this method is roughly equivalent to |
| 1052 |
writing:: |
| 1053 |
|
| 1054 |
while not predicate(): |
| 1055 |
cv.wait() |
| 1056 |
|
| 1057 |
Therefore, the same rules apply as with :meth:`wait`: The lock must be |
| 1058 |
held when called and is re-acquired on return. The predicate is evaluated |
| 1059 |
with the lock held. |
| 1060 |
|
| 1061 |
.. versionadded:: 3.2 |
| 1062 |
|
| 1063 |
.. method:: notify(n=1) |
| 1064 |
|
| 1065 |
By default, wake up one thread waiting on this condition, if any. If the |
| 1066 |
calling thread has not acquired the lock when this method is called, a |
| 1067 |
:exc:`RuntimeError` is raised. |
| 1068 |
|
| 1069 |
This method wakes up at most *n* of the threads waiting for the condition |
| 1070 |
variable; it is a no-op if no threads are waiting. |
| 1071 |
|
| 1072 |
The current implementation wakes up exactly *n* threads, if at least *n* |
| 1073 |
threads are waiting. However, it's not safe to rely on this behavior. |
| 1074 |
A future, optimized implementation may occasionally wake up more than |
| 1075 |
*n* threads. |
| 1076 |
|
| 1077 |
Note: an awakened thread does not actually return from its :meth:`wait` |
| 1078 |
call until it can reacquire the lock. Since :meth:`notify` does not |
| 1079 |
release the lock, its caller should. |
| 1080 |
|
| 1081 |
.. method:: notify_all() |
| 1082 |
|
| 1083 |
Wake up all threads waiting on this condition. This method acts like |
| 1084 |
:meth:`notify`, but wakes up all waiting threads instead of one. If the |
| 1085 |
calling thread has not acquired the lock when this method is called, a |
| 1086 |
:exc:`RuntimeError` is raised. |
| 1087 |
|
| 1088 |
The method ``notifyAll`` is a deprecated alias for this method. |
| 1089 |
|
| 1090 |
|
| 1091 |
.. _semaphore-objects: |
| 1092 |
|
| 1093 |
Semaphore objects |
| 1094 |
^^^^^^^^^^^^^^^^^ |
| 1095 |
|
| 1096 |
This is one of the oldest synchronization primitives in the history of computer |
| 1097 |
science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he |
| 1098 |
used the names ``P()`` and ``V()`` instead of :meth:`~Semaphore.acquire` and |
| 1099 |
:meth:`~Semaphore.release`). |
| 1100 |
|
| 1101 |
A semaphore manages an internal counter which is decremented by each |
| 1102 |
:meth:`~Semaphore.acquire` call and incremented by each :meth:`~Semaphore.release` |
| 1103 |
call. The counter can never go below zero; when :meth:`~Semaphore.acquire` |
| 1104 |
finds that it is zero, it blocks, waiting until some other thread calls |
| 1105 |
:meth:`~Semaphore.release`. |
| 1106 |
|
| 1107 |
Semaphores also support the :ref:`context management protocol <with-locks>`. |
| 1108 |
|
| 1109 |
|
| 1110 |
.. class:: Semaphore(value=1) |
| 1111 |
|
| 1112 |
This class implements semaphore objects. A semaphore manages an atomic |
| 1113 |
counter representing the number of :meth:`release` calls minus the number of |
| 1114 |
:meth:`acquire` calls, plus an initial value. The :meth:`acquire` method |
| 1115 |
blocks if necessary until it can return without making the counter negative. |
| 1116 |
If not given, *value* defaults to 1. |
| 1117 |
|
| 1118 |
The optional argument gives the initial *value* for the internal counter; it |
| 1119 |
defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is |
| 1120 |
raised. |
| 1121 |
|
| 1122 |
.. versionchanged:: 3.3 |
| 1123 |
changed from a factory function to a class. |
| 1124 |
|
| 1125 |
.. method:: acquire(blocking=True, timeout=None) |
| 1126 |
|
| 1127 |
Acquire a semaphore. |
| 1128 |
|
| 1129 |
When invoked without arguments: |
| 1130 |
|
| 1131 |
* If the internal counter is larger than zero on entry, decrement it by |
| 1132 |
one and return ``True`` immediately. |
| 1133 |
* If the internal counter is zero on entry, block until awoken by a call to |
| 1134 |
:meth:`~Semaphore.release`. Once awoken (and the counter is greater |
| 1135 |
than 0), decrement the counter by 1 and return ``True``. Exactly one |
| 1136 |
thread will be awoken by each call to :meth:`~Semaphore.release`. The |
| 1137 |
order in which threads are awoken should not be relied on. |
| 1138 |
|
| 1139 |
When invoked with *blocking* set to ``False``, do not block. If a call |
| 1140 |
without an argument would block, return ``False`` immediately; otherwise, do |
| 1141 |
the same thing as when called without arguments, and return ``True``. |
| 1142 |
|
| 1143 |
When invoked with a *timeout* other than ``None``, it will block for at |
| 1144 |
most *timeout* seconds. If acquire does not complete successfully in |
| 1145 |
that interval, return ``False``. Return ``True`` otherwise. |
| 1146 |
|
| 1147 |
.. versionchanged:: 3.2 |
| 1148 |
The *timeout* parameter is new. |
| 1149 |
|
| 1150 |
.. method:: release(n=1) |
| 1151 |
|
| 1152 |
Release a semaphore, incrementing the internal counter by *n*. When it |
| 1153 |
was zero on entry and other threads are waiting for it to become larger |
| 1154 |
than zero again, wake up *n* of those threads. |
| 1155 |
|
| 1156 |
.. versionchanged:: 3.9 |
| 1157 |
Added the *n* parameter to release multiple waiting threads at once. |
| 1158 |
|
| 1159 |
|
| 1160 |
.. class:: BoundedSemaphore(value=1) |
| 1161 |
|
| 1162 |
Class implementing bounded semaphore objects. A bounded semaphore checks to |
| 1163 |
make sure its current value doesn't exceed its initial value. If it does, |
| 1164 |
:exc:`ValueError` is raised. In most situations semaphores are used to guard |
| 1165 |
resources with limited capacity. If the semaphore is released too many times |
| 1166 |
it's a sign of a bug. If not given, *value* defaults to 1. |
| 1167 |
|
| 1168 |
.. versionchanged:: 3.3 |
| 1169 |
changed from a factory function to a class. |
| 1170 |
|
| 1171 |
|
| 1172 |
.. _semaphore-examples: |
| 1173 |
|
| 1174 |
:class:`Semaphore` example |
| 1175 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1176 |
|
| 1177 |
Semaphores are often used to guard resources with limited capacity, for example, |
| 1178 |
a database server. In any situation where the size of the resource is fixed, |
| 1179 |
you should use a bounded semaphore. Before spawning any worker threads, your |
| 1180 |
main thread would initialize the semaphore:: |
| 1181 |
|
| 1182 |
maxconnections = 5 |
| 1183 |
# ... |
| 1184 |
pool_sema = BoundedSemaphore(value=maxconnections) |
| 1185 |
|
| 1186 |
Once spawned, worker threads call the semaphore's acquire and release methods |
| 1187 |
when they need to connect to the server:: |
| 1188 |
|
| 1189 |
with pool_sema: |
| 1190 |
conn = connectdb() |
| 1191 |
try: |
| 1192 |
# ... use connection ... |
| 1193 |
finally: |
| 1194 |
conn.close() |
| 1195 |
|
| 1196 |
The use of a bounded semaphore reduces the chance that a programming error which |
| 1197 |
causes the semaphore to be released more than it's acquired will go undetected. |
| 1198 |
|
| 1199 |
|
| 1200 |
.. _event-objects: |
| 1201 |
|
| 1202 |
Event objects |
| 1203 |
^^^^^^^^^^^^^ |
| 1204 |
|
| 1205 |
This is one of the simplest mechanisms for communication between threads: one |
| 1206 |
thread signals an event and other threads wait for it. |
| 1207 |
|
| 1208 |
An event object manages an internal flag that can be set to true with the |
| 1209 |
:meth:`~Event.set` method and reset to false with the :meth:`~Event.clear` |
| 1210 |
method. The :meth:`~Event.wait` method blocks until the flag is true. |
| 1211 |
|
| 1212 |
|
| 1213 |
.. class:: Event() |
| 1214 |
|
| 1215 |
Class implementing event objects. An event manages a flag that can be set to |
| 1216 |
true with the :meth:`~Event.set` method and reset to false with the |
| 1217 |
:meth:`clear` method. The :meth:`wait` method blocks until the flag is true. |
| 1218 |
The flag is initially false. |
| 1219 |
|
| 1220 |
.. versionchanged:: 3.3 |
| 1221 |
changed from a factory function to a class. |
| 1222 |
|
| 1223 |
.. method:: is_set() |
| 1224 |
|
| 1225 |
Return ``True`` if and only if the internal flag is true. |
| 1226 |
|
| 1227 |
The method ``isSet`` is a deprecated alias for this method. |
| 1228 |
|
| 1229 |
.. method:: set() |
| 1230 |
|
| 1231 |
Set the internal flag to true. All threads waiting for it to become true |
| 1232 |
are awakened. Threads that call :meth:`wait` once the flag is true will |
| 1233 |
not block at all. |
| 1234 |
|
| 1235 |
.. method:: clear() |
| 1236 |
|
| 1237 |
Reset the internal flag to false. Subsequently, threads calling |
| 1238 |
:meth:`wait` will block until :meth:`.set` is called to set the internal |
| 1239 |
flag to true again. |
| 1240 |
|
| 1241 |
.. method:: wait(timeout=None) |
| 1242 |
|
| 1243 |
Block as long as the internal flag is false and the timeout, if given, |
| 1244 |
has not expired. The return value represents the |
| 1245 |
reason that this blocking method returned; ``True`` if returning because |
| 1246 |
the internal flag is set to true, or ``False`` if a timeout is given and |
| 1247 |
the internal flag did not become true within the given wait time. |
| 1248 |
|
| 1249 |
When the timeout argument is present and not ``None``, it should be a |
| 1250 |
floating-point number specifying a timeout for the operation in seconds, |
| 1251 |
or fractions thereof. |
| 1252 |
|
| 1253 |
.. versionchanged:: 3.1 |
| 1254 |
Previously, the method always returned ``None``. |
| 1255 |
|
| 1256 |
|
| 1257 |
.. _timer-objects: |
| 1258 |
|
| 1259 |
Timer objects |
| 1260 |
^^^^^^^^^^^^^ |
| 1261 |
|
| 1262 |
This class represents an action that should be run only after a certain amount |
| 1263 |
of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread` |
| 1264 |
and as such also functions as an example of creating custom threads. |
| 1265 |
|
| 1266 |
Timers are started, as with threads, by calling their :meth:`Timer.start <Thread.start>` |
| 1267 |
method. The timer can be stopped (before its action has begun) by calling the |
| 1268 |
:meth:`~Timer.cancel` method. The interval the timer will wait before |
| 1269 |
executing its action may not be exactly the same as the interval specified by |
| 1270 |
the user. |
| 1271 |
|
| 1272 |
For example:: |
| 1273 |
|
| 1274 |
def hello(): |
| 1275 |
print("hello, world") |
| 1276 |
|
| 1277 |
t = Timer(30.0, hello) |
| 1278 |
t.start() # after 30 seconds, "hello, world" will be printed |
| 1279 |
|
| 1280 |
|
| 1281 |
.. class:: Timer(interval, function, args=None, kwargs=None) |
| 1282 |
|
| 1283 |
Create a timer that will run *function* with arguments *args* and keyword |
| 1284 |
arguments *kwargs*, after *interval* seconds have passed. |
| 1285 |
If *args* is ``None`` (the default) then an empty list will be used. |
| 1286 |
If *kwargs* is ``None`` (the default) then an empty dict will be used. |
| 1287 |
|
| 1288 |
.. versionchanged:: 3.3 |
| 1289 |
changed from a factory function to a class. |
| 1290 |
|
| 1291 |
.. method:: cancel() |
| 1292 |
|
| 1293 |
Stop the timer, and cancel the execution of the timer's action. This will |
| 1294 |
only work if the timer is still in its waiting stage. |
| 1295 |
|
| 1296 |
|
| 1297 |
Barrier objects |
| 1298 |
^^^^^^^^^^^^^^^ |
| 1299 |
|
| 1300 |
.. versionadded:: 3.2 |
| 1301 |
|
| 1302 |
This class provides a simple synchronization primitive for use by a fixed number |
| 1303 |
of threads that need to wait for each other. Each of the threads tries to pass |
| 1304 |
the barrier by calling the :meth:`~Barrier.wait` method and will block until |
| 1305 |
all of the threads have made their :meth:`~Barrier.wait` calls. At this point, |
| 1306 |
the threads are released simultaneously. |
| 1307 |
|
| 1308 |
The barrier can be reused any number of times for the same number of threads. |
| 1309 |
|
| 1310 |
As an example, here is a simple way to synchronize a client and server thread:: |
| 1311 |
|
| 1312 |
b = Barrier(2, timeout=5) |
| 1313 |
|
| 1314 |
def server(): |
| 1315 |
start_server() |
| 1316 |
b.wait() |
| 1317 |
while True: |
| 1318 |
connection = accept_connection() |
| 1319 |
process_server_connection(connection) |
| 1320 |
|
| 1321 |
def client(): |
| 1322 |
b.wait() |
| 1323 |
while True: |
| 1324 |
connection = make_connection() |
| 1325 |
process_client_connection(connection) |
| 1326 |
|
| 1327 |
|
| 1328 |
.. class:: Barrier(parties, action=None, timeout=None) |
| 1329 |
|
| 1330 |
Create a barrier object for *parties* number of threads. An *action*, when |
| 1331 |
provided, is a callable to be called by one of the threads when they are |
| 1332 |
released. *timeout* is the default timeout value if none is specified for |
| 1333 |
the :meth:`wait` method. |
| 1334 |
|
| 1335 |
.. method:: wait(timeout=None) |
| 1336 |
|
| 1337 |
Pass the barrier. When all the threads party to the barrier have called |
| 1338 |
this function, they are all released simultaneously. If a *timeout* is |
| 1339 |
provided, it is used in preference to any that was supplied to the class |
| 1340 |
constructor. |
| 1341 |
|
| 1342 |
The return value is an integer in the range 0 to *parties* -- 1, different |
| 1343 |
for each thread. This can be used to select a thread to do some special |
| 1344 |
housekeeping, e.g.:: |
| 1345 |
|
| 1346 |
i = barrier.wait() |
| 1347 |
if i == 0: |
| 1348 |
# Only one thread needs to print this |
| 1349 |
print("passed the barrier") |
| 1350 |
|
| 1351 |
If an *action* was provided to the constructor, one of the threads will |
| 1352 |
have called it prior to being released. Should this call raise an error, |
| 1353 |
the barrier is put into the broken state. |
| 1354 |
|
| 1355 |
If the call times out, the barrier is put into the broken state. |
| 1356 |
|
| 1357 |
This method may raise a :class:`BrokenBarrierError` exception if the |
| 1358 |
barrier is broken or reset while a thread is waiting. |
| 1359 |
|
| 1360 |
.. method:: reset() |
| 1361 |
|
| 1362 |
Return the barrier to the default, empty state. Any threads waiting on it |
| 1363 |
will receive the :class:`BrokenBarrierError` exception. |
| 1364 |
|
| 1365 |
Note that using this function may require some external |
| 1366 |
synchronization if there are other threads whose state is unknown. If a |
| 1367 |
barrier is broken it may be better to just leave it and create a new one. |
| 1368 |
|
| 1369 |
.. method:: abort() |
| 1370 |
|
| 1371 |
Put the barrier into a broken state. This causes any active or future |
| 1372 |
calls to :meth:`wait` to fail with the :class:`BrokenBarrierError`. Use |
| 1373 |
this for example if one of the threads needs to abort, to avoid deadlocking the |
| 1374 |
application. |
| 1375 |
|
| 1376 |
It may be preferable to simply create the barrier with a sensible |
| 1377 |
*timeout* value to automatically guard against one of the threads going |
| 1378 |
awry. |
| 1379 |
|
| 1380 |
.. attribute:: parties |
| 1381 |
|
| 1382 |
The number of threads required to pass the barrier. |
| 1383 |
|
| 1384 |
.. attribute:: n_waiting |
| 1385 |
|
| 1386 |
The number of threads currently waiting in the barrier. |
| 1387 |
|
| 1388 |
.. attribute:: broken |
| 1389 |
|
| 1390 |
A boolean that is ``True`` if the barrier is in the broken state. |
| 1391 |
|
| 1392 |
|
| 1393 |
.. exception:: BrokenBarrierError |
| 1394 |
|
| 1395 |
This exception, a subclass of :exc:`RuntimeError`, is raised when the |
| 1396 |
:class:`Barrier` object is reset or broken. |
| 1397 |
|
| 1398 |
|
| 1399 |
.. _with-locks: |
| 1400 |
|
| 1401 |
Using locks, conditions, and semaphores in the :keyword:`!with` statement |
| 1402 |
------------------------------------------------------------------------- |
| 1403 |
|
| 1404 |
All of the objects provided by this module that have ``acquire`` and |
| 1405 |
``release`` methods can be used as context managers for a :keyword:`with` |
| 1406 |
statement. The ``acquire`` method will be called when the block is |
| 1407 |
entered, and ``release`` will be called when the block is exited. Hence, |
| 1408 |
the following snippet:: |
| 1409 |
|
| 1410 |
with some_lock: |
| 1411 |
# do something... |
| 1412 |
|
| 1413 |
is equivalent to:: |
| 1414 |
|
| 1415 |
some_lock.acquire() |
| 1416 |
try: |
| 1417 |
# do something... |
| 1418 |
finally: |
| 1419 |
some_lock.release() |
| 1420 |
|
| 1421 |
Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`, |
| 1422 |
:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as |
| 1423 |
:keyword:`with` statement context managers. |