blob: 497a56f22c9eb9d1f99eb0179422fb71b602b212 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`threading` --- Higher-level threading interface
2=====================================================
3
4.. module:: threading
5 :synopsis: Higher-level threading interface.
6
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 Peterson4ac9ce42009-10-04 14:49:41 +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
36
Benjamin Peterson672b8032008-06-11 19:14:14 +000037.. function:: current_thread()
Georg Brandl116aa622007-08-15 14:28:22 +000038
39 Return the current :class:`Thread` object, corresponding to the caller's thread
40 of control. If the caller's thread of control was not created through the
41 :mod:`threading` module, a dummy thread object with limited functionality is
42 returned.
43
44
45.. function:: enumerate()
46
Benjamin Peterson672b8032008-06-11 19:14:14 +000047 Return a list of all :class:`Thread` objects currently alive. The list
48 includes daemonic threads, dummy thread objects created by
49 :func:`current_thread`, and the main thread. It excludes terminated threads
50 and threads that have not yet been started.
Georg Brandl116aa622007-08-15 14:28:22 +000051
52
53.. function:: Event()
54 :noindex:
55
56 A factory function that returns a new event object. An event manages a flag
Georg Brandl502d9a52009-07-26 15:02:41 +000057 that can be set to true with the :meth:`~Event.set` method and reset to false
58 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
59 is true.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61
62.. class:: local
63
64 A class that represents thread-local data. Thread-local data are data whose
65 values are thread specific. To manage thread-local data, just create an
66 instance of :class:`local` (or a subclass) and store attributes on it::
67
68 mydata = threading.local()
69 mydata.x = 1
70
71 The instance's values will be different for separate threads.
72
73 For more details and extensive examples, see the documentation string of the
74 :mod:`_threading_local` module.
75
Georg Brandl116aa622007-08-15 14:28:22 +000076
77.. function:: Lock()
78
79 A factory function that returns a new primitive lock object. Once a thread has
80 acquired it, subsequent attempts to acquire it block, until it is released; any
81 thread may release it.
82
83
84.. function:: RLock()
85
86 A factory function that returns a new reentrant lock object. A reentrant lock
87 must be released by the thread that acquired it. Once a thread has acquired a
88 reentrant lock, the same thread may acquire it again without blocking; the
89 thread must release it once for each time it has acquired it.
90
91
Georg Brandl7f01a132009-09-16 15:58:14 +000092.. function:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +000093 :noindex:
94
95 A factory function that returns a new semaphore object. A semaphore manages a
96 counter representing the number of :meth:`release` calls minus the number of
97 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
98 if necessary until it can return without making the counter negative. If not
99 given, *value* defaults to 1.
100
101
Georg Brandl7f01a132009-09-16 15:58:14 +0000102.. function:: BoundedSemaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104 A factory function that returns a new bounded semaphore object. A bounded
105 semaphore checks to make sure its current value doesn't exceed its initial
106 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
107 are used to guard resources with limited capacity. If the semaphore is released
108 too many times it's a sign of a bug. If not given, *value* defaults to 1.
109
110
111.. class:: Thread
112
113 A class that represents a thread of control. This class can be safely
114 subclassed in a limited fashion.
115
116
117.. class:: Timer
118
119 A thread that executes a function after a specified interval has passed.
120
121
122.. function:: settrace(func)
123
124 .. index:: single: trace function
125
126 Set a trace function for all threads started from the :mod:`threading` module.
127 The *func* will be passed to :func:`sys.settrace` for each thread, before its
128 :meth:`run` method is called.
129
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131.. function:: setprofile(func)
132
133 .. index:: single: profile function
134
135 Set a profile function for all threads started from the :mod:`threading` module.
136 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
137 :meth:`run` method is called.
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140.. function:: stack_size([size])
141
142 Return the thread stack size used when creating new threads. The optional
143 *size* argument specifies the stack size to be used for subsequently created
144 threads, and must be 0 (use platform or configured default) or a positive
145 integer value of at least 32,768 (32kB). If changing the thread stack size is
146 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
147 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
148 is currently the minimum supported stack size value to guarantee sufficient
149 stack space for the interpreter itself. Note that some platforms may have
150 particular restrictions on values for the stack size, such as requiring a
151 minimum stack size > 32kB or requiring allocation in multiples of the system
152 memory page size - platform documentation should be referred to for more
153 information (4kB pages are common; using multiples of 4096 for the stack size is
154 the suggested approach in the absence of more specific information).
155 Availability: Windows, systems with POSIX threads.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000158This module also defines the following constant:
159
160.. data:: TIMEOUT_MAX
161
162 The maximum value allowed for the *timeout* parameter of blocking functions
163 (:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.).
164 Specifiying a timeout greater than this value will raise an
165 :exc:`OverflowError`.
166
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000167 .. versionadded:: 3.2
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000168
Georg Brandl67b21b72010-08-17 15:07:14 +0000169
Georg Brandl116aa622007-08-15 14:28:22 +0000170Detailed interfaces for the objects are documented below.
171
172The design of this module is loosely based on Java's threading model. However,
173where Java makes locks and condition variables basic behavior of every object,
174they are separate objects in Python. Python's :class:`Thread` class supports a
175subset of the behavior of Java's Thread class; currently, there are no
176priorities, no thread groups, and threads cannot be destroyed, stopped,
177suspended, resumed, or interrupted. The static methods of Java's Thread class,
178when implemented, are mapped to module-level functions.
179
180All of the methods described below are executed atomically.
181
182
Georg Brandla971c652008-11-07 09:39:56 +0000183.. _thread-objects:
184
185Thread Objects
186--------------
187
188This class represents an activity that is run in a separate thread of control.
189There are two ways to specify the activity: by passing a callable object to the
190constructor, or by overriding the :meth:`run` method in a subclass. No other
191methods (except for the constructor) should be overridden in a subclass. In
192other words, *only* override the :meth:`__init__` and :meth:`run` methods of
193this class.
194
195Once a thread object is created, its activity must be started by calling the
196thread's :meth:`start` method. This invokes the :meth:`run` method in a
197separate thread of control.
198
199Once the thread's activity is started, the thread is considered 'alive'. It
200stops being alive when its :meth:`run` method terminates -- either normally, or
201by raising an unhandled exception. The :meth:`is_alive` method tests whether the
202thread is alive.
203
204Other threads can call a thread's :meth:`join` method. This blocks the calling
205thread until the thread whose :meth:`join` method is called is terminated.
206
207A thread has a name. The name can be passed to the constructor, and read or
208changed through the :attr:`name` attribute.
209
210A thread can be flagged as a "daemon thread". The significance of this flag is
211that the entire Python program exits when only daemon threads are left. The
212initial value is inherited from the creating thread. The flag can be set
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000213through the :attr:`daemon` property.
Georg Brandla971c652008-11-07 09:39:56 +0000214
215There is a "main thread" object; this corresponds to the initial thread of
216control in the Python program. It is not a daemon thread.
217
218There is the possibility that "dummy thread objects" are created. These are
219thread objects corresponding to "alien threads", which are threads of control
220started outside the threading module, such as directly from C code. Dummy
221thread objects have limited functionality; they are always considered alive and
222daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
223impossible to detect the termination of alien threads.
224
225
226.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
227
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000228 This constructor should always be called with keyword arguments. Arguments
229 are:
Georg Brandla971c652008-11-07 09:39:56 +0000230
231 *group* should be ``None``; reserved for future extension when a
232 :class:`ThreadGroup` class is implemented.
233
234 *target* is the callable object to be invoked by the :meth:`run` method.
235 Defaults to ``None``, meaning nothing is called.
236
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000237 *name* is the thread name. By default, a unique name is constructed of the
238 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandla971c652008-11-07 09:39:56 +0000239
240 *args* is the argument tuple for the target invocation. Defaults to ``()``.
241
242 *kwargs* is a dictionary of keyword arguments for the target invocation.
243 Defaults to ``{}``.
244
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000245 If the subclass overrides the constructor, it must make sure to invoke the
246 base class constructor (``Thread.__init__()``) before doing anything else to
247 the thread.
Georg Brandla971c652008-11-07 09:39:56 +0000248
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000249 .. method:: start()
Georg Brandla971c652008-11-07 09:39:56 +0000250
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000251 Start the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000252
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000253 It must be called at most once per thread object. It arranges for the
254 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandla971c652008-11-07 09:39:56 +0000255
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000256 This method will raise a :exc:`RuntimeException` if called more than once
257 on the same thread object.
Georg Brandla971c652008-11-07 09:39:56 +0000258
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000259 .. method:: run()
Georg Brandla971c652008-11-07 09:39:56 +0000260
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000261 Method representing the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000262
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000263 You may override this method in a subclass. The standard :meth:`run`
264 method invokes the callable object passed to the object's constructor as
265 the *target* argument, if any, with sequential and keyword arguments taken
266 from the *args* and *kwargs* arguments, respectively.
Georg Brandla971c652008-11-07 09:39:56 +0000267
Georg Brandl7f01a132009-09-16 15:58:14 +0000268 .. method:: join(timeout=None)
Georg Brandla971c652008-11-07 09:39:56 +0000269
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000270 Wait until the thread terminates. This blocks the calling thread until the
271 thread whose :meth:`join` method is called terminates -- either normally
272 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandla971c652008-11-07 09:39:56 +0000273
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000274 When the *timeout* argument is present and not ``None``, it should be a
275 floating point number specifying a timeout for the operation in seconds
276 (or fractions thereof). As :meth:`join` always returns ``None``, you must
277 call :meth:`is_alive` after :meth:`join` to decide whether a timeout
278 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandla971c652008-11-07 09:39:56 +0000279
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000280 When the *timeout* argument is not present or ``None``, the operation will
281 block until the thread terminates.
Georg Brandla971c652008-11-07 09:39:56 +0000282
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000283 A thread can be :meth:`join`\ ed many times.
Georg Brandla971c652008-11-07 09:39:56 +0000284
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000285 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
286 the current thread as that would cause a deadlock. It is also an error to
287 :meth:`join` a thread before it has been started and attempts to do so
288 raises the same exception.
Georg Brandla971c652008-11-07 09:39:56 +0000289
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000290 .. attribute:: name
Georg Brandla971c652008-11-07 09:39:56 +0000291
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000292 A string used for identification purposes only. It has no semantics.
293 Multiple threads may be given the same name. The initial name is set by
294 the constructor.
Georg Brandla971c652008-11-07 09:39:56 +0000295
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000296 .. method:: getName()
297 setName()
Georg Brandla971c652008-11-07 09:39:56 +0000298
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000299 Old getter/setter API for :attr:`~Thread.name`; use it directly as a
300 property instead.
Georg Brandla971c652008-11-07 09:39:56 +0000301
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000302 .. attribute:: ident
Georg Brandla971c652008-11-07 09:39:56 +0000303
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000304 The 'thread identifier' of this thread or ``None`` if the thread has not
305 been started. This is a nonzero integer. See the
306 :func:`thread.get_ident()` function. Thread identifiers may be recycled
307 when a thread exits and another thread is created. The identifier is
308 available even after the thread has exited.
Georg Brandla971c652008-11-07 09:39:56 +0000309
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000310 .. method:: is_alive()
Georg Brandla971c652008-11-07 09:39:56 +0000311
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000312 Return whether the thread is alive.
Georg Brandl770b0be2009-01-02 20:10:05 +0000313
Brett Cannona57edd02010-07-23 12:26:35 +0000314 This method returns ``True`` just before the :meth:`run` method starts
315 until just after the :meth:`run` method terminates. The module function
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000316 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl770b0be2009-01-02 20:10:05 +0000317
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000318 .. attribute:: daemon
Georg Brandl770b0be2009-01-02 20:10:05 +0000319
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000320 A boolean value indicating whether this thread is a daemon thread (True)
321 or not (False). This must be set before :meth:`start` is called,
322 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
323 from the creating thread; the main thread is not a daemon thread and
324 therefore all threads created in the main thread default to :attr:`daemon`
325 = ``False``.
Georg Brandla971c652008-11-07 09:39:56 +0000326
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000327 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandla971c652008-11-07 09:39:56 +0000328
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000329 .. method:: isDaemon()
330 setDaemon()
Georg Brandla971c652008-11-07 09:39:56 +0000331
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000332 Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
333 property instead.
Georg Brandl770b0be2009-01-02 20:10:05 +0000334
335
Georg Brandl116aa622007-08-15 14:28:22 +0000336.. _lock-objects:
337
338Lock Objects
339------------
340
341A primitive lock is a synchronization primitive that is not owned by a
342particular thread when locked. In Python, it is currently the lowest level
Georg Brandl2067bfd2008-05-25 13:05:15 +0000343synchronization primitive available, implemented directly by the :mod:`_thread`
Georg Brandl116aa622007-08-15 14:28:22 +0000344extension module.
345
346A primitive lock is in one of two states, "locked" or "unlocked". It is created
347in the unlocked state. It has two basic methods, :meth:`acquire` and
348:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
349to locked and returns immediately. When the state is locked, :meth:`acquire`
350blocks until a call to :meth:`release` in another thread changes it to unlocked,
351then the :meth:`acquire` call resets it to locked and returns. The
352:meth:`release` method should only be called in the locked state; it changes the
353state to unlocked and returns immediately. If an attempt is made to release an
354unlocked lock, a :exc:`RuntimeError` will be raised.
355
356When more than one thread is blocked in :meth:`acquire` waiting for the state to
357turn to unlocked, only one thread proceeds when a :meth:`release` call resets
358the state to unlocked; which one of the waiting threads proceeds is not defined,
359and may vary across implementations.
360
361All methods are executed atomically.
362
363
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000364.. method:: Lock.acquire(blocking=True, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366 Acquire a lock, blocking or non-blocking.
367
368 When invoked without arguments, block until the lock is unlocked, then set it to
369 locked, and return true.
370
371 When invoked with the *blocking* argument set to true, do the same thing as when
372 called without arguments, and return true.
373
374 When invoked with the *blocking* argument set to false, do not block. If a call
375 without an argument would block, return false immediately; otherwise, do the
376 same thing as when called without arguments, and return true.
377
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000378 When invoked with the floating-point *timeout* argument set to a positive
379 value, block for at most the number of seconds specified by *timeout*
380 and as long as the lock cannot be acquired. A negative *timeout* argument
381 specifies an unbounded wait. It is forbidden to specify a *timeout*
382 when *blocking* is false.
383
384 The return value is ``True`` if the lock is acquired successfully,
385 ``False`` if not (for example if the *timeout* expired).
386
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000387 .. versionchanged:: 3.2
388 The *timeout* parameter is new.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Georg Brandl67b21b72010-08-17 15:07:14 +0000390
Georg Brandl116aa622007-08-15 14:28:22 +0000391.. method:: Lock.release()
392
393 Release a lock.
394
395 When the lock is locked, reset it to unlocked, and return. If any other threads
396 are blocked waiting for the lock to become unlocked, allow exactly one of them
397 to proceed.
398
399 Do not call this method when the lock is unlocked.
400
401 There is no return value.
402
403
404.. _rlock-objects:
405
406RLock Objects
407-------------
408
409A reentrant lock is a synchronization primitive that may be acquired multiple
410times by the same thread. Internally, it uses the concepts of "owning thread"
411and "recursion level" in addition to the locked/unlocked state used by primitive
412locks. In the locked state, some thread owns the lock; in the unlocked state,
413no thread owns it.
414
415To lock the lock, a thread calls its :meth:`acquire` method; this returns once
416the thread owns the lock. To unlock the lock, a thread calls its
417:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
418nested; only the final :meth:`release` (the :meth:`release` of the outermost
419pair) resets the lock to unlocked and allows another thread blocked in
420:meth:`acquire` to proceed.
421
422
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000423.. method:: RLock.acquire(blocking=True, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425 Acquire a lock, blocking or non-blocking.
426
427 When invoked without arguments: if this thread already owns the lock, increment
428 the recursion level by one, and return immediately. Otherwise, if another
429 thread owns the lock, block until the lock is unlocked. Once the lock is
430 unlocked (not owned by any thread), then grab ownership, set the recursion level
431 to one, and return. If more than one thread is blocked waiting until the lock
432 is unlocked, only one at a time will be able to grab ownership of the lock.
433 There is no return value in this case.
434
435 When invoked with the *blocking* argument set to true, do the same thing as when
436 called without arguments, and return true.
437
438 When invoked with the *blocking* argument set to false, do not block. If a call
439 without an argument would block, return false immediately; otherwise, do the
440 same thing as when called without arguments, and return true.
441
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000442 When invoked with the floating-point *timeout* argument set to a positive
443 value, block for at most the number of seconds specified by *timeout*
444 and as long as the lock cannot be acquired. Return true if the lock has
445 been acquired, false if the timeout has elapsed.
446
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000447 .. versionchanged:: 3.2
448 The *timeout* parameter is new.
449
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451.. method:: RLock.release()
452
453 Release a lock, decrementing the recursion level. If after the decrement it is
454 zero, reset the lock to unlocked (not owned by any thread), and if any other
455 threads are blocked waiting for the lock to become unlocked, allow exactly one
456 of them to proceed. If after the decrement the recursion level is still
457 nonzero, the lock remains locked and owned by the calling thread.
458
459 Only call this method when the calling thread owns the lock. A
460 :exc:`RuntimeError` is raised if this method is called when the lock is
461 unlocked.
462
463 There is no return value.
464
465
466.. _condition-objects:
467
468Condition Objects
469-----------------
470
471A condition variable is always associated with some kind of lock; this can be
472passed in or one will be created by default. (Passing one in is useful when
473several condition variables must share the same lock.)
474
475A condition variable has :meth:`acquire` and :meth:`release` methods that call
476the corresponding methods of the associated lock. It also has a :meth:`wait`
Georg Brandlf9926402008-06-13 06:32:25 +0000477method, and :meth:`notify` and :meth:`notify_all` methods. These three must only
Georg Brandl116aa622007-08-15 14:28:22 +0000478be called when the calling thread has acquired the lock, otherwise a
479:exc:`RuntimeError` is raised.
480
481The :meth:`wait` method releases the lock, and then blocks until it is awakened
Georg Brandlf9926402008-06-13 06:32:25 +0000482by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
Georg Brandl116aa622007-08-15 14:28:22 +0000483another thread. Once awakened, it re-acquires the lock and returns. It is also
484possible to specify a timeout.
485
486The :meth:`notify` method wakes up one of the threads waiting for the condition
Georg Brandlf9926402008-06-13 06:32:25 +0000487variable, if any are waiting. The :meth:`notify_all` method wakes up all threads
Georg Brandl116aa622007-08-15 14:28:22 +0000488waiting for the condition variable.
489
Georg Brandlf9926402008-06-13 06:32:25 +0000490Note: the :meth:`notify` and :meth:`notify_all` methods don't release the lock;
Georg Brandl116aa622007-08-15 14:28:22 +0000491this means that the thread or threads awakened will not return from their
492:meth:`wait` call immediately, but only when the thread that called
Georg Brandlf9926402008-06-13 06:32:25 +0000493:meth:`notify` or :meth:`notify_all` finally relinquishes ownership of the lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495Tip: the typical programming style using condition variables uses the lock to
496synchronize access to some shared state; threads that are interested in a
497particular change of state call :meth:`wait` repeatedly until they see the
498desired state, while threads that modify the state call :meth:`notify` or
Georg Brandlf9926402008-06-13 06:32:25 +0000499:meth:`notify_all` when they change the state in such a way that it could
Georg Brandl116aa622007-08-15 14:28:22 +0000500possibly be a desired state for one of the waiters. For example, the following
501code is a generic producer-consumer situation with unlimited buffer capacity::
502
503 # Consume one item
504 cv.acquire()
505 while not an_item_is_available():
506 cv.wait()
507 get_an_available_item()
508 cv.release()
509
510 # Produce one item
511 cv.acquire()
512 make_an_item_available()
513 cv.notify()
514 cv.release()
515
Georg Brandlf9926402008-06-13 06:32:25 +0000516To choose between :meth:`notify` and :meth:`notify_all`, consider whether one
Georg Brandl116aa622007-08-15 14:28:22 +0000517state change can be interesting for only one or several waiting threads. E.g.
518in a typical producer-consumer situation, adding one item to the buffer only
519needs to wake up one consumer thread.
520
521
Georg Brandl7f01a132009-09-16 15:58:14 +0000522.. class:: Condition(lock=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000523
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000524 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
525 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
526 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000528 .. method:: acquire(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000530 Acquire the underlying lock. This method calls the corresponding method on
531 the underlying lock; the return value is whatever that method returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000532
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000533 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000535 Release the underlying lock. This method calls the corresponding method on
536 the underlying lock; there is no return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Georg Brandl7f01a132009-09-16 15:58:14 +0000538 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000539
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000540 Wait until notified or until a timeout occurs. If the calling thread has
541 not acquired the lock when this method is called, a :exc:`RuntimeError` is
542 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000544 This method releases the underlying lock, and then blocks until it is
545 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
546 condition variable in another thread, or until the optional timeout
547 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000548
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000549 When the *timeout* argument is present and not ``None``, it should be a
550 floating point number specifying a timeout for the operation in seconds
551 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000553 When the underlying lock is an :class:`RLock`, it is not released using
554 its :meth:`release` method, since this may not actually unlock the lock
555 when it was acquired multiple times recursively. Instead, an internal
556 interface of the :class:`RLock` class is used, which really unlocks it
557 even when it has been recursively acquired several times. Another internal
558 interface is then used to restore the recursion level when the lock is
559 reacquired.
Georg Brandl116aa622007-08-15 14:28:22 +0000560
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000561 .. method:: notify()
Georg Brandl116aa622007-08-15 14:28:22 +0000562
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000563 Wake up a thread waiting on this condition, if any. If the calling thread
564 has not acquired the lock when this method is called, a
565 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000567 This method wakes up one of the threads waiting for the condition
568 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000570 The current implementation wakes up exactly one thread, if any are
571 waiting. However, it's not safe to rely on this behavior. A future,
572 optimized implementation may occasionally wake up more than one thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000573
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000574 Note: the awakened thread does not actually return from its :meth:`wait`
575 call until it can reacquire the lock. Since :meth:`notify` does not
576 release the lock, its caller should.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000578 .. method:: notify_all()
Georg Brandl116aa622007-08-15 14:28:22 +0000579
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000580 Wake up all threads waiting on this condition. This method acts like
581 :meth:`notify`, but wakes up all waiting threads instead of one. If the
582 calling thread has not acquired the lock when this method is called, a
583 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585
586.. _semaphore-objects:
587
588Semaphore Objects
589-----------------
590
591This is one of the oldest synchronization primitives in the history of computer
592science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
593used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
594
595A semaphore manages an internal counter which is decremented by each
596:meth:`acquire` call and incremented by each :meth:`release` call. The counter
597can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
598waiting until some other thread calls :meth:`release`.
599
600
Georg Brandl7f01a132009-09-16 15:58:14 +0000601.. class:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000602
603 The optional argument gives the initial *value* for the internal counter; it
604 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
605 raised.
606
Antoine Pitrou0454af92010-04-17 23:51:58 +0000607 .. method:: acquire(blocking=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000608
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000609 Acquire a semaphore.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000611 When invoked without arguments: if the internal counter is larger than
612 zero on entry, decrement it by one and return immediately. If it is zero
613 on entry, block, waiting until some other thread has called
614 :meth:`release` to make it larger than zero. This is done with proper
615 interlocking so that if multiple :meth:`acquire` calls are blocked,
616 :meth:`release` will wake exactly one of them up. The implementation may
617 pick one at random, so the order in which blocked threads are awakened
Antoine Pitrou0454af92010-04-17 23:51:58 +0000618 should not be relied on. Returns true (or blocks indefinitely).
Georg Brandl116aa622007-08-15 14:28:22 +0000619
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000620 When invoked with *blocking* set to false, do not block. If a call
Antoine Pitrou0454af92010-04-17 23:51:58 +0000621 without an argument would block, return false immediately; otherwise,
622 do the same thing as when called without arguments, and return true.
623
624 When invoked with a *timeout* other than None, it will block for at
625 most *timeout* seconds. If acquire does not complete successfully in
626 that interval, return false. Return true otherwise.
627
628 .. versionchanged:: 3.2
629 The *timeout* parameter is new.
Georg Brandl116aa622007-08-15 14:28:22 +0000630
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000631 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000633 Release a semaphore, incrementing the internal counter by one. When it
634 was zero on entry and another thread is waiting for it to become larger
635 than zero again, wake up that thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000636
637
638.. _semaphore-examples:
639
640:class:`Semaphore` Example
641^^^^^^^^^^^^^^^^^^^^^^^^^^
642
643Semaphores are often used to guard resources with limited capacity, for example,
644a database server. In any situation where the size of the resource size is
645fixed, you should use a bounded semaphore. Before spawning any worker threads,
646your main thread would initialize the semaphore::
647
648 maxconnections = 5
649 ...
650 pool_sema = BoundedSemaphore(value=maxconnections)
651
652Once spawned, worker threads call the semaphore's acquire and release methods
653when they need to connect to the server::
654
655 pool_sema.acquire()
656 conn = connectdb()
657 ... use connection ...
658 conn.close()
659 pool_sema.release()
660
661The use of a bounded semaphore reduces the chance that a programming error which
662causes the semaphore to be released more than it's acquired will go undetected.
663
664
665.. _event-objects:
666
667Event Objects
668-------------
669
670This is one of the simplest mechanisms for communication between threads: one
671thread signals an event and other threads wait for it.
672
673An event object manages an internal flag that can be set to true with the
Georg Brandl502d9a52009-07-26 15:02:41 +0000674:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl116aa622007-08-15 14:28:22 +0000675:meth:`wait` method blocks until the flag is true.
676
677
678.. class:: Event()
679
680 The internal flag is initially false.
681
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000682 .. method:: is_set()
Georg Brandl116aa622007-08-15 14:28:22 +0000683
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000684 Return true if and only if the internal flag is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000686 .. method:: set()
Georg Brandl116aa622007-08-15 14:28:22 +0000687
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000688 Set the internal flag to true. All threads waiting for it to become true
689 are awakened. Threads that call :meth:`wait` once the flag is true will
690 not block at all.
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000692 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000694 Reset the internal flag to false. Subsequently, threads calling
Georg Brandl502d9a52009-07-26 15:02:41 +0000695 :meth:`wait` will block until :meth:`.set` is called to set the internal
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000696 flag to true again.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Georg Brandl7f01a132009-09-16 15:58:14 +0000698 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000700 Block until the internal flag is true. If the internal flag is true on
701 entry, return immediately. Otherwise, block until another thread calls
702 :meth:`set` to set the flag to true, or until the optional timeout occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000704 When the timeout argument is present and not ``None``, it should be a
705 floating point number specifying a timeout for the operation in seconds
706 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000708 This method returns the internal flag on exit, so it will always return
709 ``True`` except if a timeout is given and the operation times out.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000711 .. versionchanged:: 3.1
712 Previously, the method always returned ``None``.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000713
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Georg Brandl116aa622007-08-15 14:28:22 +0000715.. _timer-objects:
716
717Timer Objects
718-------------
719
720This class represents an action that should be run only after a certain amount
721of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
722and as such also functions as an example of creating custom threads.
723
724Timers are started, as with threads, by calling their :meth:`start` method. The
725timer can be stopped (before its action has begun) by calling the :meth:`cancel`
726method. The interval the timer will wait before executing its action may not be
727exactly the same as the interval specified by the user.
728
729For example::
730
731 def hello():
Collin Winterc79461b2007-09-01 23:34:30 +0000732 print("hello, world")
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734 t = Timer(30.0, hello)
735 t.start() # after 30 seconds, "hello, world" will be printed
736
737
738.. class:: Timer(interval, function, args=[], kwargs={})
739
740 Create a timer that will run *function* with arguments *args* and keyword
741 arguments *kwargs*, after *interval* seconds have passed.
742
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000743 .. method:: cancel()
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000745 Stop the timer, and cancel the execution of the timer's action. This will
746 only work if the timer is still in its waiting stage.
Georg Brandl116aa622007-08-15 14:28:22 +0000747
748
749.. _with-locks:
750
751Using locks, conditions, and semaphores in the :keyword:`with` statement
752------------------------------------------------------------------------
753
754All of the objects provided by this module that have :meth:`acquire` and
755:meth:`release` methods can be used as context managers for a :keyword:`with`
756statement. The :meth:`acquire` method will be called when the block is entered,
757and :meth:`release` will be called when the block is exited.
758
759Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
760:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
761:keyword:`with` statement context managers. For example::
762
Georg Brandl116aa622007-08-15 14:28:22 +0000763 import threading
764
765 some_rlock = threading.RLock()
766
767 with some_rlock:
Collin Winterc79461b2007-09-01 23:34:30 +0000768 print("some_rlock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000769
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000770
771.. _threaded-imports:
772
773Importing in threaded code
774--------------------------
775
776While the import machinery is thread safe, there are two key
777restrictions on threaded imports due to inherent limitations in the way
778that thread safety is provided:
779
780* Firstly, other than in the main module, an import should not have the
781 side effect of spawning a new thread and then waiting for that thread in
782 any way. Failing to abide by this restriction can lead to a deadlock if
783 the spawned thread directly or indirectly attempts to import a module.
784* Secondly, all import attempts must be completed before the interpreter
785 starts shutting itself down. This can be most easily achieved by only
786 performing imports from non-daemon threads created through the threading
787 module. Daemon threads and threads created directly with the thread
788 module will require some other form of synchronization to ensure they do
789 not attempt imports after system shutdown has commenced. Failure to
790 abide by this restriction will lead to intermittent exceptions and
791 crashes during interpreter shutdown (as the late imports attempt to
792 access machinery which is no longer in a valid state).