blob: c9ef294a105ec1d8457f688a27d817213a72809f [file] [log] [blame]
Antoine Pitroufa66d582010-12-12 21:08:54 +00001:mod:`threading` --- Thread-based parallelism
2=============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: threading
Antoine Pitroufa66d582010-12-12 21:08:54 +00005 :synopsis: Thread-based parallelism.
Georg Brandl116aa622007-08-15 14:28:22 +00006
7
Georg Brandl2067bfd2008-05-25 13:05:15 +00008This module constructs higher-level threading interfaces on top of the lower
9level :mod:`_thread` module. See also the :mod:`queue` module.
Georg Brandl116aa622007-08-15 14:28:22 +000010
11The :mod:`dummy_threading` module is provided for situations where
Georg Brandl2067bfd2008-05-25 13:05:15 +000012:mod:`threading` cannot be used because :mod:`_thread` is missing.
Georg Brandl116aa622007-08-15 14:28:22 +000013
Benjamin Peterson8bdd5452008-08-18 22:38:41 +000014.. note::
15
Benjamin Petersonb3085c92008-09-01 23:09:31 +000016 While they are not listed below, the ``camelCase`` names used for some
17 methods and functions in this module in the Python 2.x series are still
18 supported by this module.
Benjamin Peterson8bdd5452008-08-18 22:38:41 +000019
Georg Brandl116aa622007-08-15 14:28:22 +000020This module defines the following functions and objects:
21
22
Benjamin Peterson672b8032008-06-11 19:14:14 +000023.. function:: active_count()
Georg Brandl116aa622007-08-15 14:28:22 +000024
25 Return the number of :class:`Thread` objects currently alive. The returned
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +000026 count is equal to the length of the list returned by :func:`.enumerate`.
Georg Brandl116aa622007-08-15 14:28:22 +000027
28
29.. function:: Condition()
30 :noindex:
31
32 A factory function that returns a new condition variable object. A condition
33 variable allows one or more threads to wait until they are notified by another
34 thread.
35
Georg Brandl57a5e3f2010-10-06 08:54:16 +000036 See :ref:`condition-objects`.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038
Benjamin Peterson672b8032008-06-11 19:14:14 +000039.. function:: current_thread()
Georg Brandl116aa622007-08-15 14:28:22 +000040
41 Return the current :class:`Thread` object, corresponding to the caller's thread
42 of control. If the caller's thread of control was not created through the
43 :mod:`threading` module, a dummy thread object with limited functionality is
44 returned.
45
46
47.. function:: enumerate()
48
Benjamin Peterson672b8032008-06-11 19:14:14 +000049 Return a list of all :class:`Thread` objects currently alive. The list
50 includes daemonic threads, dummy thread objects created by
51 :func:`current_thread`, and the main thread. It excludes terminated threads
52 and threads that have not yet been started.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54
55.. function:: Event()
56 :noindex:
57
58 A factory function that returns a new event object. An event manages a flag
Georg Brandlc5605df2009-08-13 08:26:44 +000059 that can be set to true with the :meth:`~Event.set` method and reset to false
60 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
61 is true.
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandl57a5e3f2010-10-06 08:54:16 +000063 See :ref:`event-objects`.
64
Georg Brandl116aa622007-08-15 14:28:22 +000065
66.. class:: local
67
68 A class that represents thread-local data. Thread-local data are data whose
69 values are thread specific. To manage thread-local data, just create an
70 instance of :class:`local` (or a subclass) and store attributes on it::
71
72 mydata = threading.local()
73 mydata.x = 1
74
75 The instance's values will be different for separate threads.
76
77 For more details and extensive examples, see the documentation string of the
78 :mod:`_threading_local` module.
79
Georg Brandl116aa622007-08-15 14:28:22 +000080
81.. function:: Lock()
82
83 A factory function that returns a new primitive lock object. Once a thread has
84 acquired it, subsequent attempts to acquire it block, until it is released; any
85 thread may release it.
86
Georg Brandl57a5e3f2010-10-06 08:54:16 +000087 See :ref:`lock-objects`.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089
90.. function:: RLock()
91
92 A factory function that returns a new reentrant lock object. A reentrant lock
93 must be released by the thread that acquired it. Once a thread has acquired a
94 reentrant lock, the same thread may acquire it again without blocking; the
95 thread must release it once for each time it has acquired it.
96
Georg Brandl57a5e3f2010-10-06 08:54:16 +000097 See :ref:`rlock-objects`.
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
Georg Brandlb044b2a2009-09-16 16:05:59 +0000100.. function:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000101 :noindex:
102
103 A factory function that returns a new semaphore object. A semaphore manages a
104 counter representing the number of :meth:`release` calls minus the number of
105 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
106 if necessary until it can return without making the counter negative. If not
107 given, *value* defaults to 1.
108
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000109 See :ref:`semaphore-objects`.
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Georg Brandlb044b2a2009-09-16 16:05:59 +0000112.. function:: BoundedSemaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114 A factory function that returns a new bounded semaphore object. A bounded
115 semaphore checks to make sure its current value doesn't exceed its initial
116 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
117 are used to guard resources with limited capacity. If the semaphore is released
118 too many times it's a sign of a bug. If not given, *value* defaults to 1.
119
120
121.. class:: Thread
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000122 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 A class that represents a thread of control. This class can be safely
125 subclassed in a limited fashion.
126
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000127 See :ref:`thread-objects`.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. class:: Timer
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000131 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 A thread that executes a function after a specified interval has passed.
134
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000135 See :ref:`timer-objects`.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. function:: settrace(func)
139
140 .. index:: single: trace function
141
142 Set a trace function for all threads started from the :mod:`threading` module.
143 The *func* will be passed to :func:`sys.settrace` for each thread, before its
144 :meth:`run` method is called.
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147.. function:: setprofile(func)
148
149 .. index:: single: profile function
150
151 Set a profile function for all threads started from the :mod:`threading` module.
152 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
153 :meth:`run` method is called.
154
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156.. function:: stack_size([size])
157
158 Return the thread stack size used when creating new threads. The optional
159 *size* argument specifies the stack size to be used for subsequently created
160 threads, and must be 0 (use platform or configured default) or a positive
161 integer value of at least 32,768 (32kB). If changing the thread stack size is
162 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
163 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
164 is currently the minimum supported stack size value to guarantee sufficient
165 stack space for the interpreter itself. Note that some platforms may have
166 particular restrictions on values for the stack size, such as requiring a
167 minimum stack size > 32kB or requiring allocation in multiples of the system
168 memory page size - platform documentation should be referred to for more
169 information (4kB pages are common; using multiples of 4096 for the stack size is
170 the suggested approach in the absence of more specific information).
171 Availability: Windows, systems with POSIX threads.
172
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174Detailed interfaces for the objects are documented below.
175
176The design of this module is loosely based on Java's threading model. However,
177where Java makes locks and condition variables basic behavior of every object,
178they are separate objects in Python. Python's :class:`Thread` class supports a
179subset of the behavior of Java's Thread class; currently, there are no
180priorities, no thread groups, and threads cannot be destroyed, stopped,
181suspended, resumed, or interrupted. The static methods of Java's Thread class,
182when implemented, are mapped to module-level functions.
183
184All of the methods described below are executed atomically.
185
186
Georg Brandla971c652008-11-07 09:39:56 +0000187.. _thread-objects:
188
189Thread Objects
190--------------
191
192This class represents an activity that is run in a separate thread of control.
193There are two ways to specify the activity: by passing a callable object to the
194constructor, or by overriding the :meth:`run` method in a subclass. No other
195methods (except for the constructor) should be overridden in a subclass. In
196other words, *only* override the :meth:`__init__` and :meth:`run` methods of
197this class.
198
199Once a thread object is created, its activity must be started by calling the
200thread's :meth:`start` method. This invokes the :meth:`run` method in a
201separate thread of control.
202
203Once the thread's activity is started, the thread is considered 'alive'. It
204stops being alive when its :meth:`run` method terminates -- either normally, or
205by raising an unhandled exception. The :meth:`is_alive` method tests whether the
206thread is alive.
207
208Other threads can call a thread's :meth:`join` method. This blocks the calling
209thread until the thread whose :meth:`join` method is called is terminated.
210
211A thread has a name. The name can be passed to the constructor, and read or
212changed through the :attr:`name` attribute.
213
214A thread can be flagged as a "daemon thread". The significance of this flag is
215that the entire Python program exits when only daemon threads are left. The
216initial value is inherited from the creating thread. The flag can be set
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000217through the :attr:`daemon` property.
Georg Brandla971c652008-11-07 09:39:56 +0000218
219There is a "main thread" object; this corresponds to the initial thread of
220control in the Python program. It is not a daemon thread.
221
222There is the possibility that "dummy thread objects" are created. These are
223thread objects corresponding to "alien threads", which are threads of control
224started outside the threading module, such as directly from C code. Dummy
225thread objects have limited functionality; they are always considered alive and
226daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
227impossible to detect the termination of alien threads.
228
229
230.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
231
Georg Brandlc5605df2009-08-13 08:26:44 +0000232 This constructor should always be called with keyword arguments. Arguments
233 are:
Georg Brandla971c652008-11-07 09:39:56 +0000234
235 *group* should be ``None``; reserved for future extension when a
236 :class:`ThreadGroup` class is implemented.
237
238 *target* is the callable object to be invoked by the :meth:`run` method.
239 Defaults to ``None``, meaning nothing is called.
240
Georg Brandlc5605df2009-08-13 08:26:44 +0000241 *name* is the thread name. By default, a unique name is constructed of the
242 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandla971c652008-11-07 09:39:56 +0000243
244 *args* is the argument tuple for the target invocation. Defaults to ``()``.
245
246 *kwargs* is a dictionary of keyword arguments for the target invocation.
247 Defaults to ``{}``.
248
Georg Brandlc5605df2009-08-13 08:26:44 +0000249 If the subclass overrides the constructor, it must make sure to invoke the
250 base class constructor (``Thread.__init__()``) before doing anything else to
251 the thread.
Georg Brandla971c652008-11-07 09:39:56 +0000252
Georg Brandlc5605df2009-08-13 08:26:44 +0000253 .. method:: start()
Georg Brandla971c652008-11-07 09:39:56 +0000254
Georg Brandlc5605df2009-08-13 08:26:44 +0000255 Start the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000256
Georg Brandlc5605df2009-08-13 08:26:44 +0000257 It must be called at most once per thread object. It arranges for the
258 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandla971c652008-11-07 09:39:56 +0000259
Georg Brandlc5605df2009-08-13 08:26:44 +0000260 This method will raise a :exc:`RuntimeException` if called more than once
261 on the same thread object.
Georg Brandla971c652008-11-07 09:39:56 +0000262
Georg Brandlc5605df2009-08-13 08:26:44 +0000263 .. method:: run()
Georg Brandla971c652008-11-07 09:39:56 +0000264
Georg Brandlc5605df2009-08-13 08:26:44 +0000265 Method representing the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000266
Georg Brandlc5605df2009-08-13 08:26:44 +0000267 You may override this method in a subclass. The standard :meth:`run`
268 method invokes the callable object passed to the object's constructor as
269 the *target* argument, if any, with sequential and keyword arguments taken
270 from the *args* and *kwargs* arguments, respectively.
Georg Brandla971c652008-11-07 09:39:56 +0000271
Georg Brandlb044b2a2009-09-16 16:05:59 +0000272 .. method:: join(timeout=None)
Georg Brandla971c652008-11-07 09:39:56 +0000273
Georg Brandlc5605df2009-08-13 08:26:44 +0000274 Wait until the thread terminates. This blocks the calling thread until the
275 thread whose :meth:`join` method is called terminates -- either normally
276 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandla971c652008-11-07 09:39:56 +0000277
Georg Brandlc5605df2009-08-13 08:26:44 +0000278 When the *timeout* argument is present and not ``None``, it should be a
279 floating point number specifying a timeout for the operation in seconds
280 (or fractions thereof). As :meth:`join` always returns ``None``, you must
281 call :meth:`is_alive` after :meth:`join` to decide whether a timeout
282 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandla971c652008-11-07 09:39:56 +0000283
Georg Brandlc5605df2009-08-13 08:26:44 +0000284 When the *timeout* argument is not present or ``None``, the operation will
285 block until the thread terminates.
Georg Brandla971c652008-11-07 09:39:56 +0000286
Georg Brandlc5605df2009-08-13 08:26:44 +0000287 A thread can be :meth:`join`\ ed many times.
Georg Brandla971c652008-11-07 09:39:56 +0000288
Georg Brandlc5605df2009-08-13 08:26:44 +0000289 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
290 the current thread as that would cause a deadlock. It is also an error to
291 :meth:`join` a thread before it has been started and attempts to do so
292 raises the same exception.
Georg Brandla971c652008-11-07 09:39:56 +0000293
Georg Brandlc5605df2009-08-13 08:26:44 +0000294 .. attribute:: name
Georg Brandla971c652008-11-07 09:39:56 +0000295
Georg Brandlc5605df2009-08-13 08:26:44 +0000296 A string used for identification purposes only. It has no semantics.
297 Multiple threads may be given the same name. The initial name is set by
298 the constructor.
Georg Brandla971c652008-11-07 09:39:56 +0000299
Georg Brandlc5605df2009-08-13 08:26:44 +0000300 .. method:: getName()
301 setName()
Georg Brandla971c652008-11-07 09:39:56 +0000302
Georg Brandlc5605df2009-08-13 08:26:44 +0000303 Old getter/setter API for :attr:`~Thread.name`; use it directly as a
304 property instead.
Georg Brandla971c652008-11-07 09:39:56 +0000305
Georg Brandlc5605df2009-08-13 08:26:44 +0000306 .. attribute:: ident
Georg Brandla971c652008-11-07 09:39:56 +0000307
Georg Brandlc5605df2009-08-13 08:26:44 +0000308 The 'thread identifier' of this thread or ``None`` if the thread has not
309 been started. This is a nonzero integer. See the
310 :func:`thread.get_ident()` function. Thread identifiers may be recycled
311 when a thread exits and another thread is created. The identifier is
312 available even after the thread has exited.
Georg Brandla971c652008-11-07 09:39:56 +0000313
Georg Brandlc5605df2009-08-13 08:26:44 +0000314 .. method:: is_alive()
Georg Brandla971c652008-11-07 09:39:56 +0000315
Georg Brandlc5605df2009-08-13 08:26:44 +0000316 Return whether the thread is alive.
Georg Brandl770b0be2009-01-02 20:10:05 +0000317
Brett Cannonb0a30742010-07-23 12:28:28 +0000318 This method returns ``True`` just before the :meth:`run` method starts
319 until just after the :meth:`run` method terminates. The module function
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000320 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl770b0be2009-01-02 20:10:05 +0000321
Georg Brandlc5605df2009-08-13 08:26:44 +0000322 .. attribute:: daemon
Georg Brandl770b0be2009-01-02 20:10:05 +0000323
Georg Brandlc5605df2009-08-13 08:26:44 +0000324 A boolean value indicating whether this thread is a daemon thread (True)
325 or not (False). This must be set before :meth:`start` is called,
326 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
327 from the creating thread; the main thread is not a daemon thread and
328 therefore all threads created in the main thread default to :attr:`daemon`
329 = ``False``.
Georg Brandla971c652008-11-07 09:39:56 +0000330
Georg Brandlc5605df2009-08-13 08:26:44 +0000331 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandla971c652008-11-07 09:39:56 +0000332
Georg Brandlc5605df2009-08-13 08:26:44 +0000333 .. method:: isDaemon()
334 setDaemon()
Georg Brandla971c652008-11-07 09:39:56 +0000335
Georg Brandlc5605df2009-08-13 08:26:44 +0000336 Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
337 property instead.
Georg Brandl770b0be2009-01-02 20:10:05 +0000338
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340.. _lock-objects:
341
342Lock Objects
343------------
344
345A primitive lock is a synchronization primitive that is not owned by a
346particular thread when locked. In Python, it is currently the lowest level
Georg Brandl2067bfd2008-05-25 13:05:15 +0000347synchronization primitive available, implemented directly by the :mod:`_thread`
Georg Brandl116aa622007-08-15 14:28:22 +0000348extension module.
349
350A primitive lock is in one of two states, "locked" or "unlocked". It is created
351in the unlocked state. It has two basic methods, :meth:`acquire` and
352:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
353to locked and returns immediately. When the state is locked, :meth:`acquire`
354blocks until a call to :meth:`release` in another thread changes it to unlocked,
355then the :meth:`acquire` call resets it to locked and returns. The
356:meth:`release` method should only be called in the locked state; it changes the
357state to unlocked and returns immediately. If an attempt is made to release an
358unlocked lock, a :exc:`RuntimeError` will be raised.
359
360When more than one thread is blocked in :meth:`acquire` waiting for the state to
361turn to unlocked, only one thread proceeds when a :meth:`release` call resets
362the state to unlocked; which one of the waiting threads proceeds is not defined,
363and may vary across implementations.
364
365All methods are executed atomically.
366
367
Terry Reedy2b8cf2f2011-01-01 00:29:59 +0000368.. method:: Lock.acquire([blocking])
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370 Acquire a lock, blocking or non-blocking.
371
372 When invoked without arguments, block until the lock is unlocked, then set it to
373 locked, and return true.
374
375 When invoked with the *blocking* argument set to true, do the same thing as when
376 called without arguments, and return true.
377
378 When invoked with the *blocking* argument set to false, do not block. If a call
379 without an argument would block, return false immediately; otherwise, do the
380 same thing as when called without arguments, and return true.
381
382
383.. method:: Lock.release()
384
385 Release a lock.
386
387 When the lock is locked, reset it to unlocked, and return. If any other threads
388 are blocked waiting for the lock to become unlocked, allow exactly one of them
389 to proceed.
390
391 Do not call this method when the lock is unlocked.
392
393 There is no return value.
394
395
396.. _rlock-objects:
397
398RLock Objects
399-------------
400
401A reentrant lock is a synchronization primitive that may be acquired multiple
402times by the same thread. Internally, it uses the concepts of "owning thread"
403and "recursion level" in addition to the locked/unlocked state used by primitive
404locks. In the locked state, some thread owns the lock; in the unlocked state,
405no thread owns it.
406
407To lock the lock, a thread calls its :meth:`acquire` method; this returns once
408the thread owns the lock. To unlock the lock, a thread calls its
409:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
410nested; only the final :meth:`release` (the :meth:`release` of the outermost
411pair) resets the lock to unlocked and allows another thread blocked in
412:meth:`acquire` to proceed.
413
414
Georg Brandlb044b2a2009-09-16 16:05:59 +0000415.. method:: RLock.acquire(blocking=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000416
417 Acquire a lock, blocking or non-blocking.
418
419 When invoked without arguments: if this thread already owns the lock, increment
420 the recursion level by one, and return immediately. Otherwise, if another
421 thread owns the lock, block until the lock is unlocked. Once the lock is
422 unlocked (not owned by any thread), then grab ownership, set the recursion level
423 to one, and return. If more than one thread is blocked waiting until the lock
424 is unlocked, only one at a time will be able to grab ownership of the lock.
425 There is no return value in this case.
426
427 When invoked with the *blocking* argument set to true, do the same thing as when
428 called without arguments, and return true.
429
430 When invoked with the *blocking* argument set to false, do not block. If a call
431 without an argument would block, return false immediately; otherwise, do the
432 same thing as when called without arguments, and return true.
433
434
435.. method:: RLock.release()
436
437 Release a lock, decrementing the recursion level. If after the decrement it is
438 zero, reset the lock to unlocked (not owned by any thread), and if any other
439 threads are blocked waiting for the lock to become unlocked, allow exactly one
440 of them to proceed. If after the decrement the recursion level is still
441 nonzero, the lock remains locked and owned by the calling thread.
442
443 Only call this method when the calling thread owns the lock. A
444 :exc:`RuntimeError` is raised if this method is called when the lock is
445 unlocked.
446
447 There is no return value.
448
449
450.. _condition-objects:
451
452Condition Objects
453-----------------
454
455A condition variable is always associated with some kind of lock; this can be
456passed in or one will be created by default. (Passing one in is useful when
457several condition variables must share the same lock.)
458
459A condition variable has :meth:`acquire` and :meth:`release` methods that call
460the corresponding methods of the associated lock. It also has a :meth:`wait`
Georg Brandlf9926402008-06-13 06:32:25 +0000461method, and :meth:`notify` and :meth:`notify_all` methods. These three must only
Georg Brandl116aa622007-08-15 14:28:22 +0000462be called when the calling thread has acquired the lock, otherwise a
463:exc:`RuntimeError` is raised.
464
465The :meth:`wait` method releases the lock, and then blocks until it is awakened
Georg Brandlf9926402008-06-13 06:32:25 +0000466by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
Georg Brandl116aa622007-08-15 14:28:22 +0000467another thread. Once awakened, it re-acquires the lock and returns. It is also
468possible to specify a timeout.
469
470The :meth:`notify` method wakes up one of the threads waiting for the condition
Georg Brandlf9926402008-06-13 06:32:25 +0000471variable, if any are waiting. The :meth:`notify_all` method wakes up all threads
Georg Brandl116aa622007-08-15 14:28:22 +0000472waiting for the condition variable.
473
Georg Brandlf9926402008-06-13 06:32:25 +0000474Note: the :meth:`notify` and :meth:`notify_all` methods don't release the lock;
Georg Brandl116aa622007-08-15 14:28:22 +0000475this means that the thread or threads awakened will not return from their
476:meth:`wait` call immediately, but only when the thread that called
Georg Brandlf9926402008-06-13 06:32:25 +0000477:meth:`notify` or :meth:`notify_all` finally relinquishes ownership of the lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479Tip: the typical programming style using condition variables uses the lock to
480synchronize access to some shared state; threads that are interested in a
481particular change of state call :meth:`wait` repeatedly until they see the
482desired state, while threads that modify the state call :meth:`notify` or
Georg Brandlf9926402008-06-13 06:32:25 +0000483:meth:`notify_all` when they change the state in such a way that it could
Georg Brandl116aa622007-08-15 14:28:22 +0000484possibly be a desired state for one of the waiters. For example, the following
485code is a generic producer-consumer situation with unlimited buffer capacity::
486
487 # Consume one item
488 cv.acquire()
489 while not an_item_is_available():
490 cv.wait()
491 get_an_available_item()
492 cv.release()
493
494 # Produce one item
495 cv.acquire()
496 make_an_item_available()
497 cv.notify()
498 cv.release()
499
Georg Brandlf9926402008-06-13 06:32:25 +0000500To choose between :meth:`notify` and :meth:`notify_all`, consider whether one
Georg Brandl116aa622007-08-15 14:28:22 +0000501state change can be interesting for only one or several waiting threads. E.g.
502in a typical producer-consumer situation, adding one item to the buffer only
503needs to wake up one consumer thread.
504
505
Georg Brandlb044b2a2009-09-16 16:05:59 +0000506.. class:: Condition(lock=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Georg Brandlc5605df2009-08-13 08:26:44 +0000508 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
509 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
510 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000511
Georg Brandlc5605df2009-08-13 08:26:44 +0000512 .. method:: acquire(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000513
Georg Brandlc5605df2009-08-13 08:26:44 +0000514 Acquire the underlying lock. This method calls the corresponding method on
515 the underlying lock; the return value is whatever that method returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Georg Brandlc5605df2009-08-13 08:26:44 +0000517 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Georg Brandlc5605df2009-08-13 08:26:44 +0000519 Release the underlying lock. This method calls the corresponding method on
520 the underlying lock; there is no return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Georg Brandlb044b2a2009-09-16 16:05:59 +0000522 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000523
Georg Brandlc5605df2009-08-13 08:26:44 +0000524 Wait until notified or until a timeout occurs. If the calling thread has
525 not acquired the lock when this method is called, a :exc:`RuntimeError` is
526 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandlc5605df2009-08-13 08:26:44 +0000528 This method releases the underlying lock, and then blocks until it is
529 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
530 condition variable in another thread, or until the optional timeout
531 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000532
Georg Brandlc5605df2009-08-13 08:26:44 +0000533 When the *timeout* argument is present and not ``None``, it should be a
534 floating point number specifying a timeout for the operation in seconds
535 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Georg Brandlc5605df2009-08-13 08:26:44 +0000537 When the underlying lock is an :class:`RLock`, it is not released using
538 its :meth:`release` method, since this may not actually unlock the lock
539 when it was acquired multiple times recursively. Instead, an internal
540 interface of the :class:`RLock` class is used, which really unlocks it
541 even when it has been recursively acquired several times. Another internal
542 interface is then used to restore the recursion level when the lock is
543 reacquired.
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Georg Brandlc5605df2009-08-13 08:26:44 +0000545 .. method:: notify()
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Georg Brandlc5605df2009-08-13 08:26:44 +0000547 Wake up a thread waiting on this condition, if any. If the calling thread
548 has not acquired the lock when this method is called, a
549 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Georg Brandlc5605df2009-08-13 08:26:44 +0000551 This method wakes up one of the threads waiting for the condition
552 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Georg Brandlc5605df2009-08-13 08:26:44 +0000554 The current implementation wakes up exactly one thread, if any are
555 waiting. However, it's not safe to rely on this behavior. A future,
556 optimized implementation may occasionally wake up more than one thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Georg Brandlc5605df2009-08-13 08:26:44 +0000558 Note: the awakened thread does not actually return from its :meth:`wait`
559 call until it can reacquire the lock. Since :meth:`notify` does not
560 release the lock, its caller should.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
Georg Brandlc5605df2009-08-13 08:26:44 +0000562 .. method:: notify_all()
Georg Brandl116aa622007-08-15 14:28:22 +0000563
Georg Brandlc5605df2009-08-13 08:26:44 +0000564 Wake up all threads waiting on this condition. This method acts like
565 :meth:`notify`, but wakes up all waiting threads instead of one. If the
566 calling thread has not acquired the lock when this method is called, a
567 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569
570.. _semaphore-objects:
571
572Semaphore Objects
573-----------------
574
575This is one of the oldest synchronization primitives in the history of computer
576science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
577used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
578
579A semaphore manages an internal counter which is decremented by each
580:meth:`acquire` call and incremented by each :meth:`release` call. The counter
581can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
582waiting until some other thread calls :meth:`release`.
583
584
Georg Brandlb044b2a2009-09-16 16:05:59 +0000585.. class:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000586
587 The optional argument gives the initial *value* for the internal counter; it
588 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
589 raised.
590
Georg Brandlb044b2a2009-09-16 16:05:59 +0000591 .. method:: acquire(blocking=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000592
Georg Brandlc5605df2009-08-13 08:26:44 +0000593 Acquire a semaphore.
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Georg Brandlc5605df2009-08-13 08:26:44 +0000595 When invoked without arguments: if the internal counter is larger than
596 zero on entry, decrement it by one and return immediately. If it is zero
597 on entry, block, waiting until some other thread has called
598 :meth:`release` to make it larger than zero. This is done with proper
599 interlocking so that if multiple :meth:`acquire` calls are blocked,
600 :meth:`release` will wake exactly one of them up. The implementation may
601 pick one at random, so the order in which blocked threads are awakened
602 should not be relied on. There is no return value in this case.
Georg Brandl116aa622007-08-15 14:28:22 +0000603
Georg Brandlc5605df2009-08-13 08:26:44 +0000604 When invoked with *blocking* set to true, do the same thing as when called
605 without arguments, and return true.
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Georg Brandlc5605df2009-08-13 08:26:44 +0000607 When invoked with *blocking* set to false, do not block. If a call
608 without an argument would block, return false immediately; otherwise, do
609 the same thing as when called without arguments, and return true.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
Georg Brandlc5605df2009-08-13 08:26:44 +0000611 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000612
Georg Brandlc5605df2009-08-13 08:26:44 +0000613 Release a semaphore, incrementing the internal counter by one. When it
614 was zero on entry and another thread is waiting for it to become larger
615 than zero again, wake up that thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000616
617
618.. _semaphore-examples:
619
620:class:`Semaphore` Example
621^^^^^^^^^^^^^^^^^^^^^^^^^^
622
623Semaphores are often used to guard resources with limited capacity, for example,
624a database server. In any situation where the size of the resource size is
625fixed, you should use a bounded semaphore. Before spawning any worker threads,
626your main thread would initialize the semaphore::
627
628 maxconnections = 5
629 ...
630 pool_sema = BoundedSemaphore(value=maxconnections)
631
632Once spawned, worker threads call the semaphore's acquire and release methods
633when they need to connect to the server::
634
635 pool_sema.acquire()
636 conn = connectdb()
637 ... use connection ...
638 conn.close()
639 pool_sema.release()
640
641The use of a bounded semaphore reduces the chance that a programming error which
642causes the semaphore to be released more than it's acquired will go undetected.
643
644
645.. _event-objects:
646
647Event Objects
648-------------
649
650This is one of the simplest mechanisms for communication between threads: one
651thread signals an event and other threads wait for it.
652
653An event object manages an internal flag that can be set to true with the
Georg Brandlc5605df2009-08-13 08:26:44 +0000654:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl116aa622007-08-15 14:28:22 +0000655:meth:`wait` method blocks until the flag is true.
656
657
658.. class:: Event()
659
660 The internal flag is initially false.
661
Georg Brandlc5605df2009-08-13 08:26:44 +0000662 .. method:: is_set()
Georg Brandl116aa622007-08-15 14:28:22 +0000663
Georg Brandlc5605df2009-08-13 08:26:44 +0000664 Return true if and only if the internal flag is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Georg Brandlc5605df2009-08-13 08:26:44 +0000666 .. method:: set()
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Georg Brandlc5605df2009-08-13 08:26:44 +0000668 Set the internal flag to true. All threads waiting for it to become true
669 are awakened. Threads that call :meth:`wait` once the flag is true will
670 not block at all.
Georg Brandl116aa622007-08-15 14:28:22 +0000671
Georg Brandlc5605df2009-08-13 08:26:44 +0000672 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Georg Brandlc5605df2009-08-13 08:26:44 +0000674 Reset the internal flag to false. Subsequently, threads calling
675 :meth:`wait` will block until :meth:`.set` is called to set the internal
676 flag to true again.
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Georg Brandlb044b2a2009-09-16 16:05:59 +0000678 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000679
Georg Brandlc5605df2009-08-13 08:26:44 +0000680 Block until the internal flag is true. If the internal flag is true on
681 entry, return immediately. Otherwise, block until another thread calls
682 :meth:`set` to set the flag to true, or until the optional timeout occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000683
Georg Brandlc5605df2009-08-13 08:26:44 +0000684 When the timeout argument is present and not ``None``, it should be a
685 floating point number specifying a timeout for the operation in seconds
686 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000687
Georg Brandlc5605df2009-08-13 08:26:44 +0000688 This method returns the internal flag on exit, so it will always return
689 ``True`` except if a timeout is given and the operation times out.
Georg Brandl116aa622007-08-15 14:28:22 +0000690
Georg Brandlc5605df2009-08-13 08:26:44 +0000691 .. versionchanged:: 3.1
692 Previously, the method always returned ``None``.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000693
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Georg Brandl116aa622007-08-15 14:28:22 +0000695.. _timer-objects:
696
697Timer Objects
698-------------
699
700This class represents an action that should be run only after a certain amount
701of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
702and as such also functions as an example of creating custom threads.
703
704Timers are started, as with threads, by calling their :meth:`start` method. The
705timer can be stopped (before its action has begun) by calling the :meth:`cancel`
706method. The interval the timer will wait before executing its action may not be
707exactly the same as the interval specified by the user.
708
709For example::
710
711 def hello():
Collin Winterc79461b2007-09-01 23:34:30 +0000712 print("hello, world")
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714 t = Timer(30.0, hello)
715 t.start() # after 30 seconds, "hello, world" will be printed
716
717
718.. class:: Timer(interval, function, args=[], kwargs={})
719
720 Create a timer that will run *function* with arguments *args* and keyword
721 arguments *kwargs*, after *interval* seconds have passed.
722
Georg Brandlc5605df2009-08-13 08:26:44 +0000723 .. method:: cancel()
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Georg Brandlc5605df2009-08-13 08:26:44 +0000725 Stop the timer, and cancel the execution of the timer's action. This will
726 only work if the timer is still in its waiting stage.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728
729.. _with-locks:
730
731Using locks, conditions, and semaphores in the :keyword:`with` statement
732------------------------------------------------------------------------
733
734All of the objects provided by this module that have :meth:`acquire` and
735:meth:`release` methods can be used as context managers for a :keyword:`with`
736statement. The :meth:`acquire` method will be called when the block is entered,
737and :meth:`release` will be called when the block is exited.
738
739Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
740:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
741:keyword:`with` statement context managers. For example::
742
Georg Brandl116aa622007-08-15 14:28:22 +0000743 import threading
744
745 some_rlock = threading.RLock()
746
747 with some_rlock:
Collin Winterc79461b2007-09-01 23:34:30 +0000748 print("some_rlock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000750
751.. _threaded-imports:
752
753Importing in threaded code
754--------------------------
755
Georg Brandld62ecbf2010-11-26 08:52:36 +0000756While the import machinery is thread-safe, there are two key restrictions on
757threaded imports due to inherent limitations in the way that thread-safety is
758provided:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000759
760* Firstly, other than in the main module, an import should not have the
761 side effect of spawning a new thread and then waiting for that thread in
762 any way. Failing to abide by this restriction can lead to a deadlock if
763 the spawned thread directly or indirectly attempts to import a module.
764* Secondly, all import attempts must be completed before the interpreter
765 starts shutting itself down. This can be most easily achieved by only
766 performing imports from non-daemon threads created through the threading
767 module. Daemon threads and threads created directly with the thread
768 module will require some other form of synchronization to ensure they do
769 not attempt imports after system shutdown has commenced. Failure to
770 abide by this restriction will lead to intermittent exceptions and
771 crashes during interpreter shutdown (as the late imports attempt to
772 access machinery which is no longer in a valid state).