blob: 31f1b0e878f2ded4c3830374a5527bf49709af7e [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 Brandl116aa622007-08-15 14:28:22 +0000169Detailed interfaces for the objects are documented below.
170
171The design of this module is loosely based on Java's threading model. However,
172where Java makes locks and condition variables basic behavior of every object,
173they are separate objects in Python. Python's :class:`Thread` class supports a
174subset of the behavior of Java's Thread class; currently, there are no
175priorities, no thread groups, and threads cannot be destroyed, stopped,
176suspended, resumed, or interrupted. The static methods of Java's Thread class,
177when implemented, are mapped to module-level functions.
178
179All of the methods described below are executed atomically.
180
181
Georg Brandla971c652008-11-07 09:39:56 +0000182.. _thread-objects:
183
184Thread Objects
185--------------
186
187This class represents an activity that is run in a separate thread of control.
188There are two ways to specify the activity: by passing a callable object to the
189constructor, or by overriding the :meth:`run` method in a subclass. No other
190methods (except for the constructor) should be overridden in a subclass. In
191other words, *only* override the :meth:`__init__` and :meth:`run` methods of
192this class.
193
194Once a thread object is created, its activity must be started by calling the
195thread's :meth:`start` method. This invokes the :meth:`run` method in a
196separate thread of control.
197
198Once the thread's activity is started, the thread is considered 'alive'. It
199stops being alive when its :meth:`run` method terminates -- either normally, or
200by raising an unhandled exception. The :meth:`is_alive` method tests whether the
201thread is alive.
202
203Other threads can call a thread's :meth:`join` method. This blocks the calling
204thread until the thread whose :meth:`join` method is called is terminated.
205
206A thread has a name. The name can be passed to the constructor, and read or
207changed through the :attr:`name` attribute.
208
209A thread can be flagged as a "daemon thread". The significance of this flag is
210that the entire Python program exits when only daemon threads are left. The
211initial value is inherited from the creating thread. The flag can be set
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000212through the :attr:`daemon` property.
Georg Brandla971c652008-11-07 09:39:56 +0000213
214There is a "main thread" object; this corresponds to the initial thread of
215control in the Python program. It is not a daemon thread.
216
217There is the possibility that "dummy thread objects" are created. These are
218thread objects corresponding to "alien threads", which are threads of control
219started outside the threading module, such as directly from C code. Dummy
220thread objects have limited functionality; they are always considered alive and
221daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
222impossible to detect the termination of alien threads.
223
224
225.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
226
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000227 This constructor should always be called with keyword arguments. Arguments
228 are:
Georg Brandla971c652008-11-07 09:39:56 +0000229
230 *group* should be ``None``; reserved for future extension when a
231 :class:`ThreadGroup` class is implemented.
232
233 *target* is the callable object to be invoked by the :meth:`run` method.
234 Defaults to ``None``, meaning nothing is called.
235
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000236 *name* is the thread name. By default, a unique name is constructed of the
237 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandla971c652008-11-07 09:39:56 +0000238
239 *args* is the argument tuple for the target invocation. Defaults to ``()``.
240
241 *kwargs* is a dictionary of keyword arguments for the target invocation.
242 Defaults to ``{}``.
243
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000244 If the subclass overrides the constructor, it must make sure to invoke the
245 base class constructor (``Thread.__init__()``) before doing anything else to
246 the thread.
Georg Brandla971c652008-11-07 09:39:56 +0000247
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000248 .. method:: start()
Georg Brandla971c652008-11-07 09:39:56 +0000249
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000250 Start the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000251
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000252 It must be called at most once per thread object. It arranges for the
253 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandla971c652008-11-07 09:39:56 +0000254
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000255 This method will raise a :exc:`RuntimeException` if called more than once
256 on the same thread object.
Georg Brandla971c652008-11-07 09:39:56 +0000257
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000258 .. method:: run()
Georg Brandla971c652008-11-07 09:39:56 +0000259
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000260 Method representing the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000261
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000262 You may override this method in a subclass. The standard :meth:`run`
263 method invokes the callable object passed to the object's constructor as
264 the *target* argument, if any, with sequential and keyword arguments taken
265 from the *args* and *kwargs* arguments, respectively.
Georg Brandla971c652008-11-07 09:39:56 +0000266
Georg Brandl7f01a132009-09-16 15:58:14 +0000267 .. method:: join(timeout=None)
Georg Brandla971c652008-11-07 09:39:56 +0000268
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000269 Wait until the thread terminates. This blocks the calling thread until the
270 thread whose :meth:`join` method is called terminates -- either normally
271 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandla971c652008-11-07 09:39:56 +0000272
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000273 When the *timeout* argument is present and not ``None``, it should be a
274 floating point number specifying a timeout for the operation in seconds
275 (or fractions thereof). As :meth:`join` always returns ``None``, you must
276 call :meth:`is_alive` after :meth:`join` to decide whether a timeout
277 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandla971c652008-11-07 09:39:56 +0000278
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000279 When the *timeout* argument is not present or ``None``, the operation will
280 block until the thread terminates.
Georg Brandla971c652008-11-07 09:39:56 +0000281
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000282 A thread can be :meth:`join`\ ed many times.
Georg Brandla971c652008-11-07 09:39:56 +0000283
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000284 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
285 the current thread as that would cause a deadlock. It is also an error to
286 :meth:`join` a thread before it has been started and attempts to do so
287 raises the same exception.
Georg Brandla971c652008-11-07 09:39:56 +0000288
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000289 .. attribute:: name
Georg Brandla971c652008-11-07 09:39:56 +0000290
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000291 A string used for identification purposes only. It has no semantics.
292 Multiple threads may be given the same name. The initial name is set by
293 the constructor.
Georg Brandla971c652008-11-07 09:39:56 +0000294
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000295 .. method:: getName()
296 setName()
Georg Brandla971c652008-11-07 09:39:56 +0000297
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000298 Old getter/setter API for :attr:`~Thread.name`; use it directly as a
299 property instead.
Georg Brandla971c652008-11-07 09:39:56 +0000300
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000301 .. attribute:: ident
Georg Brandla971c652008-11-07 09:39:56 +0000302
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000303 The 'thread identifier' of this thread or ``None`` if the thread has not
304 been started. This is a nonzero integer. See the
305 :func:`thread.get_ident()` function. Thread identifiers may be recycled
306 when a thread exits and another thread is created. The identifier is
307 available even after the thread has exited.
Georg Brandla971c652008-11-07 09:39:56 +0000308
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000309 .. method:: is_alive()
Georg Brandla971c652008-11-07 09:39:56 +0000310
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000311 Return whether the thread is alive.
Georg Brandl770b0be2009-01-02 20:10:05 +0000312
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000313 Roughly, a thread is alive from the moment the :meth:`start` method
314 returns until its :meth:`run` method terminates. The module function
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000315 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl770b0be2009-01-02 20:10:05 +0000316
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000317 .. attribute:: daemon
Georg Brandl770b0be2009-01-02 20:10:05 +0000318
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000319 A boolean value indicating whether this thread is a daemon thread (True)
320 or not (False). This must be set before :meth:`start` is called,
321 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
322 from the creating thread; the main thread is not a daemon thread and
323 therefore all threads created in the main thread default to :attr:`daemon`
324 = ``False``.
Georg Brandla971c652008-11-07 09:39:56 +0000325
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000326 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandla971c652008-11-07 09:39:56 +0000327
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000328 .. method:: isDaemon()
329 setDaemon()
Georg Brandla971c652008-11-07 09:39:56 +0000330
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000331 Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
332 property instead.
Georg Brandl770b0be2009-01-02 20:10:05 +0000333
334
Georg Brandl116aa622007-08-15 14:28:22 +0000335.. _lock-objects:
336
337Lock Objects
338------------
339
340A primitive lock is a synchronization primitive that is not owned by a
341particular thread when locked. In Python, it is currently the lowest level
Georg Brandl2067bfd2008-05-25 13:05:15 +0000342synchronization primitive available, implemented directly by the :mod:`_thread`
Georg Brandl116aa622007-08-15 14:28:22 +0000343extension module.
344
345A primitive lock is in one of two states, "locked" or "unlocked". It is created
346in the unlocked state. It has two basic methods, :meth:`acquire` and
347:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
348to locked and returns immediately. When the state is locked, :meth:`acquire`
349blocks until a call to :meth:`release` in another thread changes it to unlocked,
350then the :meth:`acquire` call resets it to locked and returns. The
351:meth:`release` method should only be called in the locked state; it changes the
352state to unlocked and returns immediately. If an attempt is made to release an
353unlocked lock, a :exc:`RuntimeError` will be raised.
354
355When more than one thread is blocked in :meth:`acquire` waiting for the state to
356turn to unlocked, only one thread proceeds when a :meth:`release` call resets
357the state to unlocked; which one of the waiting threads proceeds is not defined,
358and may vary across implementations.
359
360All methods are executed atomically.
361
362
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000363.. method:: Lock.acquire(blocking=True, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365 Acquire a lock, blocking or non-blocking.
366
367 When invoked without arguments, block until the lock is unlocked, then set it to
368 locked, and return true.
369
370 When invoked with the *blocking* argument set to true, do the same thing as when
371 called without arguments, and return true.
372
373 When invoked with the *blocking* argument set to false, do not block. If a call
374 without an argument would block, return false immediately; otherwise, do the
375 same thing as when called without arguments, and return true.
376
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000377 When invoked with the floating-point *timeout* argument set to a positive
378 value, block for at most the number of seconds specified by *timeout*
379 and as long as the lock cannot be acquired. A negative *timeout* argument
380 specifies an unbounded wait. It is forbidden to specify a *timeout*
381 when *blocking* is false.
382
383 The return value is ``True`` if the lock is acquired successfully,
384 ``False`` if not (for example if the *timeout* expired).
385
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000386 .. versionchanged:: 3.2
387 The *timeout* parameter is new.
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389.. method:: Lock.release()
390
391 Release a lock.
392
393 When the lock is locked, reset it to unlocked, and return. If any other threads
394 are blocked waiting for the lock to become unlocked, allow exactly one of them
395 to proceed.
396
397 Do not call this method when the lock is unlocked.
398
399 There is no return value.
400
401
402.. _rlock-objects:
403
404RLock Objects
405-------------
406
407A reentrant lock is a synchronization primitive that may be acquired multiple
408times by the same thread. Internally, it uses the concepts of "owning thread"
409and "recursion level" in addition to the locked/unlocked state used by primitive
410locks. In the locked state, some thread owns the lock; in the unlocked state,
411no thread owns it.
412
413To lock the lock, a thread calls its :meth:`acquire` method; this returns once
414the thread owns the lock. To unlock the lock, a thread calls its
415:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
416nested; only the final :meth:`release` (the :meth:`release` of the outermost
417pair) resets the lock to unlocked and allows another thread blocked in
418:meth:`acquire` to proceed.
419
420
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000421.. method:: RLock.acquire(blocking=True, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423 Acquire a lock, blocking or non-blocking.
424
425 When invoked without arguments: if this thread already owns the lock, increment
426 the recursion level by one, and return immediately. Otherwise, if another
427 thread owns the lock, block until the lock is unlocked. Once the lock is
428 unlocked (not owned by any thread), then grab ownership, set the recursion level
429 to one, and return. If more than one thread is blocked waiting until the lock
430 is unlocked, only one at a time will be able to grab ownership of the lock.
431 There is no return value in this case.
432
433 When invoked with the *blocking* argument set to true, do the same thing as when
434 called without arguments, and return true.
435
436 When invoked with the *blocking* argument set to false, do not block. If a call
437 without an argument would block, return false immediately; otherwise, do the
438 same thing as when called without arguments, and return true.
439
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000440 When invoked with the floating-point *timeout* argument set to a positive
441 value, block for at most the number of seconds specified by *timeout*
442 and as long as the lock cannot be acquired. Return true if the lock has
443 been acquired, false if the timeout has elapsed.
444
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000445 .. versionchanged:: 3.2
446 The *timeout* parameter is new.
447
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449.. method:: RLock.release()
450
451 Release a lock, decrementing the recursion level. If after the decrement it is
452 zero, reset the lock to unlocked (not owned by any thread), and if any other
453 threads are blocked waiting for the lock to become unlocked, allow exactly one
454 of them to proceed. If after the decrement the recursion level is still
455 nonzero, the lock remains locked and owned by the calling thread.
456
457 Only call this method when the calling thread owns the lock. A
458 :exc:`RuntimeError` is raised if this method is called when the lock is
459 unlocked.
460
461 There is no return value.
462
463
464.. _condition-objects:
465
466Condition Objects
467-----------------
468
469A condition variable is always associated with some kind of lock; this can be
470passed in or one will be created by default. (Passing one in is useful when
471several condition variables must share the same lock.)
472
473A condition variable has :meth:`acquire` and :meth:`release` methods that call
474the corresponding methods of the associated lock. It also has a :meth:`wait`
Georg Brandlf9926402008-06-13 06:32:25 +0000475method, and :meth:`notify` and :meth:`notify_all` methods. These three must only
Georg Brandl116aa622007-08-15 14:28:22 +0000476be called when the calling thread has acquired the lock, otherwise a
477:exc:`RuntimeError` is raised.
478
479The :meth:`wait` method releases the lock, and then blocks until it is awakened
Georg Brandlf9926402008-06-13 06:32:25 +0000480by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
Georg Brandl116aa622007-08-15 14:28:22 +0000481another thread. Once awakened, it re-acquires the lock and returns. It is also
482possible to specify a timeout.
483
484The :meth:`notify` method wakes up one of the threads waiting for the condition
Georg Brandlf9926402008-06-13 06:32:25 +0000485variable, if any are waiting. The :meth:`notify_all` method wakes up all threads
Georg Brandl116aa622007-08-15 14:28:22 +0000486waiting for the condition variable.
487
Georg Brandlf9926402008-06-13 06:32:25 +0000488Note: the :meth:`notify` and :meth:`notify_all` methods don't release the lock;
Georg Brandl116aa622007-08-15 14:28:22 +0000489this means that the thread or threads awakened will not return from their
490:meth:`wait` call immediately, but only when the thread that called
Georg Brandlf9926402008-06-13 06:32:25 +0000491:meth:`notify` or :meth:`notify_all` finally relinquishes ownership of the lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493Tip: the typical programming style using condition variables uses the lock to
494synchronize access to some shared state; threads that are interested in a
495particular change of state call :meth:`wait` repeatedly until they see the
496desired state, while threads that modify the state call :meth:`notify` or
Georg Brandlf9926402008-06-13 06:32:25 +0000497:meth:`notify_all` when they change the state in such a way that it could
Georg Brandl116aa622007-08-15 14:28:22 +0000498possibly be a desired state for one of the waiters. For example, the following
499code is a generic producer-consumer situation with unlimited buffer capacity::
500
501 # Consume one item
502 cv.acquire()
503 while not an_item_is_available():
504 cv.wait()
505 get_an_available_item()
506 cv.release()
507
508 # Produce one item
509 cv.acquire()
510 make_an_item_available()
511 cv.notify()
512 cv.release()
513
Georg Brandlf9926402008-06-13 06:32:25 +0000514To choose between :meth:`notify` and :meth:`notify_all`, consider whether one
Georg Brandl116aa622007-08-15 14:28:22 +0000515state change can be interesting for only one or several waiting threads. E.g.
516in a typical producer-consumer situation, adding one item to the buffer only
517needs to wake up one consumer thread.
518
519
Georg Brandl7f01a132009-09-16 15:58:14 +0000520.. class:: Condition(lock=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000522 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
523 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
524 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000526 .. method:: acquire(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000528 Acquire the underlying lock. This method calls the corresponding method on
529 the underlying lock; the return value is whatever that method returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000531 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000532
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000533 Release the underlying lock. This method calls the corresponding method on
534 the underlying lock; there is no return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Georg Brandl7f01a132009-09-16 15:58:14 +0000536 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000538 Wait until notified or until a timeout occurs. If the calling thread has
539 not acquired the lock when this method is called, a :exc:`RuntimeError` is
540 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000542 This method releases the underlying lock, and then blocks until it is
543 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
544 condition variable in another thread, or until the optional timeout
545 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000547 When the *timeout* argument is present and not ``None``, it should be a
548 floating point number specifying a timeout for the operation in seconds
549 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000551 When the underlying lock is an :class:`RLock`, it is not released using
552 its :meth:`release` method, since this may not actually unlock the lock
553 when it was acquired multiple times recursively. Instead, an internal
554 interface of the :class:`RLock` class is used, which really unlocks it
555 even when it has been recursively acquired several times. Another internal
556 interface is then used to restore the recursion level when the lock is
557 reacquired.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000559 .. method:: notify()
Georg Brandl116aa622007-08-15 14:28:22 +0000560
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000561 Wake up a thread waiting on this condition, if any. If the calling thread
562 has not acquired the lock when this method is called, a
563 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000565 This method wakes up one of the threads waiting for the condition
566 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000567
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000568 The current implementation wakes up exactly one thread, if any are
569 waiting. However, it's not safe to rely on this behavior. A future,
570 optimized implementation may occasionally wake up more than one thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000571
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000572 Note: the awakened thread does not actually return from its :meth:`wait`
573 call until it can reacquire the lock. Since :meth:`notify` does not
574 release the lock, its caller should.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000576 .. method:: notify_all()
Georg Brandl116aa622007-08-15 14:28:22 +0000577
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000578 Wake up all threads waiting on this condition. This method acts like
579 :meth:`notify`, but wakes up all waiting threads instead of one. If the
580 calling thread has not acquired the lock when this method is called, a
581 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583
584.. _semaphore-objects:
585
586Semaphore Objects
587-----------------
588
589This is one of the oldest synchronization primitives in the history of computer
590science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
591used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
592
593A semaphore manages an internal counter which is decremented by each
594:meth:`acquire` call and incremented by each :meth:`release` call. The counter
595can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
596waiting until some other thread calls :meth:`release`.
597
598
Georg Brandl7f01a132009-09-16 15:58:14 +0000599.. class:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601 The optional argument gives the initial *value* for the internal counter; it
602 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
603 raised.
604
Antoine Pitrou0454af92010-04-17 23:51:58 +0000605 .. method:: acquire(blocking=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000607 Acquire a semaphore.
Georg Brandl116aa622007-08-15 14:28:22 +0000608
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000609 When invoked without arguments: if the internal counter is larger than
610 zero on entry, decrement it by one and return immediately. If it is zero
611 on entry, block, waiting until some other thread has called
612 :meth:`release` to make it larger than zero. This is done with proper
613 interlocking so that if multiple :meth:`acquire` calls are blocked,
614 :meth:`release` will wake exactly one of them up. The implementation may
615 pick one at random, so the order in which blocked threads are awakened
Antoine Pitrou0454af92010-04-17 23:51:58 +0000616 should not be relied on. Returns true (or blocks indefinitely).
Georg Brandl116aa622007-08-15 14:28:22 +0000617
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000618 When invoked with *blocking* set to false, do not block. If a call
Antoine Pitrou0454af92010-04-17 23:51:58 +0000619 without an argument would block, return false immediately; otherwise,
620 do the same thing as when called without arguments, and return true.
621
622 When invoked with a *timeout* other than None, it will block for at
623 most *timeout* seconds. If acquire does not complete successfully in
624 that interval, return false. Return true otherwise.
625
626 .. versionchanged:: 3.2
627 The *timeout* parameter is new.
Georg Brandl116aa622007-08-15 14:28:22 +0000628
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000629 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000630
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000631 Release a semaphore, incrementing the internal counter by one. When it
632 was zero on entry and another thread is waiting for it to become larger
633 than zero again, wake up that thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635
636.. _semaphore-examples:
637
638:class:`Semaphore` Example
639^^^^^^^^^^^^^^^^^^^^^^^^^^
640
641Semaphores are often used to guard resources with limited capacity, for example,
642a database server. In any situation where the size of the resource size is
643fixed, you should use a bounded semaphore. Before spawning any worker threads,
644your main thread would initialize the semaphore::
645
646 maxconnections = 5
647 ...
648 pool_sema = BoundedSemaphore(value=maxconnections)
649
650Once spawned, worker threads call the semaphore's acquire and release methods
651when they need to connect to the server::
652
653 pool_sema.acquire()
654 conn = connectdb()
655 ... use connection ...
656 conn.close()
657 pool_sema.release()
658
659The use of a bounded semaphore reduces the chance that a programming error which
660causes the semaphore to be released more than it's acquired will go undetected.
661
662
663.. _event-objects:
664
665Event Objects
666-------------
667
668This is one of the simplest mechanisms for communication between threads: one
669thread signals an event and other threads wait for it.
670
671An event object manages an internal flag that can be set to true with the
Georg Brandl502d9a52009-07-26 15:02:41 +0000672:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl116aa622007-08-15 14:28:22 +0000673:meth:`wait` method blocks until the flag is true.
674
675
676.. class:: Event()
677
678 The internal flag is initially false.
679
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000680 .. method:: is_set()
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000682 Return true if and only if the internal flag is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000683
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000684 .. method:: set()
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000686 Set the internal flag to true. All threads waiting for it to become true
687 are awakened. Threads that call :meth:`wait` once the flag is true will
688 not block at all.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000690 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000692 Reset the internal flag to false. Subsequently, threads calling
Georg Brandl502d9a52009-07-26 15:02:41 +0000693 :meth:`wait` will block until :meth:`.set` is called to set the internal
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000694 flag to true again.
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Georg Brandl7f01a132009-09-16 15:58:14 +0000696 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000698 Block until the internal flag is true. If the internal flag is true on
699 entry, return immediately. Otherwise, block until another thread calls
700 :meth:`set` to set the flag to true, or until the optional timeout occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000702 When the timeout argument is present and not ``None``, it should be a
703 floating point number specifying a timeout for the operation in seconds
704 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000705
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000706 This method returns the internal flag on exit, so it will always return
707 ``True`` except if a timeout is given and the operation times out.
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000709 .. versionchanged:: 3.1
710 Previously, the method always returned ``None``.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Georg Brandl116aa622007-08-15 14:28:22 +0000713.. _timer-objects:
714
715Timer Objects
716-------------
717
718This class represents an action that should be run only after a certain amount
719of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
720and as such also functions as an example of creating custom threads.
721
722Timers are started, as with threads, by calling their :meth:`start` method. The
723timer can be stopped (before its action has begun) by calling the :meth:`cancel`
724method. The interval the timer will wait before executing its action may not be
725exactly the same as the interval specified by the user.
726
727For example::
728
729 def hello():
Collin Winterc79461b2007-09-01 23:34:30 +0000730 print("hello, world")
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732 t = Timer(30.0, hello)
733 t.start() # after 30 seconds, "hello, world" will be printed
734
735
736.. class:: Timer(interval, function, args=[], kwargs={})
737
738 Create a timer that will run *function* with arguments *args* and keyword
739 arguments *kwargs*, after *interval* seconds have passed.
740
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000741 .. method:: cancel()
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000743 Stop the timer, and cancel the execution of the timer's action. This will
744 only work if the timer is still in its waiting stage.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746
747.. _with-locks:
748
749Using locks, conditions, and semaphores in the :keyword:`with` statement
750------------------------------------------------------------------------
751
752All of the objects provided by this module that have :meth:`acquire` and
753:meth:`release` methods can be used as context managers for a :keyword:`with`
754statement. The :meth:`acquire` method will be called when the block is entered,
755and :meth:`release` will be called when the block is exited.
756
757Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
758:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
759:keyword:`with` statement context managers. For example::
760
Georg Brandl116aa622007-08-15 14:28:22 +0000761 import threading
762
763 some_rlock = threading.RLock()
764
765 with some_rlock:
Collin Winterc79461b2007-09-01 23:34:30 +0000766 print("some_rlock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000767
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000768
769.. _threaded-imports:
770
771Importing in threaded code
772--------------------------
773
774While the import machinery is thread safe, there are two key
775restrictions on threaded imports due to inherent limitations in the way
776that thread safety is provided:
777
778* Firstly, other than in the main module, an import should not have the
779 side effect of spawning a new thread and then waiting for that thread in
780 any way. Failing to abide by this restriction can lead to a deadlock if
781 the spawned thread directly or indirectly attempts to import a module.
782* Secondly, all import attempts must be completed before the interpreter
783 starts shutting itself down. This can be most easily achieved by only
784 performing imports from non-daemon threads created through the threading
785 module. Daemon threads and threads created directly with the thread
786 module will require some other form of synchronization to ensure they do
787 not attempt imports after system shutdown has commenced. Failure to
788 abide by this restriction will lead to intermittent exceptions and
789 crashes during interpreter shutdown (as the late imports attempt to
790 access machinery which is no longer in a valid state).