blob: fb1880915f214ef3350ca0b8e9a98afdafc05fc9 [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
Antoine Pitrou6e7d7112011-01-06 16:34:50 +000020.. impl-detail::
21
22 Due to the :term:`Global Interpreter Lock`, in CPython only one thread
23 can execute Python code at once (even though certain performance-oriented
24 libraries might overcome this limitation).
25 If you want your application to make better of use of the computational
26 resources of multi-core machines, you are advised to use
27 :mod:`multiprocessing`. However, threading is still an appropriate model
28 if you want to run multiple I/O-bound tasks simultaneously.
29
30
Georg Brandl116aa622007-08-15 14:28:22 +000031This module defines the following functions and objects:
32
33
Benjamin Peterson672b8032008-06-11 19:14:14 +000034.. function:: active_count()
Georg Brandl116aa622007-08-15 14:28:22 +000035
36 Return the number of :class:`Thread` objects currently alive. The returned
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +000037 count is equal to the length of the list returned by :func:`.enumerate`.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39
40.. function:: Condition()
41 :noindex:
42
43 A factory function that returns a new condition variable object. A condition
44 variable allows one or more threads to wait until they are notified by another
45 thread.
46
Georg Brandl57a5e3f2010-10-06 08:54:16 +000047 See :ref:`condition-objects`.
48
Georg Brandl116aa622007-08-15 14:28:22 +000049
Benjamin Peterson672b8032008-06-11 19:14:14 +000050.. function:: current_thread()
Georg Brandl116aa622007-08-15 14:28:22 +000051
52 Return the current :class:`Thread` object, corresponding to the caller's thread
53 of control. If the caller's thread of control was not created through the
54 :mod:`threading` module, a dummy thread object with limited functionality is
55 returned.
56
57
58.. function:: enumerate()
59
Benjamin Peterson672b8032008-06-11 19:14:14 +000060 Return a list of all :class:`Thread` objects currently alive. The list
61 includes daemonic threads, dummy thread objects created by
62 :func:`current_thread`, and the main thread. It excludes terminated threads
63 and threads that have not yet been started.
Georg Brandl116aa622007-08-15 14:28:22 +000064
65
66.. function:: Event()
67 :noindex:
68
69 A factory function that returns a new event object. An event manages a flag
Georg Brandlc5605df2009-08-13 08:26:44 +000070 that can be set to true with the :meth:`~Event.set` method and reset to false
71 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
72 is true.
Georg Brandl116aa622007-08-15 14:28:22 +000073
Georg Brandl57a5e3f2010-10-06 08:54:16 +000074 See :ref:`event-objects`.
75
Georg Brandl116aa622007-08-15 14:28:22 +000076
77.. class:: local
78
79 A class that represents thread-local data. Thread-local data are data whose
80 values are thread specific. To manage thread-local data, just create an
81 instance of :class:`local` (or a subclass) and store attributes on it::
82
83 mydata = threading.local()
84 mydata.x = 1
85
86 The instance's values will be different for separate threads.
87
88 For more details and extensive examples, see the documentation string of the
89 :mod:`_threading_local` module.
90
Georg Brandl116aa622007-08-15 14:28:22 +000091
92.. function:: Lock()
93
94 A factory function that returns a new primitive lock object. Once a thread has
95 acquired it, subsequent attempts to acquire it block, until it is released; any
96 thread may release it.
97
Georg Brandl57a5e3f2010-10-06 08:54:16 +000098 See :ref:`lock-objects`.
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101.. function:: RLock()
102
103 A factory function that returns a new reentrant lock object. A reentrant lock
104 must be released by the thread that acquired it. Once a thread has acquired a
105 reentrant lock, the same thread may acquire it again without blocking; the
106 thread must release it once for each time it has acquired it.
107
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000108 See :ref:`rlock-objects`.
109
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Georg Brandlb044b2a2009-09-16 16:05:59 +0000111.. function:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000112 :noindex:
113
114 A factory function that returns a new semaphore object. A semaphore manages a
115 counter representing the number of :meth:`release` calls minus the number of
116 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
117 if necessary until it can return without making the counter negative. If not
118 given, *value* defaults to 1.
119
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000120 See :ref:`semaphore-objects`.
121
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Georg Brandlb044b2a2009-09-16 16:05:59 +0000123.. function:: BoundedSemaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 A factory function that returns a new bounded semaphore object. A bounded
126 semaphore checks to make sure its current value doesn't exceed its initial
127 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
128 are used to guard resources with limited capacity. If the semaphore is released
129 too many times it's a sign of a bug. If not given, *value* defaults to 1.
130
131
132.. class:: Thread
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000133 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 A class that represents a thread of control. This class can be safely
136 subclassed in a limited fashion.
137
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000138 See :ref:`thread-objects`.
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141.. class:: Timer
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000142 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144 A thread that executes a function after a specified interval has passed.
145
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000146 See :ref:`timer-objects`.
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149.. function:: settrace(func)
150
151 .. index:: single: trace function
152
153 Set a trace function for all threads started from the :mod:`threading` module.
154 The *func* will be passed to :func:`sys.settrace` for each thread, before its
155 :meth:`run` method is called.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. function:: setprofile(func)
159
160 .. index:: single: profile function
161
162 Set a profile function for all threads started from the :mod:`threading` module.
163 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
164 :meth:`run` method is called.
165
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167.. function:: stack_size([size])
168
169 Return the thread stack size used when creating new threads. The optional
170 *size* argument specifies the stack size to be used for subsequently created
171 threads, and must be 0 (use platform or configured default) or a positive
172 integer value of at least 32,768 (32kB). If changing the thread stack size is
173 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
174 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
175 is currently the minimum supported stack size value to guarantee sufficient
176 stack space for the interpreter itself. Note that some platforms may have
177 particular restrictions on values for the stack size, such as requiring a
178 minimum stack size > 32kB or requiring allocation in multiples of the system
179 memory page size - platform documentation should be referred to for more
180 information (4kB pages are common; using multiples of 4096 for the stack size is
181 the suggested approach in the absence of more specific information).
182 Availability: Windows, systems with POSIX threads.
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185Detailed interfaces for the objects are documented below.
186
187The design of this module is loosely based on Java's threading model. However,
188where Java makes locks and condition variables basic behavior of every object,
189they are separate objects in Python. Python's :class:`Thread` class supports a
190subset of the behavior of Java's Thread class; currently, there are no
191priorities, no thread groups, and threads cannot be destroyed, stopped,
192suspended, resumed, or interrupted. The static methods of Java's Thread class,
193when implemented, are mapped to module-level functions.
194
195All of the methods described below are executed atomically.
196
197
Georg Brandla971c652008-11-07 09:39:56 +0000198.. _thread-objects:
199
200Thread Objects
201--------------
202
203This class represents an activity that is run in a separate thread of control.
204There are two ways to specify the activity: by passing a callable object to the
205constructor, or by overriding the :meth:`run` method in a subclass. No other
206methods (except for the constructor) should be overridden in a subclass. In
207other words, *only* override the :meth:`__init__` and :meth:`run` methods of
208this class.
209
210Once a thread object is created, its activity must be started by calling the
211thread's :meth:`start` method. This invokes the :meth:`run` method in a
212separate thread of control.
213
214Once the thread's activity is started, the thread is considered 'alive'. It
215stops being alive when its :meth:`run` method terminates -- either normally, or
216by raising an unhandled exception. The :meth:`is_alive` method tests whether the
217thread is alive.
218
219Other threads can call a thread's :meth:`join` method. This blocks the calling
220thread until the thread whose :meth:`join` method is called is terminated.
221
222A thread has a name. The name can be passed to the constructor, and read or
223changed through the :attr:`name` attribute.
224
225A thread can be flagged as a "daemon thread". The significance of this flag is
226that the entire Python program exits when only daemon threads are left. The
227initial value is inherited from the creating thread. The flag can be set
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000228through the :attr:`daemon` property.
Georg Brandla971c652008-11-07 09:39:56 +0000229
230There is a "main thread" object; this corresponds to the initial thread of
231control in the Python program. It is not a daemon thread.
232
233There is the possibility that "dummy thread objects" are created. These are
234thread objects corresponding to "alien threads", which are threads of control
235started outside the threading module, such as directly from C code. Dummy
236thread objects have limited functionality; they are always considered alive and
237daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
238impossible to detect the termination of alien threads.
239
240
241.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
242
Georg Brandlc5605df2009-08-13 08:26:44 +0000243 This constructor should always be called with keyword arguments. Arguments
244 are:
Georg Brandla971c652008-11-07 09:39:56 +0000245
246 *group* should be ``None``; reserved for future extension when a
247 :class:`ThreadGroup` class is implemented.
248
249 *target* is the callable object to be invoked by the :meth:`run` method.
250 Defaults to ``None``, meaning nothing is called.
251
Georg Brandlc5605df2009-08-13 08:26:44 +0000252 *name* is the thread name. By default, a unique name is constructed of the
253 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandla971c652008-11-07 09:39:56 +0000254
255 *args* is the argument tuple for the target invocation. Defaults to ``()``.
256
257 *kwargs* is a dictionary of keyword arguments for the target invocation.
258 Defaults to ``{}``.
259
Georg Brandlc5605df2009-08-13 08:26:44 +0000260 If the subclass overrides the constructor, it must make sure to invoke the
261 base class constructor (``Thread.__init__()``) before doing anything else to
262 the thread.
Georg Brandla971c652008-11-07 09:39:56 +0000263
Georg Brandlc5605df2009-08-13 08:26:44 +0000264 .. method:: start()
Georg Brandla971c652008-11-07 09:39:56 +0000265
Georg Brandlc5605df2009-08-13 08:26:44 +0000266 Start the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000267
Georg Brandlc5605df2009-08-13 08:26:44 +0000268 It must be called at most once per thread object. It arranges for the
269 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandla971c652008-11-07 09:39:56 +0000270
Brian Curtin070f0502011-01-31 19:41:53 +0000271 This method will raise a :exc:`RuntimeError` if called more than once
Georg Brandlc5605df2009-08-13 08:26:44 +0000272 on the same thread object.
Georg Brandla971c652008-11-07 09:39:56 +0000273
Georg Brandlc5605df2009-08-13 08:26:44 +0000274 .. method:: run()
Georg Brandla971c652008-11-07 09:39:56 +0000275
Georg Brandlc5605df2009-08-13 08:26:44 +0000276 Method representing the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000277
Georg Brandlc5605df2009-08-13 08:26:44 +0000278 You may override this method in a subclass. The standard :meth:`run`
279 method invokes the callable object passed to the object's constructor as
280 the *target* argument, if any, with sequential and keyword arguments taken
281 from the *args* and *kwargs* arguments, respectively.
Georg Brandla971c652008-11-07 09:39:56 +0000282
Georg Brandlb044b2a2009-09-16 16:05:59 +0000283 .. method:: join(timeout=None)
Georg Brandla971c652008-11-07 09:39:56 +0000284
Georg Brandlc5605df2009-08-13 08:26:44 +0000285 Wait until the thread terminates. This blocks the calling thread until the
286 thread whose :meth:`join` method is called terminates -- either normally
287 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandla971c652008-11-07 09:39:56 +0000288
Georg Brandlc5605df2009-08-13 08:26:44 +0000289 When the *timeout* argument is present and not ``None``, it should be a
290 floating point number specifying a timeout for the operation in seconds
291 (or fractions thereof). As :meth:`join` always returns ``None``, you must
292 call :meth:`is_alive` after :meth:`join` to decide whether a timeout
293 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandla971c652008-11-07 09:39:56 +0000294
Georg Brandlc5605df2009-08-13 08:26:44 +0000295 When the *timeout* argument is not present or ``None``, the operation will
296 block until the thread terminates.
Georg Brandla971c652008-11-07 09:39:56 +0000297
Georg Brandlc5605df2009-08-13 08:26:44 +0000298 A thread can be :meth:`join`\ ed many times.
Georg Brandla971c652008-11-07 09:39:56 +0000299
Georg Brandlc5605df2009-08-13 08:26:44 +0000300 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
301 the current thread as that would cause a deadlock. It is also an error to
302 :meth:`join` a thread before it has been started and attempts to do so
303 raises the same exception.
Georg Brandla971c652008-11-07 09:39:56 +0000304
Georg Brandlc5605df2009-08-13 08:26:44 +0000305 .. attribute:: name
Georg Brandla971c652008-11-07 09:39:56 +0000306
Georg Brandlc5605df2009-08-13 08:26:44 +0000307 A string used for identification purposes only. It has no semantics.
308 Multiple threads may be given the same name. The initial name is set by
309 the constructor.
Georg Brandla971c652008-11-07 09:39:56 +0000310
Georg Brandlc5605df2009-08-13 08:26:44 +0000311 .. method:: getName()
312 setName()
Georg Brandla971c652008-11-07 09:39:56 +0000313
Georg Brandlc5605df2009-08-13 08:26:44 +0000314 Old getter/setter API for :attr:`~Thread.name`; use it directly as a
315 property instead.
Georg Brandla971c652008-11-07 09:39:56 +0000316
Georg Brandlc5605df2009-08-13 08:26:44 +0000317 .. attribute:: ident
Georg Brandla971c652008-11-07 09:39:56 +0000318
Georg Brandlc5605df2009-08-13 08:26:44 +0000319 The 'thread identifier' of this thread or ``None`` if the thread has not
320 been started. This is a nonzero integer. See the
321 :func:`thread.get_ident()` function. Thread identifiers may be recycled
322 when a thread exits and another thread is created. The identifier is
323 available even after the thread has exited.
Georg Brandla971c652008-11-07 09:39:56 +0000324
Georg Brandlc5605df2009-08-13 08:26:44 +0000325 .. method:: is_alive()
Georg Brandla971c652008-11-07 09:39:56 +0000326
Georg Brandlc5605df2009-08-13 08:26:44 +0000327 Return whether the thread is alive.
Georg Brandl770b0be2009-01-02 20:10:05 +0000328
Brett Cannonb0a30742010-07-23 12:28:28 +0000329 This method returns ``True`` just before the :meth:`run` method starts
330 until just after the :meth:`run` method terminates. The module function
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000331 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl770b0be2009-01-02 20:10:05 +0000332
Georg Brandlc5605df2009-08-13 08:26:44 +0000333 .. attribute:: daemon
Georg Brandl770b0be2009-01-02 20:10:05 +0000334
Georg Brandlc5605df2009-08-13 08:26:44 +0000335 A boolean value indicating whether this thread is a daemon thread (True)
336 or not (False). This must be set before :meth:`start` is called,
337 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
338 from the creating thread; the main thread is not a daemon thread and
339 therefore all threads created in the main thread default to :attr:`daemon`
340 = ``False``.
Georg Brandla971c652008-11-07 09:39:56 +0000341
Georg Brandlc5605df2009-08-13 08:26:44 +0000342 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandla971c652008-11-07 09:39:56 +0000343
Georg Brandlc5605df2009-08-13 08:26:44 +0000344 .. method:: isDaemon()
345 setDaemon()
Georg Brandla971c652008-11-07 09:39:56 +0000346
Georg Brandlc5605df2009-08-13 08:26:44 +0000347 Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
348 property instead.
Georg Brandl770b0be2009-01-02 20:10:05 +0000349
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351.. _lock-objects:
352
353Lock Objects
354------------
355
356A primitive lock is a synchronization primitive that is not owned by a
357particular thread when locked. In Python, it is currently the lowest level
Georg Brandl2067bfd2008-05-25 13:05:15 +0000358synchronization primitive available, implemented directly by the :mod:`_thread`
Georg Brandl116aa622007-08-15 14:28:22 +0000359extension module.
360
361A primitive lock is in one of two states, "locked" or "unlocked". It is created
362in the unlocked state. It has two basic methods, :meth:`acquire` and
363:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
364to locked and returns immediately. When the state is locked, :meth:`acquire`
365blocks until a call to :meth:`release` in another thread changes it to unlocked,
366then the :meth:`acquire` call resets it to locked and returns. The
367:meth:`release` method should only be called in the locked state; it changes the
368state to unlocked and returns immediately. If an attempt is made to release an
369unlocked lock, a :exc:`RuntimeError` will be raised.
370
371When more than one thread is blocked in :meth:`acquire` waiting for the state to
372turn to unlocked, only one thread proceeds when a :meth:`release` call resets
373the state to unlocked; which one of the waiting threads proceeds is not defined,
374and may vary across implementations.
375
376All methods are executed atomically.
377
378
Terry Reedy2b8cf2f2011-01-01 00:29:59 +0000379.. method:: Lock.acquire([blocking])
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381 Acquire a lock, blocking or non-blocking.
382
383 When invoked without arguments, block until the lock is unlocked, then set it to
384 locked, and return true.
385
386 When invoked with the *blocking* argument set to true, do the same thing as when
387 called without arguments, and return true.
388
389 When invoked with the *blocking* argument set to false, do not block. If a call
390 without an argument would block, return false immediately; otherwise, do the
391 same thing as when called without arguments, and return true.
392
393
394.. method:: Lock.release()
395
396 Release a lock.
397
398 When the lock is locked, reset it to unlocked, and return. If any other threads
399 are blocked waiting for the lock to become unlocked, allow exactly one of them
400 to proceed.
401
402 Do not call this method when the lock is unlocked.
403
404 There is no return value.
405
406
407.. _rlock-objects:
408
409RLock Objects
410-------------
411
412A reentrant lock is a synchronization primitive that may be acquired multiple
413times by the same thread. Internally, it uses the concepts of "owning thread"
414and "recursion level" in addition to the locked/unlocked state used by primitive
415locks. In the locked state, some thread owns the lock; in the unlocked state,
416no thread owns it.
417
418To lock the lock, a thread calls its :meth:`acquire` method; this returns once
419the thread owns the lock. To unlock the lock, a thread calls its
420:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
421nested; only the final :meth:`release` (the :meth:`release` of the outermost
422pair) resets the lock to unlocked and allows another thread blocked in
423:meth:`acquire` to proceed.
424
425
Georg Brandlb044b2a2009-09-16 16:05:59 +0000426.. method:: RLock.acquire(blocking=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428 Acquire a lock, blocking or non-blocking.
429
430 When invoked without arguments: if this thread already owns the lock, increment
431 the recursion level by one, and return immediately. Otherwise, if another
432 thread owns the lock, block until the lock is unlocked. Once the lock is
433 unlocked (not owned by any thread), then grab ownership, set the recursion level
434 to one, and return. If more than one thread is blocked waiting until the lock
435 is unlocked, only one at a time will be able to grab ownership of the lock.
436 There is no return value in this case.
437
438 When invoked with the *blocking* argument set to true, do the same thing as when
439 called without arguments, and return true.
440
441 When invoked with the *blocking* argument set to false, do not block. If a call
442 without an argument would block, return false immediately; otherwise, do the
443 same thing as when called without arguments, and return true.
444
445
446.. method:: RLock.release()
447
448 Release a lock, decrementing the recursion level. If after the decrement it is
449 zero, reset the lock to unlocked (not owned by any thread), and if any other
450 threads are blocked waiting for the lock to become unlocked, allow exactly one
451 of them to proceed. If after the decrement the recursion level is still
452 nonzero, the lock remains locked and owned by the calling thread.
453
454 Only call this method when the calling thread owns the lock. A
455 :exc:`RuntimeError` is raised if this method is called when the lock is
456 unlocked.
457
458 There is no return value.
459
460
461.. _condition-objects:
462
463Condition Objects
464-----------------
465
466A condition variable is always associated with some kind of lock; this can be
467passed in or one will be created by default. (Passing one in is useful when
468several condition variables must share the same lock.)
469
470A condition variable has :meth:`acquire` and :meth:`release` methods that call
471the corresponding methods of the associated lock. It also has a :meth:`wait`
Georg Brandlf9926402008-06-13 06:32:25 +0000472method, and :meth:`notify` and :meth:`notify_all` methods. These three must only
Georg Brandl116aa622007-08-15 14:28:22 +0000473be called when the calling thread has acquired the lock, otherwise a
474:exc:`RuntimeError` is raised.
475
476The :meth:`wait` method releases the lock, and then blocks until it is awakened
Georg Brandlf9926402008-06-13 06:32:25 +0000477by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
Georg Brandl116aa622007-08-15 14:28:22 +0000478another thread. Once awakened, it re-acquires the lock and returns. It is also
479possible to specify a timeout.
480
481The :meth:`notify` method wakes up one of the threads waiting for the condition
Georg Brandlf9926402008-06-13 06:32:25 +0000482variable, if any are waiting. The :meth:`notify_all` method wakes up all threads
Georg Brandl116aa622007-08-15 14:28:22 +0000483waiting for the condition variable.
484
Georg Brandlf9926402008-06-13 06:32:25 +0000485Note: the :meth:`notify` and :meth:`notify_all` methods don't release the lock;
Georg Brandl116aa622007-08-15 14:28:22 +0000486this means that the thread or threads awakened will not return from their
487:meth:`wait` call immediately, but only when the thread that called
Georg Brandlf9926402008-06-13 06:32:25 +0000488:meth:`notify` or :meth:`notify_all` finally relinquishes ownership of the lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000489
490Tip: the typical programming style using condition variables uses the lock to
491synchronize access to some shared state; threads that are interested in a
492particular change of state call :meth:`wait` repeatedly until they see the
493desired state, while threads that modify the state call :meth:`notify` or
Georg Brandlf9926402008-06-13 06:32:25 +0000494:meth:`notify_all` when they change the state in such a way that it could
Georg Brandl116aa622007-08-15 14:28:22 +0000495possibly be a desired state for one of the waiters. For example, the following
496code is a generic producer-consumer situation with unlimited buffer capacity::
497
498 # Consume one item
499 cv.acquire()
500 while not an_item_is_available():
501 cv.wait()
502 get_an_available_item()
503 cv.release()
504
505 # Produce one item
506 cv.acquire()
507 make_an_item_available()
508 cv.notify()
509 cv.release()
510
Georg Brandlf9926402008-06-13 06:32:25 +0000511To choose between :meth:`notify` and :meth:`notify_all`, consider whether one
Georg Brandl116aa622007-08-15 14:28:22 +0000512state change can be interesting for only one or several waiting threads. E.g.
513in a typical producer-consumer situation, adding one item to the buffer only
514needs to wake up one consumer thread.
515
516
Georg Brandlb044b2a2009-09-16 16:05:59 +0000517.. class:: Condition(lock=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Georg Brandlc5605df2009-08-13 08:26:44 +0000519 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
520 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
521 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000522
Georg Brandlc5605df2009-08-13 08:26:44 +0000523 .. method:: acquire(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000524
Georg Brandlc5605df2009-08-13 08:26:44 +0000525 Acquire the underlying lock. This method calls the corresponding method on
526 the underlying lock; the return value is whatever that method returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandlc5605df2009-08-13 08:26:44 +0000528 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandlc5605df2009-08-13 08:26:44 +0000530 Release the underlying lock. This method calls the corresponding method on
531 the underlying lock; there is no return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000532
Georg Brandlb044b2a2009-09-16 16:05:59 +0000533 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Georg Brandlc5605df2009-08-13 08:26:44 +0000535 Wait until notified or until a timeout occurs. If the calling thread has
536 not acquired the lock when this method is called, a :exc:`RuntimeError` is
537 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Georg Brandlc5605df2009-08-13 08:26:44 +0000539 This method releases the underlying lock, and then blocks until it is
540 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
541 condition variable in another thread, or until the optional timeout
542 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
Georg Brandlc5605df2009-08-13 08:26:44 +0000544 When the *timeout* argument is present and not ``None``, it should be a
545 floating point number specifying a timeout for the operation in seconds
546 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000547
Georg Brandlc5605df2009-08-13 08:26:44 +0000548 When the underlying lock is an :class:`RLock`, it is not released using
549 its :meth:`release` method, since this may not actually unlock the lock
550 when it was acquired multiple times recursively. Instead, an internal
551 interface of the :class:`RLock` class is used, which really unlocks it
552 even when it has been recursively acquired several times. Another internal
553 interface is then used to restore the recursion level when the lock is
554 reacquired.
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Georg Brandlc5605df2009-08-13 08:26:44 +0000556 .. method:: notify()
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Georg Brandlc5605df2009-08-13 08:26:44 +0000558 Wake up a thread waiting on this condition, if any. If the calling thread
559 has not acquired the lock when this method is called, a
560 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
Georg Brandlc5605df2009-08-13 08:26:44 +0000562 This method wakes up one of the threads waiting for the condition
563 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Georg Brandlc5605df2009-08-13 08:26:44 +0000565 The current implementation wakes up exactly one thread, if any are
566 waiting. However, it's not safe to rely on this behavior. A future,
567 optimized implementation may occasionally wake up more than one thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
Georg Brandlc5605df2009-08-13 08:26:44 +0000569 Note: the awakened thread does not actually return from its :meth:`wait`
570 call until it can reacquire the lock. Since :meth:`notify` does not
571 release the lock, its caller should.
Georg Brandl116aa622007-08-15 14:28:22 +0000572
Georg Brandlc5605df2009-08-13 08:26:44 +0000573 .. method:: notify_all()
Georg Brandl116aa622007-08-15 14:28:22 +0000574
Georg Brandlc5605df2009-08-13 08:26:44 +0000575 Wake up all threads waiting on this condition. This method acts like
576 :meth:`notify`, but wakes up all waiting threads instead of one. If the
577 calling thread has not acquired the lock when this method is called, a
578 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580
581.. _semaphore-objects:
582
583Semaphore Objects
584-----------------
585
586This is one of the oldest synchronization primitives in the history of computer
587science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
588used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
589
590A semaphore manages an internal counter which is decremented by each
591:meth:`acquire` call and incremented by each :meth:`release` call. The counter
592can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
593waiting until some other thread calls :meth:`release`.
594
595
Georg Brandlb044b2a2009-09-16 16:05:59 +0000596.. class:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000597
598 The optional argument gives the initial *value* for the internal counter; it
599 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
600 raised.
601
Georg Brandlb044b2a2009-09-16 16:05:59 +0000602 .. method:: acquire(blocking=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000603
Georg Brandlc5605df2009-08-13 08:26:44 +0000604 Acquire a semaphore.
Georg Brandl116aa622007-08-15 14:28:22 +0000605
Georg Brandlc5605df2009-08-13 08:26:44 +0000606 When invoked without arguments: if the internal counter is larger than
607 zero on entry, decrement it by one and return immediately. If it is zero
608 on entry, block, waiting until some other thread has called
609 :meth:`release` to make it larger than zero. This is done with proper
610 interlocking so that if multiple :meth:`acquire` calls are blocked,
611 :meth:`release` will wake exactly one of them up. The implementation may
612 pick one at random, so the order in which blocked threads are awakened
613 should not be relied on. There is no return value in this case.
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Georg Brandlc5605df2009-08-13 08:26:44 +0000615 When invoked with *blocking* set to true, do the same thing as when called
616 without arguments, and return true.
Georg Brandl116aa622007-08-15 14:28:22 +0000617
Georg Brandlc5605df2009-08-13 08:26:44 +0000618 When invoked with *blocking* set to false, do not block. If a call
619 without an argument would block, return false immediately; otherwise, do
620 the same thing as when called without arguments, and return true.
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Georg Brandlc5605df2009-08-13 08:26:44 +0000622 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Georg Brandlc5605df2009-08-13 08:26:44 +0000624 Release a semaphore, incrementing the internal counter by one. When it
625 was zero on entry and another thread is waiting for it to become larger
626 than zero again, wake up that thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628
629.. _semaphore-examples:
630
631:class:`Semaphore` Example
632^^^^^^^^^^^^^^^^^^^^^^^^^^
633
634Semaphores are often used to guard resources with limited capacity, for example,
Georg Brandlec78b8b2011-01-09 07:59:02 +0000635a database server. In any situation where the size of the resource is fixed,
636you should use a bounded semaphore. Before spawning any worker threads, your
637main thread would initialize the semaphore::
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639 maxconnections = 5
640 ...
641 pool_sema = BoundedSemaphore(value=maxconnections)
642
643Once spawned, worker threads call the semaphore's acquire and release methods
644when they need to connect to the server::
645
646 pool_sema.acquire()
647 conn = connectdb()
648 ... use connection ...
649 conn.close()
650 pool_sema.release()
651
652The use of a bounded semaphore reduces the chance that a programming error which
653causes the semaphore to be released more than it's acquired will go undetected.
654
655
656.. _event-objects:
657
658Event Objects
659-------------
660
661This is one of the simplest mechanisms for communication between threads: one
662thread signals an event and other threads wait for it.
663
664An event object manages an internal flag that can be set to true with the
Georg Brandlc5605df2009-08-13 08:26:44 +0000665:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl116aa622007-08-15 14:28:22 +0000666:meth:`wait` method blocks until the flag is true.
667
668
669.. class:: Event()
670
671 The internal flag is initially false.
672
Georg Brandlc5605df2009-08-13 08:26:44 +0000673 .. method:: is_set()
Georg Brandl116aa622007-08-15 14:28:22 +0000674
Georg Brandlc5605df2009-08-13 08:26:44 +0000675 Return true if and only if the internal flag is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000676
Georg Brandlc5605df2009-08-13 08:26:44 +0000677 .. method:: set()
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Georg Brandlc5605df2009-08-13 08:26:44 +0000679 Set the internal flag to true. All threads waiting for it to become true
680 are awakened. Threads that call :meth:`wait` once the flag is true will
681 not block at all.
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Georg Brandlc5605df2009-08-13 08:26:44 +0000683 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Georg Brandlc5605df2009-08-13 08:26:44 +0000685 Reset the internal flag to false. Subsequently, threads calling
686 :meth:`wait` will block until :meth:`.set` is called to set the internal
687 flag to true again.
Georg Brandl116aa622007-08-15 14:28:22 +0000688
Georg Brandlb044b2a2009-09-16 16:05:59 +0000689 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000690
Georg Brandlc5605df2009-08-13 08:26:44 +0000691 Block until the internal flag is true. If the internal flag is true on
692 entry, return immediately. Otherwise, block until another thread calls
693 :meth:`set` to set the flag to true, or until the optional timeout occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Georg Brandlc5605df2009-08-13 08:26:44 +0000695 When the timeout argument is present and not ``None``, it should be a
696 floating point number specifying a timeout for the operation in seconds
697 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Georg Brandlc5605df2009-08-13 08:26:44 +0000699 This method returns the internal flag on exit, so it will always return
700 ``True`` except if a timeout is given and the operation times out.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Georg Brandlc5605df2009-08-13 08:26:44 +0000702 .. versionchanged:: 3.1
703 Previously, the method always returned ``None``.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000704
Georg Brandl116aa622007-08-15 14:28:22 +0000705
Georg Brandl116aa622007-08-15 14:28:22 +0000706.. _timer-objects:
707
708Timer Objects
709-------------
710
711This class represents an action that should be run only after a certain amount
712of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
713and as such also functions as an example of creating custom threads.
714
715Timers are started, as with threads, by calling their :meth:`start` method. The
716timer can be stopped (before its action has begun) by calling the :meth:`cancel`
717method. The interval the timer will wait before executing its action may not be
718exactly the same as the interval specified by the user.
719
720For example::
721
722 def hello():
Collin Winterc79461b2007-09-01 23:34:30 +0000723 print("hello, world")
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725 t = Timer(30.0, hello)
726 t.start() # after 30 seconds, "hello, world" will be printed
727
728
729.. class:: Timer(interval, function, args=[], kwargs={})
730
731 Create a timer that will run *function* with arguments *args* and keyword
732 arguments *kwargs*, after *interval* seconds have passed.
733
Georg Brandlc5605df2009-08-13 08:26:44 +0000734 .. method:: cancel()
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Georg Brandlc5605df2009-08-13 08:26:44 +0000736 Stop the timer, and cancel the execution of the timer's action. This will
737 only work if the timer is still in its waiting stage.
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739
740.. _with-locks:
741
742Using locks, conditions, and semaphores in the :keyword:`with` statement
743------------------------------------------------------------------------
744
745All of the objects provided by this module that have :meth:`acquire` and
746:meth:`release` methods can be used as context managers for a :keyword:`with`
747statement. The :meth:`acquire` method will be called when the block is entered,
748and :meth:`release` will be called when the block is exited.
749
750Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
751:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
752:keyword:`with` statement context managers. For example::
753
Georg Brandl116aa622007-08-15 14:28:22 +0000754 import threading
755
756 some_rlock = threading.RLock()
757
758 with some_rlock:
Collin Winterc79461b2007-09-01 23:34:30 +0000759 print("some_rlock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000761
762.. _threaded-imports:
763
764Importing in threaded code
765--------------------------
766
Georg Brandld62ecbf2010-11-26 08:52:36 +0000767While the import machinery is thread-safe, there are two key restrictions on
768threaded imports due to inherent limitations in the way that thread-safety is
769provided:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000770
771* Firstly, other than in the main module, an import should not have the
772 side effect of spawning a new thread and then waiting for that thread in
773 any way. Failing to abide by this restriction can lead to a deadlock if
774 the spawned thread directly or indirectly attempts to import a module.
775* Secondly, all import attempts must be completed before the interpreter
776 starts shutting itself down. This can be most easily achieved by only
777 performing imports from non-daemon threads created through the threading
778 module. Daemon threads and threads created directly with the thread
779 module will require some other form of synchronization to ensure they do
780 not attempt imports after system shutdown has commenced. Failure to
781 abide by this restriction will lead to intermittent exceptions and
782 crashes during interpreter shutdown (as the late imports attempt to
783 access machinery which is no longer in a valid state).