blob: b22d3d12e6b2dfe498e6996dcdaa9f13e92414ff [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
Raymond Hettingere679a372010-11-05 23:58:42 +000029.. seealso::
30
31 Latest version of the `threading module Python source code
32 <http://svn.python.org/view/python/branches/release27-maint/Lib/threading.py?view=markup>`_
Georg Brandl2cd82a82009-03-09 14:25:07 +000033
34This module defines the following functions and objects:
Georg Brandl8ec7f652007-08-15 14:28:01 +000035
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000036.. function:: active_count()
Benjamin Petersonf4395602008-06-11 17:50:00 +000037 activeCount()
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39 Return the number of :class:`Thread` objects currently alive. The returned
Georg Brandlf4da6662009-09-19 12:04:16 +000040 count is equal to the length of the list returned by :func:`.enumerate`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000041
42
43.. function:: Condition()
44 :noindex:
45
46 A factory function that returns a new condition variable object. A condition
47 variable allows one or more threads to wait until they are notified by another
48 thread.
49
Georg Brandl21946af2010-10-06 09:28:45 +000050 See :ref:`condition-objects`.
51
Georg Brandl8ec7f652007-08-15 14:28:01 +000052
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000053.. function:: current_thread()
Benjamin Petersonf4395602008-06-11 17:50:00 +000054 currentThread()
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
56 Return the current :class:`Thread` object, corresponding to the caller's thread
57 of control. If the caller's thread of control was not created through the
58 :mod:`threading` module, a dummy thread object with limited functionality is
59 returned.
60
61
62.. function:: enumerate()
63
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000064 Return a list of all :class:`Thread` objects currently alive. The list
65 includes daemonic threads, dummy thread objects created by
66 :func:`current_thread`, and the main thread. It excludes terminated threads
67 and threads that have not yet been started.
Georg Brandl8ec7f652007-08-15 14:28:01 +000068
69
70.. function:: Event()
71 :noindex:
72
73 A factory function that returns a new event object. An event manages a flag
Georg Brandl9fa61bb2009-07-26 14:19:57 +000074 that can be set to true with the :meth:`~Event.set` method and reset to false
75 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
76 is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
Georg Brandl21946af2010-10-06 09:28:45 +000078 See :ref:`event-objects`.
79
Georg Brandl8ec7f652007-08-15 14:28:01 +000080
81.. class:: local
82
83 A class that represents thread-local data. Thread-local data are data whose
84 values are thread specific. To manage thread-local data, just create an
85 instance of :class:`local` (or a subclass) and store attributes on it::
86
87 mydata = threading.local()
88 mydata.x = 1
89
90 The instance's values will be different for separate threads.
91
92 For more details and extensive examples, see the documentation string of the
93 :mod:`_threading_local` module.
94
95 .. versionadded:: 2.4
96
97
98.. function:: Lock()
99
100 A factory function that returns a new primitive lock object. Once a thread has
101 acquired it, subsequent attempts to acquire it block, until it is released; any
102 thread may release it.
103
Georg Brandl21946af2010-10-06 09:28:45 +0000104 See :ref:`lock-objects`.
105
Georg Brandl8ec7f652007-08-15 14:28:01 +0000106
107.. function:: RLock()
108
109 A factory function that returns a new reentrant lock object. A reentrant lock
110 must be released by the thread that acquired it. Once a thread has acquired a
111 reentrant lock, the same thread may acquire it again without blocking; the
112 thread must release it once for each time it has acquired it.
113
Georg Brandl21946af2010-10-06 09:28:45 +0000114 See :ref:`rlock-objects`.
115
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116
117.. function:: Semaphore([value])
118 :noindex:
119
120 A factory function that returns a new semaphore object. A semaphore manages a
121 counter representing the number of :meth:`release` calls minus the number of
122 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
123 if necessary until it can return without making the counter negative. If not
124 given, *value* defaults to 1.
125
Georg Brandl21946af2010-10-06 09:28:45 +0000126 See :ref:`semaphore-objects`.
127
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
129.. function:: BoundedSemaphore([value])
130
131 A factory function that returns a new bounded semaphore object. A bounded
132 semaphore checks to make sure its current value doesn't exceed its initial
133 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
134 are used to guard resources with limited capacity. If the semaphore is released
135 too many times it's a sign of a bug. If not given, *value* defaults to 1.
136
137
138.. class:: Thread
Georg Brandl21946af2010-10-06 09:28:45 +0000139 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000140
141 A class that represents a thread of control. This class can be safely
142 subclassed in a limited fashion.
143
Georg Brandl21946af2010-10-06 09:28:45 +0000144 See :ref:`thread-objects`.
145
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
147.. class:: Timer
Georg Brandl21946af2010-10-06 09:28:45 +0000148 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
150 A thread that executes a function after a specified interval has passed.
151
Georg Brandl21946af2010-10-06 09:28:45 +0000152 See :ref:`timer-objects`.
153
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154
155.. function:: settrace(func)
156
157 .. index:: single: trace function
158
159 Set a trace function for all threads started from the :mod:`threading` module.
160 The *func* will be passed to :func:`sys.settrace` for each thread, before its
161 :meth:`run` method is called.
162
163 .. versionadded:: 2.3
164
165
166.. function:: setprofile(func)
167
168 .. index:: single: profile function
169
170 Set a profile function for all threads started from the :mod:`threading` module.
171 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
172 :meth:`run` method is called.
173
174 .. versionadded:: 2.3
175
176
177.. function:: stack_size([size])
178
179 Return the thread stack size used when creating new threads. The optional
180 *size* argument specifies the stack size to be used for subsequently created
181 threads, and must be 0 (use platform or configured default) or a positive
182 integer value of at least 32,768 (32kB). If changing the thread stack size is
183 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
184 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
185 is currently the minimum supported stack size value to guarantee sufficient
186 stack space for the interpreter itself. Note that some platforms may have
187 particular restrictions on values for the stack size, such as requiring a
188 minimum stack size > 32kB or requiring allocation in multiples of the system
189 memory page size - platform documentation should be referred to for more
190 information (4kB pages are common; using multiples of 4096 for the stack size is
191 the suggested approach in the absence of more specific information).
192 Availability: Windows, systems with POSIX threads.
193
194 .. versionadded:: 2.5
195
196Detailed interfaces for the objects are documented below.
197
198The design of this module is loosely based on Java's threading model. However,
199where Java makes locks and condition variables basic behavior of every object,
200they are separate objects in Python. Python's :class:`Thread` class supports a
201subset of the behavior of Java's Thread class; currently, there are no
202priorities, no thread groups, and threads cannot be destroyed, stopped,
203suspended, resumed, or interrupted. The static methods of Java's Thread class,
204when implemented, are mapped to module-level functions.
205
206All of the methods described below are executed atomically.
207
208
Georg Brandl01ba86a2008-11-06 10:20:49 +0000209.. _thread-objects:
210
211Thread Objects
212--------------
213
214This class represents an activity that is run in a separate thread of control.
215There are two ways to specify the activity: by passing a callable object to the
216constructor, or by overriding the :meth:`run` method in a subclass. No other
217methods (except for the constructor) should be overridden in a subclass. In
218other words, *only* override the :meth:`__init__` and :meth:`run` methods of
219this class.
220
221Once a thread object is created, its activity must be started by calling the
222thread's :meth:`start` method. This invokes the :meth:`run` method in a
223separate thread of control.
224
225Once the thread's activity is started, the thread is considered 'alive'. It
226stops being alive when its :meth:`run` method terminates -- either normally, or
227by raising an unhandled exception. The :meth:`is_alive` method tests whether the
228thread is alive.
229
230Other threads can call a thread's :meth:`join` method. This blocks the calling
231thread until the thread whose :meth:`join` method is called is terminated.
232
233A thread has a name. The name can be passed to the constructor, and read or
234changed through the :attr:`name` attribute.
235
236A thread can be flagged as a "daemon thread". The significance of this flag is
237that the entire Python program exits when only daemon threads are left. The
238initial value is inherited from the creating thread. The flag can be set
Georg Brandlecd2afa2009-02-05 11:40:35 +0000239through the :attr:`daemon` property.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000240
241There is a "main thread" object; this corresponds to the initial thread of
242control in the Python program. It is not a daemon thread.
243
244There is the possibility that "dummy thread objects" are created. These are
245thread objects corresponding to "alien threads", which are threads of control
246started outside the threading module, such as directly from C code. Dummy
247thread objects have limited functionality; they are always considered alive and
248daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
249impossible to detect the termination of alien threads.
250
251
252.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
253
Georg Brandl3591a8f2009-07-26 14:44:23 +0000254 This constructor should always be called with keyword arguments. Arguments
255 are:
Georg Brandl01ba86a2008-11-06 10:20:49 +0000256
257 *group* should be ``None``; reserved for future extension when a
258 :class:`ThreadGroup` class is implemented.
259
260 *target* is the callable object to be invoked by the :meth:`run` method.
261 Defaults to ``None``, meaning nothing is called.
262
Georg Brandl3591a8f2009-07-26 14:44:23 +0000263 *name* is the thread name. By default, a unique name is constructed of the
264 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000265
266 *args* is the argument tuple for the target invocation. Defaults to ``()``.
267
268 *kwargs* is a dictionary of keyword arguments for the target invocation.
269 Defaults to ``{}``.
270
Georg Brandl3591a8f2009-07-26 14:44:23 +0000271 If the subclass overrides the constructor, it must make sure to invoke the
272 base class constructor (``Thread.__init__()``) before doing anything else to
273 the thread.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000274
Georg Brandl3591a8f2009-07-26 14:44:23 +0000275 .. method:: start()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000276
Georg Brandl3591a8f2009-07-26 14:44:23 +0000277 Start the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000278
Georg Brandl3591a8f2009-07-26 14:44:23 +0000279 It must be called at most once per thread object. It arranges for the
280 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000281
Georg Brandl3591a8f2009-07-26 14:44:23 +0000282 This method will raise a :exc:`RuntimeException` if called more than once
283 on the same thread object.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000284
Georg Brandl3591a8f2009-07-26 14:44:23 +0000285 .. method:: run()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000286
Georg Brandl3591a8f2009-07-26 14:44:23 +0000287 Method representing the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000288
Georg Brandl3591a8f2009-07-26 14:44:23 +0000289 You may override this method in a subclass. The standard :meth:`run`
290 method invokes the callable object passed to the object's constructor as
291 the *target* argument, if any, with sequential and keyword arguments taken
292 from the *args* and *kwargs* arguments, respectively.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000293
Georg Brandl3591a8f2009-07-26 14:44:23 +0000294 .. method:: join([timeout])
Georg Brandl01ba86a2008-11-06 10:20:49 +0000295
Georg Brandl3591a8f2009-07-26 14:44:23 +0000296 Wait until the thread terminates. This blocks the calling thread until the
297 thread whose :meth:`join` method is called terminates -- either normally
298 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000299
Georg Brandl3591a8f2009-07-26 14:44:23 +0000300 When the *timeout* argument is present and not ``None``, it should be a
301 floating point number specifying a timeout for the operation in seconds
302 (or fractions thereof). As :meth:`join` always returns ``None``, you must
303 call :meth:`isAlive` after :meth:`join` to decide whether a timeout
304 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000305
Georg Brandl3591a8f2009-07-26 14:44:23 +0000306 When the *timeout* argument is not present or ``None``, the operation will
307 block until the thread terminates.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000308
Georg Brandl3591a8f2009-07-26 14:44:23 +0000309 A thread can be :meth:`join`\ ed many times.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000310
Georg Brandl3591a8f2009-07-26 14:44:23 +0000311 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
312 the current thread as that would cause a deadlock. It is also an error to
313 :meth:`join` a thread before it has been started and attempts to do so
314 raises the same exception.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000315
Georg Brandl3591a8f2009-07-26 14:44:23 +0000316 .. method:: getName()
317 setName()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000318
Georg Brandl3591a8f2009-07-26 14:44:23 +0000319 Old API for :attr:`~Thread.name`.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000320
Georg Brandl3591a8f2009-07-26 14:44:23 +0000321 .. attribute:: name
Georg Brandl01ba86a2008-11-06 10:20:49 +0000322
Georg Brandl3591a8f2009-07-26 14:44:23 +0000323 A string used for identification purposes only. It has no semantics.
324 Multiple threads may be given the same name. The initial name is set by
325 the constructor.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000326
Georg Brandl3591a8f2009-07-26 14:44:23 +0000327 .. attribute:: ident
Georg Brandl01ba86a2008-11-06 10:20:49 +0000328
Georg Brandl3591a8f2009-07-26 14:44:23 +0000329 The 'thread identifier' of this thread or ``None`` if the thread has not
330 been started. This is a nonzero integer. See the
331 :func:`thread.get_ident()` function. Thread identifiers may be recycled
332 when a thread exits and another thread is created. The identifier is
333 available even after the thread has exited.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000334
Georg Brandl3591a8f2009-07-26 14:44:23 +0000335 .. versionadded:: 2.6
Georg Brandl01ba86a2008-11-06 10:20:49 +0000336
Georg Brandl3591a8f2009-07-26 14:44:23 +0000337 .. method:: is_alive()
338 isAlive()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000339
Georg Brandl3591a8f2009-07-26 14:44:23 +0000340 Return whether the thread is alive.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000341
Brett Cannon11a30612010-07-23 12:30:10 +0000342 This method returns ``True`` just before the :meth:`run` method starts
343 until just after the :meth:`run` method terminates. The module function
Georg Brandlf4da6662009-09-19 12:04:16 +0000344 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000345
Georg Brandl3591a8f2009-07-26 14:44:23 +0000346 .. method:: isDaemon()
347 setDaemon()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000348
Georg Brandl3591a8f2009-07-26 14:44:23 +0000349 Old API for :attr:`~Thread.daemon`.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000350
Georg Brandl3591a8f2009-07-26 14:44:23 +0000351 .. attribute:: daemon
Georg Brandl01ba86a2008-11-06 10:20:49 +0000352
Georg Brandl3591a8f2009-07-26 14:44:23 +0000353 A boolean value indicating whether this thread is a daemon thread (True)
354 or not (False). This must be set before :meth:`start` is called,
355 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
356 from the creating thread; the main thread is not a daemon thread and
357 therefore all threads created in the main thread default to :attr:`daemon`
358 = ``False``.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000359
Georg Brandl3591a8f2009-07-26 14:44:23 +0000360 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000361
362
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363.. _lock-objects:
364
365Lock Objects
366------------
367
368A primitive lock is a synchronization primitive that is not owned by a
369particular thread when locked. In Python, it is currently the lowest level
370synchronization primitive available, implemented directly by the :mod:`thread`
371extension module.
372
373A primitive lock is in one of two states, "locked" or "unlocked". It is created
374in the unlocked state. It has two basic methods, :meth:`acquire` and
375:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
376to locked and returns immediately. When the state is locked, :meth:`acquire`
377blocks until a call to :meth:`release` in another thread changes it to unlocked,
378then the :meth:`acquire` call resets it to locked and returns. The
379:meth:`release` method should only be called in the locked state; it changes the
380state to unlocked and returns immediately. If an attempt is made to release an
381unlocked lock, a :exc:`RuntimeError` will be raised.
382
383When more than one thread is blocked in :meth:`acquire` waiting for the state to
384turn to unlocked, only one thread proceeds when a :meth:`release` call resets
385the state to unlocked; which one of the waiting threads proceeds is not defined,
386and may vary across implementations.
387
388All methods are executed atomically.
389
390
391.. method:: Lock.acquire([blocking=1])
392
393 Acquire a lock, blocking or non-blocking.
394
395 When invoked without arguments, block until the lock is unlocked, then set it to
396 locked, and return true.
397
398 When invoked with the *blocking* argument set to true, do the same thing as when
399 called without arguments, and return true.
400
401 When invoked with the *blocking* argument set to false, do not block. If a call
402 without an argument would block, return false immediately; otherwise, do the
403 same thing as when called without arguments, and return true.
404
405
406.. method:: Lock.release()
407
408 Release a lock.
409
410 When the lock is locked, reset it to unlocked, and return. If any other threads
411 are blocked waiting for the lock to become unlocked, allow exactly one of them
412 to proceed.
413
414 Do not call this method when the lock is unlocked.
415
416 There is no return value.
417
418
419.. _rlock-objects:
420
421RLock Objects
422-------------
423
424A reentrant lock is a synchronization primitive that may be acquired multiple
425times by the same thread. Internally, it uses the concepts of "owning thread"
426and "recursion level" in addition to the locked/unlocked state used by primitive
427locks. In the locked state, some thread owns the lock; in the unlocked state,
428no thread owns it.
429
430To lock the lock, a thread calls its :meth:`acquire` method; this returns once
431the thread owns the lock. To unlock the lock, a thread calls its
432:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
433nested; only the final :meth:`release` (the :meth:`release` of the outermost
434pair) resets the lock to unlocked and allows another thread blocked in
435:meth:`acquire` to proceed.
436
437
438.. method:: RLock.acquire([blocking=1])
439
440 Acquire a lock, blocking or non-blocking.
441
442 When invoked without arguments: if this thread already owns the lock, increment
443 the recursion level by one, and return immediately. Otherwise, if another
444 thread owns the lock, block until the lock is unlocked. Once the lock is
445 unlocked (not owned by any thread), then grab ownership, set the recursion level
446 to one, and return. If more than one thread is blocked waiting until the lock
447 is unlocked, only one at a time will be able to grab ownership of the lock.
448 There is no return value in this case.
449
450 When invoked with the *blocking* argument set to true, do the same thing as when
451 called without arguments, and return true.
452
453 When invoked with the *blocking* argument set to false, do not block. If a call
454 without an argument would block, return false immediately; otherwise, do the
455 same thing as when called without arguments, and return true.
456
457
458.. method:: RLock.release()
459
460 Release a lock, decrementing the recursion level. If after the decrement it is
461 zero, reset the lock to unlocked (not owned by any thread), and if any other
462 threads are blocked waiting for the lock to become unlocked, allow exactly one
463 of them to proceed. If after the decrement the recursion level is still
464 nonzero, the lock remains locked and owned by the calling thread.
465
466 Only call this method when the calling thread owns the lock. A
467 :exc:`RuntimeError` is raised if this method is called when the lock is
468 unlocked.
469
470 There is no return value.
471
472
473.. _condition-objects:
474
475Condition Objects
476-----------------
477
478A condition variable is always associated with some kind of lock; this can be
479passed in or one will be created by default. (Passing one in is useful when
480several condition variables must share the same lock.)
481
482A condition variable has :meth:`acquire` and :meth:`release` methods that call
483the corresponding methods of the associated lock. It also has a :meth:`wait`
484method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
485be called when the calling thread has acquired the lock, otherwise a
486:exc:`RuntimeError` is raised.
487
488The :meth:`wait` method releases the lock, and then blocks until it is awakened
489by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
490another thread. Once awakened, it re-acquires the lock and returns. It is also
491possible to specify a timeout.
492
493The :meth:`notify` method wakes up one of the threads waiting for the condition
494variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
495waiting for the condition variable.
496
497Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
498this means that the thread or threads awakened will not return from their
499:meth:`wait` call immediately, but only when the thread that called
500:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
501
502Tip: the typical programming style using condition variables uses the lock to
503synchronize access to some shared state; threads that are interested in a
504particular change of state call :meth:`wait` repeatedly until they see the
505desired state, while threads that modify the state call :meth:`notify` or
506:meth:`notifyAll` when they change the state in such a way that it could
507possibly be a desired state for one of the waiters. For example, the following
508code is a generic producer-consumer situation with unlimited buffer capacity::
509
510 # Consume one item
511 cv.acquire()
512 while not an_item_is_available():
513 cv.wait()
514 get_an_available_item()
515 cv.release()
516
517 # Produce one item
518 cv.acquire()
519 make_an_item_available()
520 cv.notify()
521 cv.release()
522
523To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
524state change can be interesting for only one or several waiting threads. E.g.
525in a typical producer-consumer situation, adding one item to the buffer only
526needs to wake up one consumer thread.
527
528
529.. class:: Condition([lock])
530
Georg Brandl3591a8f2009-07-26 14:44:23 +0000531 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
532 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
533 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000534
Georg Brandl3591a8f2009-07-26 14:44:23 +0000535 .. method:: acquire(*args)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000536
Georg Brandl3591a8f2009-07-26 14:44:23 +0000537 Acquire the underlying lock. This method calls the corresponding method on
538 the underlying lock; the return value is whatever that method returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539
Georg Brandl3591a8f2009-07-26 14:44:23 +0000540 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000541
Georg Brandl3591a8f2009-07-26 14:44:23 +0000542 Release the underlying lock. This method calls the corresponding method on
543 the underlying lock; there is no return value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000544
Georg Brandl3591a8f2009-07-26 14:44:23 +0000545 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
Georg Brandl3591a8f2009-07-26 14:44:23 +0000547 Wait until notified or until a timeout occurs. If the calling thread has not
548 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000549
Georg Brandl3591a8f2009-07-26 14:44:23 +0000550 This method releases the underlying lock, and then blocks until it is
551 awakened by a :meth:`notify` or :meth:`notifyAll` call for the same
552 condition variable in another thread, or until the optional timeout
553 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000554
Georg Brandl3591a8f2009-07-26 14:44:23 +0000555 When the *timeout* argument is present and not ``None``, it should be a
556 floating point number specifying a timeout for the operation in seconds
557 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000558
Georg Brandl3591a8f2009-07-26 14:44:23 +0000559 When the underlying lock is an :class:`RLock`, it is not released using
560 its :meth:`release` method, since this may not actually unlock the lock
561 when it was acquired multiple times recursively. Instead, an internal
562 interface of the :class:`RLock` class is used, which really unlocks it
563 even when it has been recursively acquired several times. Another internal
564 interface is then used to restore the recursion level when the lock is
565 reacquired.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000566
Georg Brandl3591a8f2009-07-26 14:44:23 +0000567 .. method:: notify()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
Georg Brandl3591a8f2009-07-26 14:44:23 +0000569 Wake up a thread waiting on this condition, if any. If the calling thread
570 has not acquired the lock when this method is called, a
571 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000572
Georg Brandl3591a8f2009-07-26 14:44:23 +0000573 This method wakes up one of the threads waiting for the condition
574 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
Georg Brandl3591a8f2009-07-26 14:44:23 +0000576 The current implementation wakes up exactly one thread, if any are
577 waiting. However, it's not safe to rely on this behavior. A future,
578 optimized implementation may occasionally wake up more than one thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579
Georg Brandl3591a8f2009-07-26 14:44:23 +0000580 Note: the awakened thread does not actually return from its :meth:`wait`
581 call until it can reacquire the lock. Since :meth:`notify` does not
582 release the lock, its caller should.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000583
Georg Brandl3591a8f2009-07-26 14:44:23 +0000584 .. method:: notify_all()
585 notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000586
Georg Brandl3591a8f2009-07-26 14:44:23 +0000587 Wake up all threads waiting on this condition. This method acts like
588 :meth:`notify`, but wakes up all waiting threads instead of one. If the
589 calling thread has not acquired the lock when this method is called, a
590 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000591
592
593.. _semaphore-objects:
594
595Semaphore Objects
596-----------------
597
598This is one of the oldest synchronization primitives in the history of computer
599science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
600used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
601
602A semaphore manages an internal counter which is decremented by each
603:meth:`acquire` call and incremented by each :meth:`release` call. The counter
604can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
605waiting until some other thread calls :meth:`release`.
606
607
608.. class:: Semaphore([value])
609
610 The optional argument gives the initial *value* for the internal counter; it
611 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
612 raised.
613
Georg Brandl3591a8f2009-07-26 14:44:23 +0000614 .. method:: acquire([blocking])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615
Georg Brandl3591a8f2009-07-26 14:44:23 +0000616 Acquire a semaphore.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
Georg Brandl3591a8f2009-07-26 14:44:23 +0000618 When invoked without arguments: if the internal counter is larger than
619 zero on entry, decrement it by one and return immediately. If it is zero
620 on entry, block, waiting until some other thread has called
621 :meth:`release` to make it larger than zero. This is done with proper
622 interlocking so that if multiple :meth:`acquire` calls are blocked,
623 :meth:`release` will wake exactly one of them up. The implementation may
624 pick one at random, so the order in which blocked threads are awakened
625 should not be relied on. There is no return value in this case.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000626
Georg Brandl3591a8f2009-07-26 14:44:23 +0000627 When invoked with *blocking* set to true, do the same thing as when called
628 without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000629
Georg Brandl3591a8f2009-07-26 14:44:23 +0000630 When invoked with *blocking* set to false, do not block. If a call
631 without an argument would block, return false immediately; otherwise, do
632 the same thing as when called without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633
Georg Brandl3591a8f2009-07-26 14:44:23 +0000634 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Georg Brandl3591a8f2009-07-26 14:44:23 +0000636 Release a semaphore, incrementing the internal counter by one. When it
637 was zero on entry and another thread is waiting for it to become larger
638 than zero again, wake up that thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639
640
641.. _semaphore-examples:
642
643:class:`Semaphore` Example
644^^^^^^^^^^^^^^^^^^^^^^^^^^
645
646Semaphores are often used to guard resources with limited capacity, for example,
647a database server. In any situation where the size of the resource size is
648fixed, you should use a bounded semaphore. Before spawning any worker threads,
649your main thread would initialize the semaphore::
650
651 maxconnections = 5
652 ...
653 pool_sema = BoundedSemaphore(value=maxconnections)
654
655Once spawned, worker threads call the semaphore's acquire and release methods
656when they need to connect to the server::
657
658 pool_sema.acquire()
659 conn = connectdb()
660 ... use connection ...
661 conn.close()
662 pool_sema.release()
663
664The use of a bounded semaphore reduces the chance that a programming error which
665causes the semaphore to be released more than it's acquired will go undetected.
666
667
668.. _event-objects:
669
670Event Objects
671-------------
672
673This is one of the simplest mechanisms for communication between threads: one
674thread signals an event and other threads wait for it.
675
676An event object manages an internal flag that can be set to true with the
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000677:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678:meth:`wait` method blocks until the flag is true.
679
680
681.. class:: Event()
682
683 The internal flag is initially false.
684
Georg Brandl3591a8f2009-07-26 14:44:23 +0000685 .. method:: is_set()
686 isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000687
Georg Brandl3591a8f2009-07-26 14:44:23 +0000688 Return true if and only if the internal flag is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000689
Facundo Batista47b66592010-01-25 06:15:01 +0000690 .. versionchanged:: 2.6
691 The ``is_set()`` syntax is new.
692
Georg Brandl3591a8f2009-07-26 14:44:23 +0000693 .. method:: set()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Georg Brandl3591a8f2009-07-26 14:44:23 +0000695 Set the internal flag to true. All threads waiting for it to become true
696 are awakened. Threads that call :meth:`wait` once the flag is true will
697 not block at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698
Georg Brandl3591a8f2009-07-26 14:44:23 +0000699 .. method:: clear()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Georg Brandl3591a8f2009-07-26 14:44:23 +0000701 Reset the internal flag to false. Subsequently, threads calling
702 :meth:`wait` will block until :meth:`.set` is called to set the internal
703 flag to true again.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000704
Georg Brandl3591a8f2009-07-26 14:44:23 +0000705 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000706
Georg Brandl3591a8f2009-07-26 14:44:23 +0000707 Block until the internal flag is true. If the internal flag is true on
708 entry, return immediately. Otherwise, block until another thread calls
709 :meth:`.set` to set the flag to true, or until the optional timeout
710 occurs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711
Georg Brandl3591a8f2009-07-26 14:44:23 +0000712 When the timeout argument is present and not ``None``, it should be a
713 floating point number specifying a timeout for the operation in seconds
714 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000715
Georg Brandl3591a8f2009-07-26 14:44:23 +0000716 This method returns the internal flag on exit, so it will always return
717 ``True`` except if a timeout is given and the operation times out.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
Georg Brandl3591a8f2009-07-26 14:44:23 +0000719 .. versionchanged:: 2.7
720 Previously, the method always returned ``None``.
Georg Brandlef660e82009-03-31 20:41:08 +0000721
Georg Brandl8ec7f652007-08-15 14:28:01 +0000722
Georg Brandl8ec7f652007-08-15 14:28:01 +0000723.. _timer-objects:
724
725Timer Objects
726-------------
727
728This class represents an action that should be run only after a certain amount
729of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
730and as such also functions as an example of creating custom threads.
731
732Timers are started, as with threads, by calling their :meth:`start` method. The
733timer can be stopped (before its action has begun) by calling the :meth:`cancel`
734method. The interval the timer will wait before executing its action may not be
735exactly the same as the interval specified by the user.
736
737For example::
738
739 def hello():
740 print "hello, world"
741
742 t = Timer(30.0, hello)
743 t.start() # after 30 seconds, "hello, world" will be printed
744
745
746.. class:: Timer(interval, function, args=[], kwargs={})
747
748 Create a timer that will run *function* with arguments *args* and keyword
749 arguments *kwargs*, after *interval* seconds have passed.
750
Georg Brandl3591a8f2009-07-26 14:44:23 +0000751 .. method:: cancel()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000752
Georg Brandl3591a8f2009-07-26 14:44:23 +0000753 Stop the timer, and cancel the execution of the timer's action. This will
754 only work if the timer is still in its waiting stage.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755
756
757.. _with-locks:
758
759Using locks, conditions, and semaphores in the :keyword:`with` statement
760------------------------------------------------------------------------
761
762All of the objects provided by this module that have :meth:`acquire` and
763:meth:`release` methods can be used as context managers for a :keyword:`with`
764statement. The :meth:`acquire` method will be called when the block is entered,
765and :meth:`release` will be called when the block is exited.
766
767Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
768:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
769:keyword:`with` statement context managers. For example::
770
Georg Brandl8ec7f652007-08-15 14:28:01 +0000771 import threading
772
773 some_rlock = threading.RLock()
774
775 with some_rlock:
776 print "some_rlock is locked while this executes"
777
Georg Brandl2e255512008-03-13 07:21:41 +0000778
779.. _threaded-imports:
780
781Importing in threaded code
782--------------------------
783
784While the import machinery is thread safe, there are two key
785restrictions on threaded imports due to inherent limitations in the way
786that thread safety is provided:
787
788* Firstly, other than in the main module, an import should not have the
789 side effect of spawning a new thread and then waiting for that thread in
790 any way. Failing to abide by this restriction can lead to a deadlock if
791 the spawned thread directly or indirectly attempts to import a module.
792* Secondly, all import attempts must be completed before the interpreter
793 starts shutting itself down. This can be most easily achieved by only
794 performing imports from non-daemon threads created through the threading
795 module. Daemon threads and threads created directly with the thread
796 module will require some other form of synchronization to ensure they do
797 not attempt imports after system shutdown has commenced. Failure to
798 abide by this restriction will lead to intermittent exceptions and
799 crashes during interpreter shutdown (as the late imports attempt to
800 access machinery which is no longer in a valid state).