blob: 2028f8b4747623b11f468a3a12cb2377d5989b39 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`threading` --- Higher-level threading interface
2=====================================================
3
4.. module:: threading
5 :synopsis: Higher-level threading interface.
6
7
8This module constructs higher-level threading interfaces on top of the lower
9level :mod:`thread` module.
Georg Brandla6168f92008-05-25 07:20:14 +000010See also the :mod:`mutex` and :mod:`Queue` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
12The :mod:`dummy_threading` module is provided for situations where
13:mod:`threading` cannot be used because :mod:`thread` is missing.
14
Benjamin Petersonf4395602008-06-11 17:50:00 +000015.. note::
16
Victor Stinner8ded4772010-05-14 14:20:07 +000017 Starting with Python 2.6, this module provides :pep:`8` compliant aliases and
Benjamin Peterson973e6c22008-09-01 23:12:58 +000018 properties to replace the ``camelCase`` names that were inspired by Java's
19 threading API. This updated API is compatible with that of the
20 :mod:`multiprocessing` module. However, no schedule has been set for the
21 deprecation of the ``camelCase`` names and they remain fully supported in
22 both Python 2.x and 3.x.
Benjamin Petersonf4395602008-06-11 17:50:00 +000023
Georg Brandl2cd82a82009-03-09 14:25:07 +000024.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000025
Georg Brandl2cd82a82009-03-09 14:25:07 +000026 Starting with Python 2.5, several Thread methods raise :exc:`RuntimeError`
27 instead of :exc:`AssertionError` if called erroneously.
28
29
30This module defines the following functions and objects:
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000032.. function:: active_count()
Benjamin Petersonf4395602008-06-11 17:50:00 +000033 activeCount()
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35 Return the number of :class:`Thread` objects currently alive. The returned
Georg Brandlf4da6662009-09-19 12:04:16 +000036 count is equal to the length of the list returned by :func:`.enumerate`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000037
38
39.. function:: Condition()
40 :noindex:
41
42 A factory function that returns a new condition variable object. A condition
43 variable allows one or more threads to wait until they are notified by another
44 thread.
45
Georg Brandl21946af2010-10-06 09:28:45 +000046 See :ref:`condition-objects`.
47
Georg Brandl8ec7f652007-08-15 14:28:01 +000048
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000049.. function:: current_thread()
Benjamin Petersonf4395602008-06-11 17:50:00 +000050 currentThread()
Georg Brandl8ec7f652007-08-15 14:28:01 +000051
52 Return the current :class:`Thread` object, corresponding to the caller's thread
53 of control. If the caller's thread of control was not created through the
54 :mod:`threading` module, a dummy thread object with limited functionality is
55 returned.
56
57
58.. function:: enumerate()
59
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000060 Return a list of all :class:`Thread` objects currently alive. The list
61 includes daemonic threads, dummy thread objects created by
62 :func:`current_thread`, and the main thread. It excludes terminated threads
63 and threads that have not yet been started.
Georg Brandl8ec7f652007-08-15 14:28:01 +000064
65
66.. function:: Event()
67 :noindex:
68
69 A factory function that returns a new event object. An event manages a flag
Georg Brandl9fa61bb2009-07-26 14:19:57 +000070 that can be set to true with the :meth:`~Event.set` method and reset to false
71 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
72 is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +000073
Georg Brandl21946af2010-10-06 09:28:45 +000074 See :ref:`event-objects`.
75
Georg Brandl8ec7f652007-08-15 14:28:01 +000076
77.. class:: local
78
79 A class that represents thread-local data. Thread-local data are data whose
80 values are thread specific. To manage thread-local data, just create an
81 instance of :class:`local` (or a subclass) and store attributes on it::
82
83 mydata = threading.local()
84 mydata.x = 1
85
86 The instance's values will be different for separate threads.
87
88 For more details and extensive examples, see the documentation string of the
89 :mod:`_threading_local` module.
90
91 .. versionadded:: 2.4
92
93
94.. function:: Lock()
95
96 A factory function that returns a new primitive lock object. Once a thread has
97 acquired it, subsequent attempts to acquire it block, until it is released; any
98 thread may release it.
99
Georg Brandl21946af2010-10-06 09:28:45 +0000100 See :ref:`lock-objects`.
101
Georg Brandl8ec7f652007-08-15 14:28:01 +0000102
103.. function:: RLock()
104
105 A factory function that returns a new reentrant lock object. A reentrant lock
106 must be released by the thread that acquired it. Once a thread has acquired a
107 reentrant lock, the same thread may acquire it again without blocking; the
108 thread must release it once for each time it has acquired it.
109
Georg Brandl21946af2010-10-06 09:28:45 +0000110 See :ref:`rlock-objects`.
111
Georg Brandl8ec7f652007-08-15 14:28:01 +0000112
113.. function:: Semaphore([value])
114 :noindex:
115
116 A factory function that returns a new semaphore object. A semaphore manages a
117 counter representing the number of :meth:`release` calls minus the number of
118 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
119 if necessary until it can return without making the counter negative. If not
120 given, *value* defaults to 1.
121
Georg Brandl21946af2010-10-06 09:28:45 +0000122 See :ref:`semaphore-objects`.
123
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124
125.. function:: BoundedSemaphore([value])
126
127 A factory function that returns a new bounded semaphore object. A bounded
128 semaphore checks to make sure its current value doesn't exceed its initial
129 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
130 are used to guard resources with limited capacity. If the semaphore is released
131 too many times it's a sign of a bug. If not given, *value* defaults to 1.
132
133
134.. class:: Thread
Georg Brandl21946af2010-10-06 09:28:45 +0000135 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136
137 A class that represents a thread of control. This class can be safely
138 subclassed in a limited fashion.
139
Georg Brandl21946af2010-10-06 09:28:45 +0000140 See :ref:`thread-objects`.
141
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
143.. class:: Timer
Georg Brandl21946af2010-10-06 09:28:45 +0000144 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000145
146 A thread that executes a function after a specified interval has passed.
147
Georg Brandl21946af2010-10-06 09:28:45 +0000148 See :ref:`timer-objects`.
149
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151.. function:: settrace(func)
152
153 .. index:: single: trace function
154
155 Set a trace function for all threads started from the :mod:`threading` module.
156 The *func* will be passed to :func:`sys.settrace` for each thread, before its
157 :meth:`run` method is called.
158
159 .. versionadded:: 2.3
160
161
162.. function:: setprofile(func)
163
164 .. index:: single: profile function
165
166 Set a profile function for all threads started from the :mod:`threading` module.
167 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
168 :meth:`run` method is called.
169
170 .. versionadded:: 2.3
171
172
173.. function:: stack_size([size])
174
175 Return the thread stack size used when creating new threads. The optional
176 *size* argument specifies the stack size to be used for subsequently created
177 threads, and must be 0 (use platform or configured default) or a positive
178 integer value of at least 32,768 (32kB). If changing the thread stack size is
179 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
180 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
181 is currently the minimum supported stack size value to guarantee sufficient
182 stack space for the interpreter itself. Note that some platforms may have
183 particular restrictions on values for the stack size, such as requiring a
184 minimum stack size > 32kB or requiring allocation in multiples of the system
185 memory page size - platform documentation should be referred to for more
186 information (4kB pages are common; using multiples of 4096 for the stack size is
187 the suggested approach in the absence of more specific information).
188 Availability: Windows, systems with POSIX threads.
189
190 .. versionadded:: 2.5
191
192Detailed interfaces for the objects are documented below.
193
194The design of this module is loosely based on Java's threading model. However,
195where Java makes locks and condition variables basic behavior of every object,
196they are separate objects in Python. Python's :class:`Thread` class supports a
197subset of the behavior of Java's Thread class; currently, there are no
198priorities, no thread groups, and threads cannot be destroyed, stopped,
199suspended, resumed, or interrupted. The static methods of Java's Thread class,
200when implemented, are mapped to module-level functions.
201
202All of the methods described below are executed atomically.
203
204
Georg Brandl01ba86a2008-11-06 10:20:49 +0000205.. _thread-objects:
206
207Thread Objects
208--------------
209
210This class represents an activity that is run in a separate thread of control.
211There are two ways to specify the activity: by passing a callable object to the
212constructor, or by overriding the :meth:`run` method in a subclass. No other
213methods (except for the constructor) should be overridden in a subclass. In
214other words, *only* override the :meth:`__init__` and :meth:`run` methods of
215this class.
216
217Once a thread object is created, its activity must be started by calling the
218thread's :meth:`start` method. This invokes the :meth:`run` method in a
219separate thread of control.
220
221Once the thread's activity is started, the thread is considered 'alive'. It
222stops being alive when its :meth:`run` method terminates -- either normally, or
223by raising an unhandled exception. The :meth:`is_alive` method tests whether the
224thread is alive.
225
226Other threads can call a thread's :meth:`join` method. This blocks the calling
227thread until the thread whose :meth:`join` method is called is terminated.
228
229A thread has a name. The name can be passed to the constructor, and read or
230changed through the :attr:`name` attribute.
231
232A thread can be flagged as a "daemon thread". The significance of this flag is
233that the entire Python program exits when only daemon threads are left. The
234initial value is inherited from the creating thread. The flag can be set
Georg Brandlecd2afa2009-02-05 11:40:35 +0000235through the :attr:`daemon` property.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000236
237There is a "main thread" object; this corresponds to the initial thread of
238control in the Python program. It is not a daemon thread.
239
240There is the possibility that "dummy thread objects" are created. These are
241thread objects corresponding to "alien threads", which are threads of control
242started outside the threading module, such as directly from C code. Dummy
243thread objects have limited functionality; they are always considered alive and
244daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
245impossible to detect the termination of alien threads.
246
247
248.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
249
Georg Brandl3591a8f2009-07-26 14:44:23 +0000250 This constructor should always be called with keyword arguments. Arguments
251 are:
Georg Brandl01ba86a2008-11-06 10:20:49 +0000252
253 *group* should be ``None``; reserved for future extension when a
254 :class:`ThreadGroup` class is implemented.
255
256 *target* is the callable object to be invoked by the :meth:`run` method.
257 Defaults to ``None``, meaning nothing is called.
258
Georg Brandl3591a8f2009-07-26 14:44:23 +0000259 *name* is the thread name. By default, a unique name is constructed of the
260 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000261
262 *args* is the argument tuple for the target invocation. Defaults to ``()``.
263
264 *kwargs* is a dictionary of keyword arguments for the target invocation.
265 Defaults to ``{}``.
266
Georg Brandl3591a8f2009-07-26 14:44:23 +0000267 If the subclass overrides the constructor, it must make sure to invoke the
268 base class constructor (``Thread.__init__()``) before doing anything else to
269 the thread.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000270
Georg Brandl3591a8f2009-07-26 14:44:23 +0000271 .. method:: start()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000272
Georg Brandl3591a8f2009-07-26 14:44:23 +0000273 Start the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000274
Georg Brandl3591a8f2009-07-26 14:44:23 +0000275 It must be called at most once per thread object. It arranges for the
276 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000277
Georg Brandl3591a8f2009-07-26 14:44:23 +0000278 This method will raise a :exc:`RuntimeException` if called more than once
279 on the same thread object.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000280
Georg Brandl3591a8f2009-07-26 14:44:23 +0000281 .. method:: run()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000282
Georg Brandl3591a8f2009-07-26 14:44:23 +0000283 Method representing the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000284
Georg Brandl3591a8f2009-07-26 14:44:23 +0000285 You may override this method in a subclass. The standard :meth:`run`
286 method invokes the callable object passed to the object's constructor as
287 the *target* argument, if any, with sequential and keyword arguments taken
288 from the *args* and *kwargs* arguments, respectively.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000289
Georg Brandl3591a8f2009-07-26 14:44:23 +0000290 .. method:: join([timeout])
Georg Brandl01ba86a2008-11-06 10:20:49 +0000291
Georg Brandl3591a8f2009-07-26 14:44:23 +0000292 Wait until the thread terminates. This blocks the calling thread until the
293 thread whose :meth:`join` method is called terminates -- either normally
294 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000295
Georg Brandl3591a8f2009-07-26 14:44:23 +0000296 When the *timeout* argument is present and not ``None``, it should be a
297 floating point number specifying a timeout for the operation in seconds
298 (or fractions thereof). As :meth:`join` always returns ``None``, you must
299 call :meth:`isAlive` after :meth:`join` to decide whether a timeout
300 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000301
Georg Brandl3591a8f2009-07-26 14:44:23 +0000302 When the *timeout* argument is not present or ``None``, the operation will
303 block until the thread terminates.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000304
Georg Brandl3591a8f2009-07-26 14:44:23 +0000305 A thread can be :meth:`join`\ ed many times.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000306
Georg Brandl3591a8f2009-07-26 14:44:23 +0000307 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
308 the current thread as that would cause a deadlock. It is also an error to
309 :meth:`join` a thread before it has been started and attempts to do so
310 raises the same exception.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000311
Georg Brandl3591a8f2009-07-26 14:44:23 +0000312 .. method:: getName()
313 setName()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000314
Georg Brandl3591a8f2009-07-26 14:44:23 +0000315 Old API for :attr:`~Thread.name`.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000316
Georg Brandl3591a8f2009-07-26 14:44:23 +0000317 .. attribute:: name
Georg Brandl01ba86a2008-11-06 10:20:49 +0000318
Georg Brandl3591a8f2009-07-26 14:44:23 +0000319 A string used for identification purposes only. It has no semantics.
320 Multiple threads may be given the same name. The initial name is set by
321 the constructor.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000322
Georg Brandl3591a8f2009-07-26 14:44:23 +0000323 .. attribute:: ident
Georg Brandl01ba86a2008-11-06 10:20:49 +0000324
Georg Brandl3591a8f2009-07-26 14:44:23 +0000325 The 'thread identifier' of this thread or ``None`` if the thread has not
326 been started. This is a nonzero integer. See the
327 :func:`thread.get_ident()` function. Thread identifiers may be recycled
328 when a thread exits and another thread is created. The identifier is
329 available even after the thread has exited.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000330
Georg Brandl3591a8f2009-07-26 14:44:23 +0000331 .. versionadded:: 2.6
Georg Brandl01ba86a2008-11-06 10:20:49 +0000332
Georg Brandl3591a8f2009-07-26 14:44:23 +0000333 .. method:: is_alive()
334 isAlive()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000335
Georg Brandl3591a8f2009-07-26 14:44:23 +0000336 Return whether the thread is alive.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000337
Brett Cannon11a30612010-07-23 12:30:10 +0000338 This method returns ``True`` just before the :meth:`run` method starts
339 until just after the :meth:`run` method terminates. The module function
Georg Brandlf4da6662009-09-19 12:04:16 +0000340 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000341
Georg Brandl3591a8f2009-07-26 14:44:23 +0000342 .. method:: isDaemon()
343 setDaemon()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000344
Georg Brandl3591a8f2009-07-26 14:44:23 +0000345 Old API for :attr:`~Thread.daemon`.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000346
Georg Brandl3591a8f2009-07-26 14:44:23 +0000347 .. attribute:: daemon
Georg Brandl01ba86a2008-11-06 10:20:49 +0000348
Georg Brandl3591a8f2009-07-26 14:44:23 +0000349 A boolean value indicating whether this thread is a daemon thread (True)
350 or not (False). This must be set before :meth:`start` is called,
351 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
352 from the creating thread; the main thread is not a daemon thread and
353 therefore all threads created in the main thread default to :attr:`daemon`
354 = ``False``.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000355
Georg Brandl3591a8f2009-07-26 14:44:23 +0000356 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000357
358
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359.. _lock-objects:
360
361Lock Objects
362------------
363
364A primitive lock is a synchronization primitive that is not owned by a
365particular thread when locked. In Python, it is currently the lowest level
366synchronization primitive available, implemented directly by the :mod:`thread`
367extension module.
368
369A primitive lock is in one of two states, "locked" or "unlocked". It is created
370in the unlocked state. It has two basic methods, :meth:`acquire` and
371:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
372to locked and returns immediately. When the state is locked, :meth:`acquire`
373blocks until a call to :meth:`release` in another thread changes it to unlocked,
374then the :meth:`acquire` call resets it to locked and returns. The
375:meth:`release` method should only be called in the locked state; it changes the
376state to unlocked and returns immediately. If an attempt is made to release an
377unlocked lock, a :exc:`RuntimeError` will be raised.
378
379When more than one thread is blocked in :meth:`acquire` waiting for the state to
380turn to unlocked, only one thread proceeds when a :meth:`release` call resets
381the state to unlocked; which one of the waiting threads proceeds is not defined,
382and may vary across implementations.
383
384All methods are executed atomically.
385
386
387.. method:: Lock.acquire([blocking=1])
388
389 Acquire a lock, blocking or non-blocking.
390
391 When invoked without arguments, block until the lock is unlocked, then set it to
392 locked, and return true.
393
394 When invoked with the *blocking* argument set to true, do the same thing as when
395 called without arguments, and return true.
396
397 When invoked with the *blocking* argument set to false, do not block. If a call
398 without an argument would block, return false immediately; otherwise, do the
399 same thing as when called without arguments, and return true.
400
401
402.. method:: Lock.release()
403
404 Release a lock.
405
406 When the lock is locked, reset it to unlocked, and return. If any other threads
407 are blocked waiting for the lock to become unlocked, allow exactly one of them
408 to proceed.
409
410 Do not call this method when the lock is unlocked.
411
412 There is no return value.
413
414
415.. _rlock-objects:
416
417RLock Objects
418-------------
419
420A reentrant lock is a synchronization primitive that may be acquired multiple
421times by the same thread. Internally, it uses the concepts of "owning thread"
422and "recursion level" in addition to the locked/unlocked state used by primitive
423locks. In the locked state, some thread owns the lock; in the unlocked state,
424no thread owns it.
425
426To lock the lock, a thread calls its :meth:`acquire` method; this returns once
427the thread owns the lock. To unlock the lock, a thread calls its
428:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
429nested; only the final :meth:`release` (the :meth:`release` of the outermost
430pair) resets the lock to unlocked and allows another thread blocked in
431:meth:`acquire` to proceed.
432
433
434.. method:: RLock.acquire([blocking=1])
435
436 Acquire a lock, blocking or non-blocking.
437
438 When invoked without arguments: if this thread already owns the lock, increment
439 the recursion level by one, and return immediately. Otherwise, if another
440 thread owns the lock, block until the lock is unlocked. Once the lock is
441 unlocked (not owned by any thread), then grab ownership, set the recursion level
442 to one, and return. If more than one thread is blocked waiting until the lock
443 is unlocked, only one at a time will be able to grab ownership of the lock.
444 There is no return value in this case.
445
446 When invoked with the *blocking* argument set to true, do the same thing as when
447 called without arguments, and return true.
448
449 When invoked with the *blocking* argument set to false, do not block. If a call
450 without an argument would block, return false immediately; otherwise, do the
451 same thing as when called without arguments, and return true.
452
453
454.. method:: RLock.release()
455
456 Release a lock, decrementing the recursion level. If after the decrement it is
457 zero, reset the lock to unlocked (not owned by any thread), and if any other
458 threads are blocked waiting for the lock to become unlocked, allow exactly one
459 of them to proceed. If after the decrement the recursion level is still
460 nonzero, the lock remains locked and owned by the calling thread.
461
462 Only call this method when the calling thread owns the lock. A
463 :exc:`RuntimeError` is raised if this method is called when the lock is
464 unlocked.
465
466 There is no return value.
467
468
469.. _condition-objects:
470
471Condition Objects
472-----------------
473
474A condition variable is always associated with some kind of lock; this can be
475passed in or one will be created by default. (Passing one in is useful when
476several condition variables must share the same lock.)
477
478A condition variable has :meth:`acquire` and :meth:`release` methods that call
479the corresponding methods of the associated lock. It also has a :meth:`wait`
480method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
481be called when the calling thread has acquired the lock, otherwise a
482:exc:`RuntimeError` is raised.
483
484The :meth:`wait` method releases the lock, and then blocks until it is awakened
485by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
486another thread. Once awakened, it re-acquires the lock and returns. It is also
487possible to specify a timeout.
488
489The :meth:`notify` method wakes up one of the threads waiting for the condition
490variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
491waiting for the condition variable.
492
493Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
494this means that the thread or threads awakened will not return from their
495:meth:`wait` call immediately, but only when the thread that called
496:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
497
498Tip: the typical programming style using condition variables uses the lock to
499synchronize access to some shared state; threads that are interested in a
500particular change of state call :meth:`wait` repeatedly until they see the
501desired state, while threads that modify the state call :meth:`notify` or
502:meth:`notifyAll` when they change the state in such a way that it could
503possibly be a desired state for one of the waiters. For example, the following
504code is a generic producer-consumer situation with unlimited buffer capacity::
505
506 # Consume one item
507 cv.acquire()
508 while not an_item_is_available():
509 cv.wait()
510 get_an_available_item()
511 cv.release()
512
513 # Produce one item
514 cv.acquire()
515 make_an_item_available()
516 cv.notify()
517 cv.release()
518
519To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
520state change can be interesting for only one or several waiting threads. E.g.
521in a typical producer-consumer situation, adding one item to the buffer only
522needs to wake up one consumer thread.
523
524
525.. class:: Condition([lock])
526
Georg Brandl3591a8f2009-07-26 14:44:23 +0000527 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
528 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
529 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000530
Georg Brandl3591a8f2009-07-26 14:44:23 +0000531 .. method:: acquire(*args)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000532
Georg Brandl3591a8f2009-07-26 14:44:23 +0000533 Acquire the underlying lock. This method calls the corresponding method on
534 the underlying lock; the return value is whatever that method returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000535
Georg Brandl3591a8f2009-07-26 14:44:23 +0000536 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
Georg Brandl3591a8f2009-07-26 14:44:23 +0000538 Release the underlying lock. This method calls the corresponding method on
539 the underlying lock; there is no return value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000540
Georg Brandl3591a8f2009-07-26 14:44:23 +0000541 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000542
Georg Brandl3591a8f2009-07-26 14:44:23 +0000543 Wait until notified or until a timeout occurs. If the calling thread has not
544 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545
Georg Brandl3591a8f2009-07-26 14:44:23 +0000546 This method releases the underlying lock, and then blocks until it is
547 awakened by a :meth:`notify` or :meth:`notifyAll` call for the same
548 condition variable in another thread, or until the optional timeout
549 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000550
Georg Brandl3591a8f2009-07-26 14:44:23 +0000551 When the *timeout* argument is present and not ``None``, it should be a
552 floating point number specifying a timeout for the operation in seconds
553 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000554
Georg Brandl3591a8f2009-07-26 14:44:23 +0000555 When the underlying lock is an :class:`RLock`, it is not released using
556 its :meth:`release` method, since this may not actually unlock the lock
557 when it was acquired multiple times recursively. Instead, an internal
558 interface of the :class:`RLock` class is used, which really unlocks it
559 even when it has been recursively acquired several times. Another internal
560 interface is then used to restore the recursion level when the lock is
561 reacquired.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562
Georg Brandl3591a8f2009-07-26 14:44:23 +0000563 .. method:: notify()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564
Georg Brandl3591a8f2009-07-26 14:44:23 +0000565 Wake up a thread waiting on this condition, if any. If the calling thread
566 has not acquired the lock when this method is called, a
567 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
Georg Brandl3591a8f2009-07-26 14:44:23 +0000569 This method wakes up one of the threads waiting for the condition
570 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
Georg Brandl3591a8f2009-07-26 14:44:23 +0000572 The current implementation wakes up exactly one thread, if any are
573 waiting. However, it's not safe to rely on this behavior. A future,
574 optimized implementation may occasionally wake up more than one thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
Georg Brandl3591a8f2009-07-26 14:44:23 +0000576 Note: the awakened thread does not actually return from its :meth:`wait`
577 call until it can reacquire the lock. Since :meth:`notify` does not
578 release the lock, its caller should.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579
Georg Brandl3591a8f2009-07-26 14:44:23 +0000580 .. method:: notify_all()
581 notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000582
Georg Brandl3591a8f2009-07-26 14:44:23 +0000583 Wake up all threads waiting on this condition. This method acts like
584 :meth:`notify`, but wakes up all waiting threads instead of one. If the
585 calling thread has not acquired the lock when this method is called, a
586 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000587
588
589.. _semaphore-objects:
590
591Semaphore Objects
592-----------------
593
594This is one of the oldest synchronization primitives in the history of computer
595science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
596used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
597
598A semaphore manages an internal counter which is decremented by each
599:meth:`acquire` call and incremented by each :meth:`release` call. The counter
600can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
601waiting until some other thread calls :meth:`release`.
602
603
604.. class:: Semaphore([value])
605
606 The optional argument gives the initial *value* for the internal counter; it
607 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
608 raised.
609
Georg Brandl3591a8f2009-07-26 14:44:23 +0000610 .. method:: acquire([blocking])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000611
Georg Brandl3591a8f2009-07-26 14:44:23 +0000612 Acquire a semaphore.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000613
Georg Brandl3591a8f2009-07-26 14:44:23 +0000614 When invoked without arguments: if the internal counter is larger than
615 zero on entry, decrement it by one and return immediately. If it is zero
616 on entry, block, waiting until some other thread has called
617 :meth:`release` to make it larger than zero. This is done with proper
618 interlocking so that if multiple :meth:`acquire` calls are blocked,
619 :meth:`release` will wake exactly one of them up. The implementation may
620 pick one at random, so the order in which blocked threads are awakened
621 should not be relied on. There is no return value in this case.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000622
Georg Brandl3591a8f2009-07-26 14:44:23 +0000623 When invoked with *blocking* set to true, do the same thing as when called
624 without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
Georg Brandl3591a8f2009-07-26 14:44:23 +0000626 When invoked with *blocking* set to false, do not block. If a call
627 without an argument would block, return false immediately; otherwise, do
628 the same thing as when called without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000629
Georg Brandl3591a8f2009-07-26 14:44:23 +0000630 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000631
Georg Brandl3591a8f2009-07-26 14:44:23 +0000632 Release a semaphore, incrementing the internal counter by one. When it
633 was zero on entry and another thread is waiting for it to become larger
634 than zero again, wake up that thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
636
637.. _semaphore-examples:
638
639:class:`Semaphore` Example
640^^^^^^^^^^^^^^^^^^^^^^^^^^
641
642Semaphores are often used to guard resources with limited capacity, for example,
643a database server. In any situation where the size of the resource size is
644fixed, you should use a bounded semaphore. Before spawning any worker threads,
645your main thread would initialize the semaphore::
646
647 maxconnections = 5
648 ...
649 pool_sema = BoundedSemaphore(value=maxconnections)
650
651Once spawned, worker threads call the semaphore's acquire and release methods
652when they need to connect to the server::
653
654 pool_sema.acquire()
655 conn = connectdb()
656 ... use connection ...
657 conn.close()
658 pool_sema.release()
659
660The use of a bounded semaphore reduces the chance that a programming error which
661causes the semaphore to be released more than it's acquired will go undetected.
662
663
664.. _event-objects:
665
666Event Objects
667-------------
668
669This is one of the simplest mechanisms for communication between threads: one
670thread signals an event and other threads wait for it.
671
672An event object manages an internal flag that can be set to true with the
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000673:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674:meth:`wait` method blocks until the flag is true.
675
676
677.. class:: Event()
678
679 The internal flag is initially false.
680
Georg Brandl3591a8f2009-07-26 14:44:23 +0000681 .. method:: is_set()
682 isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000683
Georg Brandl3591a8f2009-07-26 14:44:23 +0000684 Return true if and only if the internal flag is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000685
Facundo Batista47b66592010-01-25 06:15:01 +0000686 .. versionchanged:: 2.6
687 The ``is_set()`` syntax is new.
688
Georg Brandl3591a8f2009-07-26 14:44:23 +0000689 .. method:: set()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000690
Georg Brandl3591a8f2009-07-26 14:44:23 +0000691 Set the internal flag to true. All threads waiting for it to become true
692 are awakened. Threads that call :meth:`wait` once the flag is true will
693 not block at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Georg Brandl3591a8f2009-07-26 14:44:23 +0000695 .. method:: clear()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000696
Georg Brandl3591a8f2009-07-26 14:44:23 +0000697 Reset the internal flag to false. Subsequently, threads calling
698 :meth:`wait` will block until :meth:`.set` is called to set the internal
699 flag to true again.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Georg Brandl3591a8f2009-07-26 14:44:23 +0000701 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702
Georg Brandl3591a8f2009-07-26 14:44:23 +0000703 Block until the internal flag is true. If the internal flag is true on
704 entry, return immediately. Otherwise, block until another thread calls
705 :meth:`.set` to set the flag to true, or until the optional timeout
706 occurs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000707
Georg Brandl3591a8f2009-07-26 14:44:23 +0000708 When the timeout argument is present and not ``None``, it should be a
709 floating point number specifying a timeout for the operation in seconds
710 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711
Georg Brandl3591a8f2009-07-26 14:44:23 +0000712 This method returns the internal flag on exit, so it will always return
713 ``True`` except if a timeout is given and the operation times out.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000714
Georg Brandl3591a8f2009-07-26 14:44:23 +0000715 .. versionchanged:: 2.7
716 Previously, the method always returned ``None``.
Georg Brandlef660e82009-03-31 20:41:08 +0000717
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719.. _timer-objects:
720
721Timer Objects
722-------------
723
724This class represents an action that should be run only after a certain amount
725of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
726and as such also functions as an example of creating custom threads.
727
728Timers are started, as with threads, by calling their :meth:`start` method. The
729timer can be stopped (before its action has begun) by calling the :meth:`cancel`
730method. The interval the timer will wait before executing its action may not be
731exactly the same as the interval specified by the user.
732
733For example::
734
735 def hello():
736 print "hello, world"
737
738 t = Timer(30.0, hello)
739 t.start() # after 30 seconds, "hello, world" will be printed
740
741
742.. class:: Timer(interval, function, args=[], kwargs={})
743
744 Create a timer that will run *function* with arguments *args* and keyword
745 arguments *kwargs*, after *interval* seconds have passed.
746
Georg Brandl3591a8f2009-07-26 14:44:23 +0000747 .. method:: cancel()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748
Georg Brandl3591a8f2009-07-26 14:44:23 +0000749 Stop the timer, and cancel the execution of the timer's action. This will
750 only work if the timer is still in its waiting stage.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
752
753.. _with-locks:
754
755Using locks, conditions, and semaphores in the :keyword:`with` statement
756------------------------------------------------------------------------
757
758All of the objects provided by this module that have :meth:`acquire` and
759:meth:`release` methods can be used as context managers for a :keyword:`with`
760statement. The :meth:`acquire` method will be called when the block is entered,
761and :meth:`release` will be called when the block is exited.
762
763Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
764:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
765:keyword:`with` statement context managers. For example::
766
Georg Brandl8ec7f652007-08-15 14:28:01 +0000767 import threading
768
769 some_rlock = threading.RLock()
770
771 with some_rlock:
772 print "some_rlock is locked while this executes"
773
Georg Brandl2e255512008-03-13 07:21:41 +0000774
775.. _threaded-imports:
776
777Importing in threaded code
778--------------------------
779
780While the import machinery is thread safe, there are two key
781restrictions on threaded imports due to inherent limitations in the way
782that thread safety is provided:
783
784* Firstly, other than in the main module, an import should not have the
785 side effect of spawning a new thread and then waiting for that thread in
786 any way. Failing to abide by this restriction can lead to a deadlock if
787 the spawned thread directly or indirectly attempts to import a module.
788* Secondly, all import attempts must be completed before the interpreter
789 starts shutting itself down. This can be most easily achieved by only
790 performing imports from non-daemon threads created through the threading
791 module. Daemon threads and threads created directly with the thread
792 module will require some other form of synchronization to ensure they do
793 not attempt imports after system shutdown has commenced. Failure to
794 abide by this restriction will lead to intermittent exceptions and
795 crashes during interpreter shutdown (as the late imports attempt to
796 access machinery which is no longer in a valid state).