Debian Codegraph @

Doc/library/threading.rst

raw
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, experimental :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)
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 If the subclass overrides the constructor, it must make sure to invoke the
536 base class constructor (``Thread.__init__()``) before doing anything else to
537 the thread.
538
539 .. versionchanged:: 3.3
540 Added the *daemon* parameter.
541
542 .. versionchanged:: 3.10
543 Use the *target* name if *name* argument is omitted.
544
545 .. method:: start()
546
547 Start the thread's activity.
548
549 It must be called at most once per thread object. It arranges for the
550 object's :meth:`~Thread.run` method to be invoked in a separate thread
551 of control.
552
553 This method will raise a :exc:`RuntimeError` if called more than once
554 on the same thread object.
555
556 .. method:: run()
557
558 Method representing the thread's activity.
559
560 You may override this method in a subclass. The standard :meth:`run`
561 method invokes the callable object passed to the object's constructor as
562 the *target* argument, if any, with positional and keyword arguments taken
563 from the *args* and *kwargs* arguments, respectively.
564
565 Using list or tuple as the *args* argument which passed to the :class:`Thread`
566 could achieve the same effect.
567
568 Example::
569
570 >>> from threading import Thread
571 >>> t = Thread(target=print, args=[1])
572 >>> t.run()
573 1
574 >>> t = Thread(target=print, args=(1,))
575 >>> t.run()
576 1
577
578 .. _meth-thread-join:
579
580 .. method:: join(timeout=None)
581
582 Wait until the thread terminates. This blocks the calling thread until
583 the thread whose :meth:`~Thread.join` method is called terminates -- either
584 normally or through an unhandled exception -- or until the optional
585 timeout occurs.
586
587 When the *timeout* argument is present and not ``None``, it should be a
588 floating-point number specifying a timeout for the operation in seconds
589 (or fractions thereof). As :meth:`~Thread.join` always returns ``None``,
590 you must call :meth:`~Thread.is_alive` after :meth:`~Thread.join` to
591 decide whether a timeout happened -- if the thread is still alive, the
592 :meth:`~Thread.join` call timed out.
593
594 When the *timeout* argument is not present or ``None``, the operation will
595 block until the thread terminates.
596
597 A thread can be joined many times.
598
599 :meth:`~Thread.join` raises a :exc:`RuntimeError` if an attempt is made
600 to join the current thread as that would cause a deadlock. It is also
601 an error to :meth:`~Thread.join` a thread before it has been started
602 and attempts to do so raise the same exception.
603
604 .. attribute:: name
605
606 A string used for identification purposes only. It has no semantics.
607 Multiple threads may be given the same name. The initial name is set by
608 the constructor.
609
610 .. method:: getName()
611 setName()
612
613 Deprecated getter/setter API for :attr:`~Thread.name`; use it directly as a
614 property instead.
615
616 .. deprecated:: 3.10
617
618 .. attribute:: ident
619
620 The 'thread identifier' of this thread or ``None`` if the thread has not
621 been started. This is a nonzero integer. See the :func:`get_ident`
622 function. Thread identifiers may be recycled when a thread exits and
623 another thread is created. The identifier is available even after the
624 thread has exited.
625
626 .. attribute:: native_id
627
628 The Thread ID (``TID``) of this thread, as assigned by the OS (kernel).
629 This is a non-negative integer, or ``None`` if the thread has not
630 been started. See the :func:`get_native_id` function.
631 This value may be used to uniquely identify this particular thread
632 system-wide (until the thread terminates, after which the value
633 may be recycled by the OS).
634
635 .. note::
636
637 Similar to Process IDs, Thread IDs are only valid (guaranteed unique
638 system-wide) from the time the thread is created until the thread
639 has been terminated.
640
641 .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.
642
643 .. versionadded:: 3.8
644
645 .. method:: is_alive()
646
647 Return whether the thread is alive.
648
649 This method returns ``True`` just before the :meth:`~Thread.run` method
650 starts until just after the :meth:`~Thread.run` method terminates. The
651 module function :func:`.enumerate` returns a list of all alive threads.
652
653 .. attribute:: daemon
654
655 A boolean value indicating whether this thread is a daemon thread (``True``)
656 or not (``False``). This must be set before :meth:`~Thread.start` is called,
657 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
658 from the creating thread; the main thread is not a daemon thread and
659 therefore all threads created in the main thread default to
660 :attr:`~Thread.daemon` = ``False``.
661
662 The entire Python program exits when no alive non-daemon threads are left.
663
664 .. method:: isDaemon()
665 setDaemon()
666
667 Deprecated getter/setter API for :attr:`~Thread.daemon`; use it directly as a
668 property instead.
669
670 .. deprecated:: 3.10
671
672
673 .. _lock-objects:
674
675 Lock objects
676 ^^^^^^^^^^^^
677
678 A primitive lock is a synchronization primitive that is not owned by a
679 particular thread when locked. In Python, it is currently the lowest level
680 synchronization primitive available, implemented directly by the :mod:`_thread`
681 extension module.
682
683 A primitive lock is in one of two states, "locked" or "unlocked". It is created
684 in the unlocked state. It has two basic methods, :meth:`~Lock.acquire` and
685 :meth:`~Lock.release`. When the state is unlocked, :meth:`~Lock.acquire`
686 changes the state to locked and returns immediately. When the state is locked,
687 :meth:`~Lock.acquire` blocks until a call to :meth:`~Lock.release` in another
688 thread changes it to unlocked, then the :meth:`~Lock.acquire` call resets it
689 to locked and returns. The :meth:`~Lock.release` method should only be
690 called in the locked state; it changes the state to unlocked and returns
691 immediately. If an attempt is made to release an unlocked lock, a
692 :exc:`RuntimeError` will be raised.
693
694 Locks also support the :ref:`context management protocol <with-locks>`.
695
696 When more than one thread is blocked in :meth:`~Lock.acquire` waiting for the
697 state to turn to unlocked, only one thread proceeds when a :meth:`~Lock.release`
698 call resets the state to unlocked; which one of the waiting threads proceeds
699 is not defined, and may vary across implementations.
700
701 All methods are executed atomically.
702
703
704 .. class:: Lock()
705
706 The class implementing primitive lock objects. Once a thread has acquired a
707 lock, subsequent attempts to acquire it block, until it is released; any
708 thread may release it.
709
710 .. versionchanged:: 3.13
711 ``Lock`` is now a class. In earlier Pythons, ``Lock`` was a factory
712 function which returned an instance of the underlying private lock
713 type.
714
715
716 .. method:: acquire(blocking=True, timeout=-1)
717
718 Acquire a lock, blocking or non-blocking.
719
720 When invoked with the *blocking* argument set to ``True`` (the default),
721 block until the lock is unlocked, then set it to locked and return ``True``.
722
723 When invoked with the *blocking* argument set to ``False``, do not block.
724 If a call with *blocking* set to ``True`` would block, return ``False``
725 immediately; otherwise, set the lock to locked and return ``True``.
726
727 When invoked with the floating-point *timeout* argument set to a positive
728 value, block for at most the number of seconds specified by *timeout*
729 and as long as the lock cannot be acquired. A *timeout* argument of ``-1``
730 specifies an unbounded wait. It is forbidden to specify a *timeout*
731 when *blocking* is ``False``.
732
733 The return value is ``True`` if the lock is acquired successfully,
734 ``False`` if not (for example if the *timeout* expired).
735
736 .. versionchanged:: 3.2
737 The *timeout* parameter is new.
738
739 .. versionchanged:: 3.2
740 Lock acquisition can now be interrupted by signals on POSIX if the
741 underlying threading implementation supports it.
742
743
744 .. method:: release()
745
746 Release a lock. This can be called from any thread, not only the thread
747 which has acquired the lock.
748
749 When the lock is locked, reset it to unlocked, and return. If any other threads
750 are blocked waiting for the lock to become unlocked, allow exactly one of them
751 to proceed.
752
753 When invoked on an unlocked lock, a :exc:`RuntimeError` is raised.
754
755 There is no return value.
756
757 .. method:: locked()
758
759 Return ``True`` if the lock is acquired.
760
761
762
763 .. _rlock-objects:
764
765 RLock objects
766 ^^^^^^^^^^^^^
767
768 A reentrant lock is a synchronization primitive that may be acquired multiple
769 times by the same thread. Internally, it uses the concepts of "owning thread"
770 and "recursion level" in addition to the locked/unlocked state used by primitive
771 locks. In the locked state, some thread owns the lock; in the unlocked state,
772 no thread owns it.
773
774 Threads call a lock's :meth:`~RLock.acquire` method to lock it,
775 and its :meth:`~Lock.release` method to unlock it.
776
777 .. note::
778
779 Reentrant locks support the :ref:`context management protocol <with-locks>`,
780 so it is recommended to use :keyword:`with` instead of manually calling
781 :meth:`~RLock.acquire` and :meth:`~RLock.release`
782 to handle acquiring and releasing the lock for a block of code.
783
784 RLock's :meth:`~RLock.acquire`/:meth:`~RLock.release` call pairs may be nested,
785 unlike Lock's :meth:`~Lock.acquire`/:meth:`~Lock.release`. Only the final
786 :meth:`~RLock.release` (the :meth:`~Lock.release` of the outermost pair) resets
787 the lock to an unlocked state and allows another thread blocked in
788 :meth:`~RLock.acquire` to proceed.
789
790 :meth:`~RLock.acquire`/:meth:`~RLock.release` must be used in pairs: each acquire
791 must have a release in the thread that has acquired the lock. Failing to
792 call release as many times the lock has been acquired can lead to deadlock.
793
794
795 .. class:: RLock()
796
797 This class implements reentrant lock objects. A reentrant lock must be
798 released by the thread that acquired it. Once a thread has acquired a
799 reentrant lock, the same thread may acquire it again without blocking; the
800 thread must release it once for each time it has acquired it.
801
802 Note that ``RLock`` is actually a factory function which returns an instance
803 of the most efficient version of the concrete RLock class that is supported
804 by the platform.
805
806
807 .. method:: acquire(blocking=True, timeout=-1)
808
809 Acquire a lock, blocking or non-blocking.
810
811 .. seealso::
812
813 :ref:`Using RLock as a context manager <with-locks>`
814 Recommended over manual :meth:`!acquire` and :meth:`release` calls
815 whenever practical.
816
817
818 When invoked with the *blocking* argument set to ``True`` (the default):
819
820 * If no thread owns the lock, acquire the lock and return immediately.
821
822 * If another thread owns the lock, block until we are able to acquire
823 lock, or *timeout*, if set to a positive float value.
824
825 * If the same thread owns the lock, acquire the lock again, and
826 return immediately. This is the difference between :class:`Lock` and
827 :class:`!RLock`; :class:`Lock` handles this case the same as the previous,
828 blocking until the lock can be acquired.
829
830 When invoked with the *blocking* argument set to ``False``:
831
832 * If no thread owns the lock, acquire the lock and return immediately.
833
834 * If another thread owns the lock, return immediately.
835
836 * If the same thread owns the lock, acquire the lock again and return
837 immediately.
838
839 In all cases, if the thread was able to acquire the lock, return ``True``.
840 If the thread was unable to acquire the lock (i.e. if not blocking or
841 the timeout was reached) return ``False``.
842
843 If called multiple times, failing to call :meth:`~RLock.release` as many times
844 may lead to deadlock. Consider using :class:`!RLock` as a context manager rather than
845 calling acquire/release directly.
846
847 .. versionchanged:: 3.2
848 The *timeout* parameter is new.
849
850
851 .. method:: release()
852
853 Release a lock, decrementing the recursion level. If after the decrement it is
854 zero, reset the lock to unlocked (not owned by any thread), and if any other
855 threads are blocked waiting for the lock to become unlocked, allow exactly one
856 of them to proceed. If after the decrement the recursion level is still
857 nonzero, the lock remains locked and owned by the calling thread.
858
859 Only call this method when the calling thread owns the lock. A
860 :exc:`RuntimeError` is raised if this method is called when the lock is
861 not acquired.
862
863 There is no return value.
864
865
866 .. _condition-objects:
867
868 Condition objects
869 ^^^^^^^^^^^^^^^^^
870
871 A condition variable is always associated with some kind of lock; this can be
872 passed in or one will be created by default. Passing one in is useful when
873 several condition variables must share the same lock. The lock is part of
874 the condition object: you don't have to track it separately.
875
876 A condition variable obeys the :ref:`context management protocol <with-locks>`:
877 using the ``with`` statement acquires the associated lock for the duration of
878 the enclosed block. The :meth:`~Condition.acquire` and
879 :meth:`~Condition.release` methods also call the corresponding methods of
880 the associated lock.
881
882 Other methods must be called with the associated lock held. The
883 :meth:`~Condition.wait` method releases the lock, and then blocks until
884 another thread awakens it by calling :meth:`~Condition.notify` or
885 :meth:`~Condition.notify_all`. Once awakened, :meth:`~Condition.wait`
886 re-acquires the lock and returns. It is also possible to specify a timeout.
887
888 The :meth:`~Condition.notify` method wakes up one of the threads waiting for
889 the condition variable, if any are waiting. The :meth:`~Condition.notify_all`
890 method wakes up all threads waiting for the condition variable.
891
892 Note: the :meth:`~Condition.notify` and :meth:`~Condition.notify_all` methods
893 don't release the lock; this means that the thread or threads awakened will
894 not return from their :meth:`~Condition.wait` call immediately, but only when
895 the thread that called :meth:`~Condition.notify` or :meth:`~Condition.notify_all`
896 finally relinquishes ownership of the lock.
897
898 The typical programming style using condition variables uses the lock to
899 synchronize access to some shared state; threads that are interested in a
900 particular change of state call :meth:`~Condition.wait` repeatedly until they
901 see the desired state, while threads that modify the state call
902 :meth:`~Condition.notify` or :meth:`~Condition.notify_all` when they change
903 the state in such a way that it could possibly be a desired state for one
904 of the waiters. For example, the following code is a generic
905 producer-consumer situation with unlimited buffer capacity::
906
907 # Consume one item
908 with cv:
909 while not an_item_is_available():
910 cv.wait()
911 get_an_available_item()
912
913 # Produce one item
914 with cv:
915 make_an_item_available()
916 cv.notify()
917
918 The ``while`` loop checking for the application's condition is necessary
919 because :meth:`~Condition.wait` can return after an arbitrary long time,
920 and the condition which prompted the :meth:`~Condition.notify` call may
921 no longer hold true. This is inherent to multi-threaded programming. The
922 :meth:`~Condition.wait_for` method can be used to automate the condition
923 checking, and eases the computation of timeouts::
924
925 # Consume an item
926 with cv:
927 cv.wait_for(an_item_is_available)
928 get_an_available_item()
929
930 To choose between :meth:`~Condition.notify` and :meth:`~Condition.notify_all`,
931 consider whether one state change can be interesting for only one or several
932 waiting threads. E.g. in a typical producer-consumer situation, adding one
933 item to the buffer only needs to wake up one consumer thread.
934
935
936 .. class:: Condition(lock=None)
937
938 This class implements condition variable objects. A condition variable
939 allows one or more threads to wait until they are notified by another thread.
940
941 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
942 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
943 a new :class:`RLock` object is created and used as the underlying lock.
944
945 .. versionchanged:: 3.3
946 changed from a factory function to a class.
947
948 .. method:: acquire(*args)
949
950 Acquire the underlying lock. This method calls the corresponding method on
951 the underlying lock; the return value is whatever that method returns.
952
953 .. method:: release()
954
955 Release the underlying lock. This method calls the corresponding method on
956 the underlying lock; there is no return value.
957
958 .. method:: wait(timeout=None)
959
960 Wait until notified or until a timeout occurs. If the calling thread has
961 not acquired the lock when this method is called, a :exc:`RuntimeError` is
962 raised.
963
964 This method releases the underlying lock, and then blocks until it is
965 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
966 condition variable in another thread, or until the optional timeout
967 occurs. Once awakened or timed out, it re-acquires the lock and returns.
968
969 When the *timeout* argument is present and not ``None``, it should be a
970 floating-point number specifying a timeout for the operation in seconds
971 (or fractions thereof).
972
973 When the underlying lock is an :class:`RLock`, it is not released using
974 its :meth:`release` method, since this may not actually unlock the lock
975 when it was acquired multiple times recursively. Instead, an internal
976 interface of the :class:`RLock` class is used, which really unlocks it
977 even when it has been recursively acquired several times. Another internal
978 interface is then used to restore the recursion level when the lock is
979 reacquired.
980
981 The return value is ``True`` unless a given *timeout* expired, in which
982 case it is ``False``.
983
984 .. versionchanged:: 3.2
985 Previously, the method always returned ``None``.
986
987 .. method:: wait_for(predicate, timeout=None)
988
989 Wait until a condition evaluates to true. *predicate* should be a
990 callable which result will be interpreted as a boolean value.
991 A *timeout* may be provided giving the maximum time to wait.
992
993 This utility method may call :meth:`wait` repeatedly until the predicate
994 is satisfied, or until a timeout occurs. The return value is
995 the last return value of the predicate and will evaluate to
996 ``False`` if the method timed out.
997
998 Ignoring the timeout feature, calling this method is roughly equivalent to
999 writing::
1000
1001 while not predicate():
1002 cv.wait()
1003
1004 Therefore, the same rules apply as with :meth:`wait`: The lock must be
1005 held when called and is re-acquired on return. The predicate is evaluated
1006 with the lock held.
1007
1008 .. versionadded:: 3.2
1009
1010 .. method:: notify(n=1)
1011
1012 By default, wake up one thread waiting on this condition, if any. If the
1013 calling thread has not acquired the lock when this method is called, a
1014 :exc:`RuntimeError` is raised.
1015
1016 This method wakes up at most *n* of the threads waiting for the condition
1017 variable; it is a no-op if no threads are waiting.
1018
1019 The current implementation wakes up exactly *n* threads, if at least *n*
1020 threads are waiting. However, it's not safe to rely on this behavior.
1021 A future, optimized implementation may occasionally wake up more than
1022 *n* threads.
1023
1024 Note: an awakened thread does not actually return from its :meth:`wait`
1025 call until it can reacquire the lock. Since :meth:`notify` does not
1026 release the lock, its caller should.
1027
1028 .. method:: notify_all()
1029
1030 Wake up all threads waiting on this condition. This method acts like
1031 :meth:`notify`, but wakes up all waiting threads instead of one. If the
1032 calling thread has not acquired the lock when this method is called, a
1033 :exc:`RuntimeError` is raised.
1034
1035 The method ``notifyAll`` is a deprecated alias for this method.
1036
1037
1038 .. _semaphore-objects:
1039
1040 Semaphore objects
1041 ^^^^^^^^^^^^^^^^^
1042
1043 This is one of the oldest synchronization primitives in the history of computer
1044 science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
1045 used the names ``P()`` and ``V()`` instead of :meth:`~Semaphore.acquire` and
1046 :meth:`~Semaphore.release`).
1047
1048 A semaphore manages an internal counter which is decremented by each
1049 :meth:`~Semaphore.acquire` call and incremented by each :meth:`~Semaphore.release`
1050 call. The counter can never go below zero; when :meth:`~Semaphore.acquire`
1051 finds that it is zero, it blocks, waiting until some other thread calls
1052 :meth:`~Semaphore.release`.
1053
1054 Semaphores also support the :ref:`context management protocol <with-locks>`.
1055
1056
1057 .. class:: Semaphore(value=1)
1058
1059 This class implements semaphore objects. A semaphore manages an atomic
1060 counter representing the number of :meth:`release` calls minus the number of
1061 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method
1062 blocks if necessary until it can return without making the counter negative.
1063 If not given, *value* defaults to 1.
1064
1065 The optional argument gives the initial *value* for the internal counter; it
1066 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
1067 raised.
1068
1069 .. versionchanged:: 3.3
1070 changed from a factory function to a class.
1071
1072 .. method:: acquire(blocking=True, timeout=None)
1073
1074 Acquire a semaphore.
1075
1076 When invoked without arguments:
1077
1078 * If the internal counter is larger than zero on entry, decrement it by
1079 one and return ``True`` immediately.
1080 * If the internal counter is zero on entry, block until awoken by a call to
1081 :meth:`~Semaphore.release`. Once awoken (and the counter is greater
1082 than 0), decrement the counter by 1 and return ``True``. Exactly one
1083 thread will be awoken by each call to :meth:`~Semaphore.release`. The
1084 order in which threads are awoken should not be relied on.
1085
1086 When invoked with *blocking* set to ``False``, do not block. If a call
1087 without an argument would block, return ``False`` immediately; otherwise, do
1088 the same thing as when called without arguments, and return ``True``.
1089
1090 When invoked with a *timeout* other than ``None``, it will block for at
1091 most *timeout* seconds. If acquire does not complete successfully in
1092 that interval, return ``False``. Return ``True`` otherwise.
1093
1094 .. versionchanged:: 3.2
1095 The *timeout* parameter is new.
1096
1097 .. method:: release(n=1)
1098
1099 Release a semaphore, incrementing the internal counter by *n*. When it
1100 was zero on entry and other threads are waiting for it to become larger
1101 than zero again, wake up *n* of those threads.
1102
1103 .. versionchanged:: 3.9
1104 Added the *n* parameter to release multiple waiting threads at once.
1105
1106
1107 .. class:: BoundedSemaphore(value=1)
1108
1109 Class implementing bounded semaphore objects. A bounded semaphore checks to
1110 make sure its current value doesn't exceed its initial value. If it does,
1111 :exc:`ValueError` is raised. In most situations semaphores are used to guard
1112 resources with limited capacity. If the semaphore is released too many times
1113 it's a sign of a bug. If not given, *value* defaults to 1.
1114
1115 .. versionchanged:: 3.3
1116 changed from a factory function to a class.
1117
1118
1119 .. _semaphore-examples:
1120
1121 :class:`Semaphore` example
1122 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1123
1124 Semaphores are often used to guard resources with limited capacity, for example,
1125 a database server. In any situation where the size of the resource is fixed,
1126 you should use a bounded semaphore. Before spawning any worker threads, your
1127 main thread would initialize the semaphore::
1128
1129 maxconnections = 5
1130 # ...
1131 pool_sema = BoundedSemaphore(value=maxconnections)
1132
1133 Once spawned, worker threads call the semaphore's acquire and release methods
1134 when they need to connect to the server::
1135
1136 with pool_sema:
1137 conn = connectdb()
1138 try:
1139 # ... use connection ...
1140 finally:
1141 conn.close()
1142
1143 The use of a bounded semaphore reduces the chance that a programming error which
1144 causes the semaphore to be released more than it's acquired will go undetected.
1145
1146
1147 .. _event-objects:
1148
1149 Event objects
1150 ^^^^^^^^^^^^^
1151
1152 This is one of the simplest mechanisms for communication between threads: one
1153 thread signals an event and other threads wait for it.
1154
1155 An event object manages an internal flag that can be set to true with the
1156 :meth:`~Event.set` method and reset to false with the :meth:`~Event.clear`
1157 method. The :meth:`~Event.wait` method blocks until the flag is true.
1158
1159
1160 .. class:: Event()
1161
1162 Class implementing event objects. An event manages a flag that can be set to
1163 true with the :meth:`~Event.set` method and reset to false with the
1164 :meth:`clear` method. The :meth:`wait` method blocks until the flag is true.
1165 The flag is initially false.
1166
1167 .. versionchanged:: 3.3
1168 changed from a factory function to a class.
1169
1170 .. method:: is_set()
1171
1172 Return ``True`` if and only if the internal flag is true.
1173
1174 The method ``isSet`` is a deprecated alias for this method.
1175
1176 .. method:: set()
1177
1178 Set the internal flag to true. All threads waiting for it to become true
1179 are awakened. Threads that call :meth:`wait` once the flag is true will
1180 not block at all.
1181
1182 .. method:: clear()
1183
1184 Reset the internal flag to false. Subsequently, threads calling
1185 :meth:`wait` will block until :meth:`.set` is called to set the internal
1186 flag to true again.
1187
1188 .. method:: wait(timeout=None)
1189
1190 Block as long as the internal flag is false and the timeout, if given,
1191 has not expired. The return value represents the
1192 reason that this blocking method returned; ``True`` if returning because
1193 the internal flag is set to true, or ``False`` if a timeout is given and
1194 the internal flag did not become true within the given wait time.
1195
1196 When the timeout argument is present and not ``None``, it should be a
1197 floating-point number specifying a timeout for the operation in seconds,
1198 or fractions thereof.
1199
1200 .. versionchanged:: 3.1
1201 Previously, the method always returned ``None``.
1202
1203
1204 .. _timer-objects:
1205
1206 Timer objects
1207 ^^^^^^^^^^^^^
1208
1209 This class represents an action that should be run only after a certain amount
1210 of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
1211 and as such also functions as an example of creating custom threads.
1212
1213 Timers are started, as with threads, by calling their :meth:`Timer.start <Thread.start>`
1214 method. The timer can be stopped (before its action has begun) by calling the
1215 :meth:`~Timer.cancel` method. The interval the timer will wait before
1216 executing its action may not be exactly the same as the interval specified by
1217 the user.
1218
1219 For example::
1220
1221 def hello():
1222 print("hello, world")
1223
1224 t = Timer(30.0, hello)
1225 t.start() # after 30 seconds, "hello, world" will be printed
1226
1227
1228 .. class:: Timer(interval, function, args=None, kwargs=None)
1229
1230 Create a timer that will run *function* with arguments *args* and keyword
1231 arguments *kwargs*, after *interval* seconds have passed.
1232 If *args* is ``None`` (the default) then an empty list will be used.
1233 If *kwargs* is ``None`` (the default) then an empty dict will be used.
1234
1235 .. versionchanged:: 3.3
1236 changed from a factory function to a class.
1237
1238 .. method:: cancel()
1239
1240 Stop the timer, and cancel the execution of the timer's action. This will
1241 only work if the timer is still in its waiting stage.
1242
1243
1244 Barrier objects
1245 ^^^^^^^^^^^^^^^
1246
1247 .. versionadded:: 3.2
1248
1249 This class provides a simple synchronization primitive for use by a fixed number
1250 of threads that need to wait for each other. Each of the threads tries to pass
1251 the barrier by calling the :meth:`~Barrier.wait` method and will block until
1252 all of the threads have made their :meth:`~Barrier.wait` calls. At this point,
1253 the threads are released simultaneously.
1254
1255 The barrier can be reused any number of times for the same number of threads.
1256
1257 As an example, here is a simple way to synchronize a client and server thread::
1258
1259 b = Barrier(2, timeout=5)
1260
1261 def server():
1262 start_server()
1263 b.wait()
1264 while True:
1265 connection = accept_connection()
1266 process_server_connection(connection)
1267
1268 def client():
1269 b.wait()
1270 while True:
1271 connection = make_connection()
1272 process_client_connection(connection)
1273
1274
1275 .. class:: Barrier(parties, action=None, timeout=None)
1276
1277 Create a barrier object for *parties* number of threads. An *action*, when
1278 provided, is a callable to be called by one of the threads when they are
1279 released. *timeout* is the default timeout value if none is specified for
1280 the :meth:`wait` method.
1281
1282 .. method:: wait(timeout=None)
1283
1284 Pass the barrier. When all the threads party to the barrier have called
1285 this function, they are all released simultaneously. If a *timeout* is
1286 provided, it is used in preference to any that was supplied to the class
1287 constructor.
1288
1289 The return value is an integer in the range 0 to *parties* -- 1, different
1290 for each thread. This can be used to select a thread to do some special
1291 housekeeping, e.g.::
1292
1293 i = barrier.wait()
1294 if i == 0:
1295 # Only one thread needs to print this
1296 print("passed the barrier")
1297
1298 If an *action* was provided to the constructor, one of the threads will
1299 have called it prior to being released. Should this call raise an error,
1300 the barrier is put into the broken state.
1301
1302 If the call times out, the barrier is put into the broken state.
1303
1304 This method may raise a :class:`BrokenBarrierError` exception if the
1305 barrier is broken or reset while a thread is waiting.
1306
1307 .. method:: reset()
1308
1309 Return the barrier to the default, empty state. Any threads waiting on it
1310 will receive the :class:`BrokenBarrierError` exception.
1311
1312 Note that using this function may require some external
1313 synchronization if there are other threads whose state is unknown. If a
1314 barrier is broken it may be better to just leave it and create a new one.
1315
1316 .. method:: abort()
1317
1318 Put the barrier into a broken state. This causes any active or future
1319 calls to :meth:`wait` to fail with the :class:`BrokenBarrierError`. Use
1320 this for example if one of the threads needs to abort, to avoid deadlocking the
1321 application.
1322
1323 It may be preferable to simply create the barrier with a sensible
1324 *timeout* value to automatically guard against one of the threads going
1325 awry.
1326
1327 .. attribute:: parties
1328
1329 The number of threads required to pass the barrier.
1330
1331 .. attribute:: n_waiting
1332
1333 The number of threads currently waiting in the barrier.
1334
1335 .. attribute:: broken
1336
1337 A boolean that is ``True`` if the barrier is in the broken state.
1338
1339
1340 .. exception:: BrokenBarrierError
1341
1342 This exception, a subclass of :exc:`RuntimeError`, is raised when the
1343 :class:`Barrier` object is reset or broken.
1344
1345
1346 .. _with-locks:
1347
1348 Using locks, conditions, and semaphores in the :keyword:`!with` statement
1349 -------------------------------------------------------------------------
1350
1351 All of the objects provided by this module that have ``acquire`` and
1352 ``release`` methods can be used as context managers for a :keyword:`with`
1353 statement. The ``acquire`` method will be called when the block is
1354 entered, and ``release`` will be called when the block is exited. Hence,
1355 the following snippet::
1356
1357 with some_lock:
1358 # do something...
1359
1360 is equivalent to::
1361
1362 some_lock.acquire()
1363 try:
1364 # do something...
1365 finally:
1366 some_lock.release()
1367
1368 Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
1369 :class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
1370 :keyword:`with` statement context managers.