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