blob: 3419e65c0e1cf99a7d31ef2a4390917375d4bf4c [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
Georg Brandl179249f2010-08-26 14:30:15 +000036 See :ref:`condition-objects`.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038
Benjamin Peterson672b8032008-06-11 19:14:14 +000039.. function:: current_thread()
Georg Brandl116aa622007-08-15 14:28:22 +000040
41 Return the current :class:`Thread` object, corresponding to the caller's thread
42 of control. If the caller's thread of control was not created through the
43 :mod:`threading` module, a dummy thread object with limited functionality is
44 returned.
45
46
47.. function:: enumerate()
48
Benjamin Peterson672b8032008-06-11 19:14:14 +000049 Return a list of all :class:`Thread` objects currently alive. The list
50 includes daemonic threads, dummy thread objects created by
51 :func:`current_thread`, and the main thread. It excludes terminated threads
52 and threads that have not yet been started.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54
55.. function:: Event()
56 :noindex:
57
58 A factory function that returns a new event object. An event manages a flag
Georg Brandl502d9a52009-07-26 15:02:41 +000059 that can be set to true with the :meth:`~Event.set` method and reset to false
60 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
61 is true.
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandl179249f2010-08-26 14:30:15 +000063 See :ref:`event-objects`.
64
Georg Brandl116aa622007-08-15 14:28:22 +000065
66.. class:: local
67
68 A class that represents thread-local data. Thread-local data are data whose
69 values are thread specific. To manage thread-local data, just create an
70 instance of :class:`local` (or a subclass) and store attributes on it::
71
72 mydata = threading.local()
73 mydata.x = 1
74
75 The instance's values will be different for separate threads.
76
77 For more details and extensive examples, see the documentation string of the
78 :mod:`_threading_local` module.
79
Georg Brandl116aa622007-08-15 14:28:22 +000080
81.. function:: Lock()
82
83 A factory function that returns a new primitive lock object. Once a thread has
84 acquired it, subsequent attempts to acquire it block, until it is released; any
85 thread may release it.
86
Georg Brandl179249f2010-08-26 14:30:15 +000087 See :ref:`lock-objects`.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089
90.. function:: RLock()
91
92 A factory function that returns a new reentrant lock object. A reentrant lock
93 must be released by the thread that acquired it. Once a thread has acquired a
94 reentrant lock, the same thread may acquire it again without blocking; the
95 thread must release it once for each time it has acquired it.
96
Georg Brandl179249f2010-08-26 14:30:15 +000097 See :ref:`rlock-objects`.
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
Georg Brandl7f01a132009-09-16 15:58:14 +0000100.. function:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000101 :noindex:
102
103 A factory function that returns a new semaphore object. A semaphore manages a
104 counter representing the number of :meth:`release` calls minus the number of
105 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
106 if necessary until it can return without making the counter negative. If not
107 given, *value* defaults to 1.
108
Georg Brandl179249f2010-08-26 14:30:15 +0000109 See :ref:`semaphore-objects`.
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Georg Brandl7f01a132009-09-16 15:58:14 +0000112.. function:: BoundedSemaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114 A factory function that returns a new bounded semaphore object. A bounded
115 semaphore checks to make sure its current value doesn't exceed its initial
116 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
117 are used to guard resources with limited capacity. If the semaphore is released
118 too many times it's a sign of a bug. If not given, *value* defaults to 1.
119
120
121.. class:: Thread
Georg Brandl179249f2010-08-26 14:30:15 +0000122 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 A class that represents a thread of control. This class can be safely
125 subclassed in a limited fashion.
126
Georg Brandl179249f2010-08-26 14:30:15 +0000127 See :ref:`thread-objects`.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. class:: Timer
Georg Brandl179249f2010-08-26 14:30:15 +0000131 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 A thread that executes a function after a specified interval has passed.
134
Georg Brandl179249f2010-08-26 14:30:15 +0000135 See :ref:`timer-objects`.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. function:: settrace(func)
139
140 .. index:: single: trace function
141
142 Set a trace function for all threads started from the :mod:`threading` module.
143 The *func* will be passed to :func:`sys.settrace` for each thread, before its
144 :meth:`run` method is called.
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147.. function:: setprofile(func)
148
149 .. index:: single: profile function
150
151 Set a profile function for all threads started from the :mod:`threading` module.
152 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
153 :meth:`run` method is called.
154
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156.. function:: stack_size([size])
157
158 Return the thread stack size used when creating new threads. The optional
159 *size* argument specifies the stack size to be used for subsequently created
160 threads, and must be 0 (use platform or configured default) or a positive
161 integer value of at least 32,768 (32kB). If changing the thread stack size is
162 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
163 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
164 is currently the minimum supported stack size value to guarantee sufficient
165 stack space for the interpreter itself. Note that some platforms may have
166 particular restrictions on values for the stack size, such as requiring a
167 minimum stack size > 32kB or requiring allocation in multiples of the system
168 memory page size - platform documentation should be referred to for more
169 information (4kB pages are common; using multiples of 4096 for the stack size is
170 the suggested approach in the absence of more specific information).
171 Availability: Windows, systems with POSIX threads.
172
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000174This module also defines the following constant:
175
176.. data:: TIMEOUT_MAX
177
178 The maximum value allowed for the *timeout* parameter of blocking functions
179 (:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.).
Georg Brandl6faee4e2010-09-21 14:48:28 +0000180 Specifying a timeout greater than this value will raise an
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000181 :exc:`OverflowError`.
182
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000183 .. versionadded:: 3.2
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000184
Georg Brandl67b21b72010-08-17 15:07:14 +0000185
Georg Brandl116aa622007-08-15 14:28:22 +0000186Detailed interfaces for the objects are documented below.
187
188The design of this module is loosely based on Java's threading model. However,
189where Java makes locks and condition variables basic behavior of every object,
190they are separate objects in Python. Python's :class:`Thread` class supports a
191subset of the behavior of Java's Thread class; currently, there are no
192priorities, no thread groups, and threads cannot be destroyed, stopped,
193suspended, resumed, or interrupted. The static methods of Java's Thread class,
194when implemented, are mapped to module-level functions.
195
196All of the methods described below are executed atomically.
197
198
Georg Brandla971c652008-11-07 09:39:56 +0000199.. _thread-objects:
200
201Thread Objects
202--------------
203
204This class represents an activity that is run in a separate thread of control.
205There are two ways to specify the activity: by passing a callable object to the
206constructor, or by overriding the :meth:`run` method in a subclass. No other
207methods (except for the constructor) should be overridden in a subclass. In
208other words, *only* override the :meth:`__init__` and :meth:`run` methods of
209this class.
210
211Once a thread object is created, its activity must be started by calling the
212thread's :meth:`start` method. This invokes the :meth:`run` method in a
213separate thread of control.
214
215Once the thread's activity is started, the thread is considered 'alive'. It
216stops being alive when its :meth:`run` method terminates -- either normally, or
217by raising an unhandled exception. The :meth:`is_alive` method tests whether the
218thread is alive.
219
220Other threads can call a thread's :meth:`join` method. This blocks the calling
221thread until the thread whose :meth:`join` method is called is terminated.
222
223A thread has a name. The name can be passed to the constructor, and read or
224changed through the :attr:`name` attribute.
225
226A thread can be flagged as a "daemon thread". The significance of this flag is
227that the entire Python program exits when only daemon threads are left. The
228initial value is inherited from the creating thread. The flag can be set
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000229through the :attr:`daemon` property.
Georg Brandla971c652008-11-07 09:39:56 +0000230
231There is a "main thread" object; this corresponds to the initial thread of
232control in the Python program. It is not a daemon thread.
233
234There is the possibility that "dummy thread objects" are created. These are
235thread objects corresponding to "alien threads", which are threads of control
236started outside the threading module, such as directly from C code. Dummy
237thread objects have limited functionality; they are always considered alive and
238daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
239impossible to detect the termination of alien threads.
240
241
242.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
243
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000244 This constructor should always be called with keyword arguments. Arguments
245 are:
Georg Brandla971c652008-11-07 09:39:56 +0000246
247 *group* should be ``None``; reserved for future extension when a
248 :class:`ThreadGroup` class is implemented.
249
250 *target* is the callable object to be invoked by the :meth:`run` method.
251 Defaults to ``None``, meaning nothing is called.
252
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000253 *name* is the thread name. By default, a unique name is constructed of the
254 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandla971c652008-11-07 09:39:56 +0000255
256 *args* is the argument tuple for the target invocation. Defaults to ``()``.
257
258 *kwargs* is a dictionary of keyword arguments for the target invocation.
259 Defaults to ``{}``.
260
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000261 If the subclass overrides the constructor, it must make sure to invoke the
262 base class constructor (``Thread.__init__()``) before doing anything else to
263 the thread.
Georg Brandla971c652008-11-07 09:39:56 +0000264
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000265 .. method:: start()
Georg Brandla971c652008-11-07 09:39:56 +0000266
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000267 Start the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000268
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000269 It must be called at most once per thread object. It arranges for the
270 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandla971c652008-11-07 09:39:56 +0000271
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000272 This method will raise a :exc:`RuntimeException` if called more than once
273 on the same thread object.
Georg Brandla971c652008-11-07 09:39:56 +0000274
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000275 .. method:: run()
Georg Brandla971c652008-11-07 09:39:56 +0000276
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000277 Method representing the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000278
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000279 You may override this method in a subclass. The standard :meth:`run`
280 method invokes the callable object passed to the object's constructor as
281 the *target* argument, if any, with sequential and keyword arguments taken
282 from the *args* and *kwargs* arguments, respectively.
Georg Brandla971c652008-11-07 09:39:56 +0000283
Georg Brandl7f01a132009-09-16 15:58:14 +0000284 .. method:: join(timeout=None)
Georg Brandla971c652008-11-07 09:39:56 +0000285
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000286 Wait until the thread terminates. This blocks the calling thread until the
287 thread whose :meth:`join` method is called terminates -- either normally
288 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandla971c652008-11-07 09:39:56 +0000289
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000290 When the *timeout* argument is present and not ``None``, it should be a
291 floating point number specifying a timeout for the operation in seconds
292 (or fractions thereof). As :meth:`join` always returns ``None``, you must
293 call :meth:`is_alive` after :meth:`join` to decide whether a timeout
294 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandla971c652008-11-07 09:39:56 +0000295
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000296 When the *timeout* argument is not present or ``None``, the operation will
297 block until the thread terminates.
Georg Brandla971c652008-11-07 09:39:56 +0000298
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000299 A thread can be :meth:`join`\ ed many times.
Georg Brandla971c652008-11-07 09:39:56 +0000300
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000301 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
302 the current thread as that would cause a deadlock. It is also an error to
303 :meth:`join` a thread before it has been started and attempts to do so
304 raises the same exception.
Georg Brandla971c652008-11-07 09:39:56 +0000305
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000306 .. attribute:: name
Georg Brandla971c652008-11-07 09:39:56 +0000307
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000308 A string used for identification purposes only. It has no semantics.
309 Multiple threads may be given the same name. The initial name is set by
310 the constructor.
Georg Brandla971c652008-11-07 09:39:56 +0000311
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000312 .. method:: getName()
313 setName()
Georg Brandla971c652008-11-07 09:39:56 +0000314
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000315 Old getter/setter API for :attr:`~Thread.name`; use it directly as a
316 property instead.
Georg Brandla971c652008-11-07 09:39:56 +0000317
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000318 .. attribute:: ident
Georg Brandla971c652008-11-07 09:39:56 +0000319
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000320 The 'thread identifier' of this thread or ``None`` if the thread has not
321 been started. This is a nonzero integer. See the
322 :func:`thread.get_ident()` function. Thread identifiers may be recycled
323 when a thread exits and another thread is created. The identifier is
324 available even after the thread has exited.
Georg Brandla971c652008-11-07 09:39:56 +0000325
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000326 .. method:: is_alive()
Georg Brandla971c652008-11-07 09:39:56 +0000327
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000328 Return whether the thread is alive.
Georg Brandl770b0be2009-01-02 20:10:05 +0000329
Brett Cannona57edd02010-07-23 12:26:35 +0000330 This method returns ``True`` just before the :meth:`run` method starts
331 until just after the :meth:`run` method terminates. The module function
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000332 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl770b0be2009-01-02 20:10:05 +0000333
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000334 .. attribute:: daemon
Georg Brandl770b0be2009-01-02 20:10:05 +0000335
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000336 A boolean value indicating whether this thread is a daemon thread (True)
337 or not (False). This must be set before :meth:`start` is called,
338 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
339 from the creating thread; the main thread is not a daemon thread and
340 therefore all threads created in the main thread default to :attr:`daemon`
341 = ``False``.
Georg Brandla971c652008-11-07 09:39:56 +0000342
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000343 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandla971c652008-11-07 09:39:56 +0000344
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000345 .. method:: isDaemon()
346 setDaemon()
Georg Brandla971c652008-11-07 09:39:56 +0000347
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000348 Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
349 property instead.
Georg Brandl770b0be2009-01-02 20:10:05 +0000350
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352.. _lock-objects:
353
354Lock Objects
355------------
356
357A primitive lock is a synchronization primitive that is not owned by a
358particular thread when locked. In Python, it is currently the lowest level
Georg Brandl2067bfd2008-05-25 13:05:15 +0000359synchronization primitive available, implemented directly by the :mod:`_thread`
Georg Brandl116aa622007-08-15 14:28:22 +0000360extension module.
361
362A primitive lock is in one of two states, "locked" or "unlocked". It is created
363in the unlocked state. It has two basic methods, :meth:`acquire` and
364:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
365to locked and returns immediately. When the state is locked, :meth:`acquire`
366blocks until a call to :meth:`release` in another thread changes it to unlocked,
367then the :meth:`acquire` call resets it to locked and returns. The
368:meth:`release` method should only be called in the locked state; it changes the
369state to unlocked and returns immediately. If an attempt is made to release an
370unlocked lock, a :exc:`RuntimeError` will be raised.
371
372When more than one thread is blocked in :meth:`acquire` waiting for the state to
373turn to unlocked, only one thread proceeds when a :meth:`release` call resets
374the state to unlocked; which one of the waiting threads proceeds is not defined,
375and may vary across implementations.
376
377All methods are executed atomically.
378
379
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000380.. method:: Lock.acquire(blocking=True, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382 Acquire a lock, blocking or non-blocking.
383
384 When invoked without arguments, block until the lock is unlocked, then set it to
385 locked, and return true.
386
387 When invoked with the *blocking* argument set to true, do the same thing as when
388 called without arguments, and return true.
389
390 When invoked with the *blocking* argument set to false, do not block. If a call
391 without an argument would block, return false immediately; otherwise, do the
392 same thing as when called without arguments, and return true.
393
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000394 When invoked with the floating-point *timeout* argument set to a positive
395 value, block for at most the number of seconds specified by *timeout*
396 and as long as the lock cannot be acquired. A negative *timeout* argument
397 specifies an unbounded wait. It is forbidden to specify a *timeout*
398 when *blocking* is false.
399
400 The return value is ``True`` if the lock is acquired successfully,
401 ``False`` if not (for example if the *timeout* expired).
402
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000403 .. versionchanged:: 3.2
404 The *timeout* parameter is new.
Georg Brandl116aa622007-08-15 14:28:22 +0000405
Georg Brandl67b21b72010-08-17 15:07:14 +0000406
Georg Brandl116aa622007-08-15 14:28:22 +0000407.. method:: Lock.release()
408
409 Release a lock.
410
411 When the lock is locked, reset it to unlocked, and return. If any other threads
412 are blocked waiting for the lock to become unlocked, allow exactly one of them
413 to proceed.
414
415 Do not call this method when the lock is unlocked.
416
417 There is no return value.
418
419
420.. _rlock-objects:
421
422RLock Objects
423-------------
424
425A reentrant lock is a synchronization primitive that may be acquired multiple
426times by the same thread. Internally, it uses the concepts of "owning thread"
427and "recursion level" in addition to the locked/unlocked state used by primitive
428locks. In the locked state, some thread owns the lock; in the unlocked state,
429no thread owns it.
430
431To lock the lock, a thread calls its :meth:`acquire` method; this returns once
432the thread owns the lock. To unlock the lock, a thread calls its
433:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
434nested; only the final :meth:`release` (the :meth:`release` of the outermost
435pair) resets the lock to unlocked and allows another thread blocked in
436:meth:`acquire` to proceed.
437
438
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000439.. method:: RLock.acquire(blocking=True, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441 Acquire a lock, blocking or non-blocking.
442
443 When invoked without arguments: if this thread already owns the lock, increment
444 the recursion level by one, and return immediately. Otherwise, if another
445 thread owns the lock, block until the lock is unlocked. Once the lock is
446 unlocked (not owned by any thread), then grab ownership, set the recursion level
447 to one, and return. If more than one thread is blocked waiting until the lock
448 is unlocked, only one at a time will be able to grab ownership of the lock.
449 There is no return value in this case.
450
451 When invoked with the *blocking* argument set to true, do the same thing as when
452 called without arguments, and return true.
453
454 When invoked with the *blocking* argument set to false, do not block. If a call
455 without an argument would block, return false immediately; otherwise, do the
456 same thing as when called without arguments, and return true.
457
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000458 When invoked with the floating-point *timeout* argument set to a positive
459 value, block for at most the number of seconds specified by *timeout*
460 and as long as the lock cannot be acquired. Return true if the lock has
461 been acquired, false if the timeout has elapsed.
462
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000463 .. versionchanged:: 3.2
464 The *timeout* parameter is new.
465
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467.. method:: RLock.release()
468
469 Release a lock, decrementing the recursion level. If after the decrement it is
470 zero, reset the lock to unlocked (not owned by any thread), and if any other
471 threads are blocked waiting for the lock to become unlocked, allow exactly one
472 of them to proceed. If after the decrement the recursion level is still
473 nonzero, the lock remains locked and owned by the calling thread.
474
475 Only call this method when the calling thread owns the lock. A
476 :exc:`RuntimeError` is raised if this method is called when the lock is
477 unlocked.
478
479 There is no return value.
480
481
482.. _condition-objects:
483
484Condition Objects
485-----------------
486
487A condition variable is always associated with some kind of lock; this can be
488passed in or one will be created by default. (Passing one in is useful when
489several condition variables must share the same lock.)
490
491A condition variable has :meth:`acquire` and :meth:`release` methods that call
492the corresponding methods of the associated lock. It also has a :meth:`wait`
Georg Brandlf9926402008-06-13 06:32:25 +0000493method, and :meth:`notify` and :meth:`notify_all` methods. These three must only
Georg Brandl116aa622007-08-15 14:28:22 +0000494be called when the calling thread has acquired the lock, otherwise a
495:exc:`RuntimeError` is raised.
496
497The :meth:`wait` method releases the lock, and then blocks until it is awakened
Georg Brandlf9926402008-06-13 06:32:25 +0000498by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
Georg Brandl116aa622007-08-15 14:28:22 +0000499another thread. Once awakened, it re-acquires the lock and returns. It is also
500possible to specify a timeout.
501
502The :meth:`notify` method wakes up one of the threads waiting for the condition
Georg Brandlf9926402008-06-13 06:32:25 +0000503variable, if any are waiting. The :meth:`notify_all` method wakes up all threads
Georg Brandl116aa622007-08-15 14:28:22 +0000504waiting for the condition variable.
505
Georg Brandlf9926402008-06-13 06:32:25 +0000506Note: the :meth:`notify` and :meth:`notify_all` methods don't release the lock;
Georg Brandl116aa622007-08-15 14:28:22 +0000507this means that the thread or threads awakened will not return from their
508:meth:`wait` call immediately, but only when the thread that called
Georg Brandlf9926402008-06-13 06:32:25 +0000509:meth:`notify` or :meth:`notify_all` finally relinquishes ownership of the lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511Tip: the typical programming style using condition variables uses the lock to
512synchronize access to some shared state; threads that are interested in a
513particular change of state call :meth:`wait` repeatedly until they see the
514desired state, while threads that modify the state call :meth:`notify` or
Georg Brandlf9926402008-06-13 06:32:25 +0000515:meth:`notify_all` when they change the state in such a way that it could
Georg Brandl116aa622007-08-15 14:28:22 +0000516possibly be a desired state for one of the waiters. For example, the following
517code is a generic producer-consumer situation with unlimited buffer capacity::
518
519 # Consume one item
520 cv.acquire()
521 while not an_item_is_available():
522 cv.wait()
523 get_an_available_item()
524 cv.release()
525
526 # Produce one item
527 cv.acquire()
528 make_an_item_available()
529 cv.notify()
530 cv.release()
531
Georg Brandlf9926402008-06-13 06:32:25 +0000532To choose between :meth:`notify` and :meth:`notify_all`, consider whether one
Georg Brandl116aa622007-08-15 14:28:22 +0000533state change can be interesting for only one or several waiting threads. E.g.
534in a typical producer-consumer situation, adding one item to the buffer only
535needs to wake up one consumer thread.
536
537
Georg Brandl7f01a132009-09-16 15:58:14 +0000538.. class:: Condition(lock=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000539
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000540 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
541 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
542 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000544 .. method:: acquire(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000545
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000546 Acquire the underlying lock. This method calls the corresponding method on
547 the underlying lock; the return value is whatever that method returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000548
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000549 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000551 Release the underlying lock. This method calls the corresponding method on
552 the underlying lock; there is no return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Georg Brandl7f01a132009-09-16 15:58:14 +0000554 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000556 Wait until notified or until a timeout occurs. If the calling thread has
557 not acquired the lock when this method is called, a :exc:`RuntimeError` is
558 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000560 This method releases the underlying lock, and then blocks until it is
561 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
562 condition variable in another thread, or until the optional timeout
563 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000565 When the *timeout* argument is present and not ``None``, it should be a
566 floating point number specifying a timeout for the operation in seconds
567 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000568
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000569 When the underlying lock is an :class:`RLock`, it is not released using
570 its :meth:`release` method, since this may not actually unlock the lock
571 when it was acquired multiple times recursively. Instead, an internal
572 interface of the :class:`RLock` class is used, which really unlocks it
573 even when it has been recursively acquired several times. Another internal
574 interface is then used to restore the recursion level when the lock is
575 reacquired.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000577 .. method:: notify()
Georg Brandl116aa622007-08-15 14:28:22 +0000578
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000579 Wake up a thread waiting on this condition, if any. If the calling thread
580 has not acquired the lock when this method is called, a
581 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000582
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000583 This method wakes up one of the threads waiting for the condition
584 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000586 The current implementation wakes up exactly one thread, if any are
587 waiting. However, it's not safe to rely on this behavior. A future,
588 optimized implementation may occasionally wake up more than one thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000590 Note: the awakened thread does not actually return from its :meth:`wait`
591 call until it can reacquire the lock. Since :meth:`notify` does not
592 release the lock, its caller should.
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000594 .. method:: notify_all()
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000596 Wake up all threads waiting on this condition. This method acts like
597 :meth:`notify`, but wakes up all waiting threads instead of one. If the
598 calling thread has not acquired the lock when this method is called, a
599 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601
602.. _semaphore-objects:
603
604Semaphore Objects
605-----------------
606
607This is one of the oldest synchronization primitives in the history of computer
608science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
609used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
610
611A semaphore manages an internal counter which is decremented by each
612:meth:`acquire` call and incremented by each :meth:`release` call. The counter
613can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
614waiting until some other thread calls :meth:`release`.
615
616
Georg Brandl7f01a132009-09-16 15:58:14 +0000617.. class:: Semaphore(value=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619 The optional argument gives the initial *value* for the internal counter; it
620 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
621 raised.
622
Antoine Pitrou0454af92010-04-17 23:51:58 +0000623 .. method:: acquire(blocking=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000624
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000625 Acquire a semaphore.
Georg Brandl116aa622007-08-15 14:28:22 +0000626
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000627 When invoked without arguments: if the internal counter is larger than
628 zero on entry, decrement it by one and return immediately. If it is zero
629 on entry, block, waiting until some other thread has called
630 :meth:`release` to make it larger than zero. This is done with proper
631 interlocking so that if multiple :meth:`acquire` calls are blocked,
632 :meth:`release` will wake exactly one of them up. The implementation may
633 pick one at random, so the order in which blocked threads are awakened
Antoine Pitrou0454af92010-04-17 23:51:58 +0000634 should not be relied on. Returns true (or blocks indefinitely).
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000636 When invoked with *blocking* set to false, do not block. If a call
Antoine Pitrou0454af92010-04-17 23:51:58 +0000637 without an argument would block, return false immediately; otherwise,
638 do the same thing as when called without arguments, and return true.
639
640 When invoked with a *timeout* other than None, it will block for at
641 most *timeout* seconds. If acquire does not complete successfully in
642 that interval, return false. Return true otherwise.
643
644 .. versionchanged:: 3.2
645 The *timeout* parameter is new.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000647 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000649 Release a semaphore, incrementing the internal counter by one. When it
650 was zero on entry and another thread is waiting for it to become larger
651 than zero again, wake up that thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653
654.. _semaphore-examples:
655
656:class:`Semaphore` Example
657^^^^^^^^^^^^^^^^^^^^^^^^^^
658
659Semaphores are often used to guard resources with limited capacity, for example,
660a database server. In any situation where the size of the resource size is
661fixed, you should use a bounded semaphore. Before spawning any worker threads,
662your main thread would initialize the semaphore::
663
664 maxconnections = 5
665 ...
666 pool_sema = BoundedSemaphore(value=maxconnections)
667
668Once spawned, worker threads call the semaphore's acquire and release methods
669when they need to connect to the server::
670
671 pool_sema.acquire()
672 conn = connectdb()
673 ... use connection ...
674 conn.close()
675 pool_sema.release()
676
677The use of a bounded semaphore reduces the chance that a programming error which
678causes the semaphore to be released more than it's acquired will go undetected.
679
680
681.. _event-objects:
682
683Event Objects
684-------------
685
686This is one of the simplest mechanisms for communication between threads: one
687thread signals an event and other threads wait for it.
688
689An event object manages an internal flag that can be set to true with the
Georg Brandl502d9a52009-07-26 15:02:41 +0000690:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl116aa622007-08-15 14:28:22 +0000691:meth:`wait` method blocks until the flag is true.
692
693
694.. class:: Event()
695
696 The internal flag is initially false.
697
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000698 .. method:: is_set()
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000700 Return true if and only if the internal flag is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000702 .. method:: set()
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000704 Set the internal flag to true. All threads waiting for it to become true
705 are awakened. Threads that call :meth:`wait` once the flag is true will
706 not block at all.
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000708 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000710 Reset the internal flag to false. Subsequently, threads calling
Georg Brandl502d9a52009-07-26 15:02:41 +0000711 :meth:`wait` will block until :meth:`.set` is called to set the internal
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000712 flag to true again.
Georg Brandl116aa622007-08-15 14:28:22 +0000713
Georg Brandl7f01a132009-09-16 15:58:14 +0000714 .. method:: wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000716 Block until the internal flag is true. If the internal flag is true on
717 entry, return immediately. Otherwise, block until another thread calls
718 :meth:`set` to set the flag to true, or until the optional timeout occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000720 When the timeout argument is present and not ``None``, it should be a
721 floating point number specifying a timeout for the operation in seconds
722 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000724 This method returns the internal flag on exit, so it will always return
725 ``True`` except if a timeout is given and the operation times out.
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000727 .. versionchanged:: 3.1
728 Previously, the method always returned ``None``.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000729
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Georg Brandl116aa622007-08-15 14:28:22 +0000731.. _timer-objects:
732
733Timer Objects
734-------------
735
736This class represents an action that should be run only after a certain amount
737of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
738and as such also functions as an example of creating custom threads.
739
740Timers are started, as with threads, by calling their :meth:`start` method. The
741timer can be stopped (before its action has begun) by calling the :meth:`cancel`
742method. The interval the timer will wait before executing its action may not be
743exactly the same as the interval specified by the user.
744
745For example::
746
747 def hello():
Collin Winterc79461b2007-09-01 23:34:30 +0000748 print("hello, world")
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750 t = Timer(30.0, hello)
751 t.start() # after 30 seconds, "hello, world" will be printed
752
753
754.. class:: Timer(interval, function, args=[], kwargs={})
755
756 Create a timer that will run *function* with arguments *args* and keyword
757 arguments *kwargs*, after *interval* seconds have passed.
758
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000759 .. method:: cancel()
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000761 Stop the timer, and cancel the execution of the timer's action. This will
762 only work if the timer is still in its waiting stage.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
764
765.. _with-locks:
766
767Using locks, conditions, and semaphores in the :keyword:`with` statement
768------------------------------------------------------------------------
769
770All of the objects provided by this module that have :meth:`acquire` and
771:meth:`release` methods can be used as context managers for a :keyword:`with`
772statement. The :meth:`acquire` method will be called when the block is entered,
773and :meth:`release` will be called when the block is exited.
774
775Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
776:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
777:keyword:`with` statement context managers. For example::
778
Georg Brandl116aa622007-08-15 14:28:22 +0000779 import threading
780
781 some_rlock = threading.RLock()
782
783 with some_rlock:
Collin Winterc79461b2007-09-01 23:34:30 +0000784 print("some_rlock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000786
787.. _threaded-imports:
788
789Importing in threaded code
790--------------------------
791
792While the import machinery is thread safe, there are two key
793restrictions on threaded imports due to inherent limitations in the way
794that thread safety is provided:
795
796* Firstly, other than in the main module, an import should not have the
797 side effect of spawning a new thread and then waiting for that thread in
798 any way. Failing to abide by this restriction can lead to a deadlock if
799 the spawned thread directly or indirectly attempts to import a module.
800* Secondly, all import attempts must be completed before the interpreter
801 starts shutting itself down. This can be most easily achieved by only
802 performing imports from non-daemon threads created through the threading
803 module. Daemon threads and threads created directly with the thread
804 module will require some other form of synchronization to ensure they do
805 not attempt imports after system shutdown has commenced. Failure to
806 abide by this restriction will lead to intermittent exceptions and
807 crashes during interpreter shutdown (as the late imports attempt to
808 access machinery which is no longer in a valid state).