blob: f18c959b118d3381c1d6cb78bbaaec1ce27940be [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`threading` --- Higher-level threading interface
2=====================================================
3
4.. module:: threading
5 :synopsis: Higher-level threading interface.
6
7
8This module constructs higher-level threading interfaces on top of the lower
9level :mod:`thread` module.
Georg Brandla6168f92008-05-25 07:20:14 +000010See also the :mod:`mutex` and :mod:`Queue` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
12The :mod:`dummy_threading` module is provided for situations where
13:mod:`threading` cannot be used because :mod:`thread` is missing.
14
Benjamin Petersonf4395602008-06-11 17:50:00 +000015.. note::
16
Victor Stinner8ded4772010-05-14 14:20:07 +000017 Starting with Python 2.6, this module provides :pep:`8` compliant aliases and
Benjamin Peterson973e6c22008-09-01 23:12:58 +000018 properties to replace the ``camelCase`` names that were inspired by Java's
19 threading API. This updated API is compatible with that of the
20 :mod:`multiprocessing` module. However, no schedule has been set for the
21 deprecation of the ``camelCase`` names and they remain fully supported in
22 both Python 2.x and 3.x.
Benjamin Petersonf4395602008-06-11 17:50:00 +000023
Georg Brandl2cd82a82009-03-09 14:25:07 +000024.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000025
Georg Brandl2cd82a82009-03-09 14:25:07 +000026 Starting with Python 2.5, several Thread methods raise :exc:`RuntimeError`
27 instead of :exc:`AssertionError` if called erroneously.
28
29
30This module defines the following functions and objects:
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000032.. function:: active_count()
Benjamin Petersonf4395602008-06-11 17:50:00 +000033 activeCount()
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35 Return the number of :class:`Thread` objects currently alive. The returned
Georg Brandlf4da6662009-09-19 12:04:16 +000036 count is equal to the length of the list returned by :func:`.enumerate`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000037
38
39.. function:: Condition()
40 :noindex:
41
42 A factory function that returns a new condition variable object. A condition
43 variable allows one or more threads to wait until they are notified by another
44 thread.
45
46
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000047.. function:: current_thread()
Benjamin Petersonf4395602008-06-11 17:50:00 +000048 currentThread()
Georg Brandl8ec7f652007-08-15 14:28:01 +000049
50 Return the current :class:`Thread` object, corresponding to the caller's thread
51 of control. If the caller's thread of control was not created through the
52 :mod:`threading` module, a dummy thread object with limited functionality is
53 returned.
54
55
56.. function:: enumerate()
57
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000058 Return a list of all :class:`Thread` objects currently alive. The list
59 includes daemonic threads, dummy thread objects created by
60 :func:`current_thread`, and the main thread. It excludes terminated threads
61 and threads that have not yet been started.
Georg Brandl8ec7f652007-08-15 14:28:01 +000062
63
64.. function:: Event()
65 :noindex:
66
67 A factory function that returns a new event object. An event manages a flag
Georg Brandl9fa61bb2009-07-26 14:19:57 +000068 that can be set to true with the :meth:`~Event.set` method and reset to false
69 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
70 is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +000071
72
73.. class:: local
74
75 A class that represents thread-local data. Thread-local data are data whose
76 values are thread specific. To manage thread-local data, just create an
77 instance of :class:`local` (or a subclass) and store attributes on it::
78
79 mydata = threading.local()
80 mydata.x = 1
81
82 The instance's values will be different for separate threads.
83
84 For more details and extensive examples, see the documentation string of the
85 :mod:`_threading_local` module.
86
87 .. versionadded:: 2.4
88
89
90.. function:: Lock()
91
92 A factory function that returns a new primitive lock object. Once a thread has
93 acquired it, subsequent attempts to acquire it block, until it is released; any
94 thread may release it.
95
96
97.. function:: RLock()
98
99 A factory function that returns a new reentrant lock object. A reentrant lock
100 must be released by the thread that acquired it. Once a thread has acquired a
101 reentrant lock, the same thread may acquire it again without blocking; the
102 thread must release it once for each time it has acquired it.
103
104
105.. function:: Semaphore([value])
106 :noindex:
107
108 A factory function that returns a new semaphore object. A semaphore manages a
109 counter representing the number of :meth:`release` calls minus the number of
110 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
111 if necessary until it can return without making the counter negative. If not
112 given, *value* defaults to 1.
113
114
115.. function:: BoundedSemaphore([value])
116
117 A factory function that returns a new bounded semaphore object. A bounded
118 semaphore checks to make sure its current value doesn't exceed its initial
119 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
120 are used to guard resources with limited capacity. If the semaphore is released
121 too many times it's a sign of a bug. If not given, *value* defaults to 1.
122
123
124.. class:: Thread
125
126 A class that represents a thread of control. This class can be safely
127 subclassed in a limited fashion.
128
129
130.. class:: Timer
131
132 A thread that executes a function after a specified interval has passed.
133
134
135.. function:: settrace(func)
136
137 .. index:: single: trace function
138
139 Set a trace function for all threads started from the :mod:`threading` module.
140 The *func* will be passed to :func:`sys.settrace` for each thread, before its
141 :meth:`run` method is called.
142
143 .. versionadded:: 2.3
144
145
146.. function:: setprofile(func)
147
148 .. index:: single: profile function
149
150 Set a profile function for all threads started from the :mod:`threading` module.
151 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
152 :meth:`run` method is called.
153
154 .. versionadded:: 2.3
155
156
157.. function:: stack_size([size])
158
159 Return the thread stack size used when creating new threads. The optional
160 *size* argument specifies the stack size to be used for subsequently created
161 threads, and must be 0 (use platform or configured default) or a positive
162 integer value of at least 32,768 (32kB). If changing the thread stack size is
163 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
164 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
165 is currently the minimum supported stack size value to guarantee sufficient
166 stack space for the interpreter itself. Note that some platforms may have
167 particular restrictions on values for the stack size, such as requiring a
168 minimum stack size > 32kB or requiring allocation in multiples of the system
169 memory page size - platform documentation should be referred to for more
170 information (4kB pages are common; using multiples of 4096 for the stack size is
171 the suggested approach in the absence of more specific information).
172 Availability: Windows, systems with POSIX threads.
173
174 .. versionadded:: 2.5
175
176Detailed interfaces for the objects are documented below.
177
178The design of this module is loosely based on Java's threading model. However,
179where Java makes locks and condition variables basic behavior of every object,
180they are separate objects in Python. Python's :class:`Thread` class supports a
181subset of the behavior of Java's Thread class; currently, there are no
182priorities, no thread groups, and threads cannot be destroyed, stopped,
183suspended, resumed, or interrupted. The static methods of Java's Thread class,
184when implemented, are mapped to module-level functions.
185
186All of the methods described below are executed atomically.
187
188
Georg Brandl01ba86a2008-11-06 10:20:49 +0000189.. _thread-objects:
190
191Thread Objects
192--------------
193
194This class represents an activity that is run in a separate thread of control.
195There are two ways to specify the activity: by passing a callable object to the
196constructor, or by overriding the :meth:`run` method in a subclass. No other
197methods (except for the constructor) should be overridden in a subclass. In
198other words, *only* override the :meth:`__init__` and :meth:`run` methods of
199this class.
200
201Once a thread object is created, its activity must be started by calling the
202thread's :meth:`start` method. This invokes the :meth:`run` method in a
203separate thread of control.
204
205Once the thread's activity is started, the thread is considered 'alive'. It
206stops being alive when its :meth:`run` method terminates -- either normally, or
207by raising an unhandled exception. The :meth:`is_alive` method tests whether the
208thread is alive.
209
210Other threads can call a thread's :meth:`join` method. This blocks the calling
211thread until the thread whose :meth:`join` method is called is terminated.
212
213A thread has a name. The name can be passed to the constructor, and read or
214changed through the :attr:`name` attribute.
215
216A thread can be flagged as a "daemon thread". The significance of this flag is
217that the entire Python program exits when only daemon threads are left. The
218initial value is inherited from the creating thread. The flag can be set
Georg Brandlecd2afa2009-02-05 11:40:35 +0000219through the :attr:`daemon` property.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000220
221There is a "main thread" object; this corresponds to the initial thread of
222control in the Python program. It is not a daemon thread.
223
224There is the possibility that "dummy thread objects" are created. These are
225thread objects corresponding to "alien threads", which are threads of control
226started outside the threading module, such as directly from C code. Dummy
227thread objects have limited functionality; they are always considered alive and
228daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
229impossible to detect the termination of alien threads.
230
231
232.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
233
Georg Brandl3591a8f2009-07-26 14:44:23 +0000234 This constructor should always be called with keyword arguments. Arguments
235 are:
Georg Brandl01ba86a2008-11-06 10:20:49 +0000236
237 *group* should be ``None``; reserved for future extension when a
238 :class:`ThreadGroup` class is implemented.
239
240 *target* is the callable object to be invoked by the :meth:`run` method.
241 Defaults to ``None``, meaning nothing is called.
242
Georg Brandl3591a8f2009-07-26 14:44:23 +0000243 *name* is the thread name. By default, a unique name is constructed of the
244 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000245
246 *args* is the argument tuple for the target invocation. Defaults to ``()``.
247
248 *kwargs* is a dictionary of keyword arguments for the target invocation.
249 Defaults to ``{}``.
250
Georg Brandl3591a8f2009-07-26 14:44:23 +0000251 If the subclass overrides the constructor, it must make sure to invoke the
252 base class constructor (``Thread.__init__()``) before doing anything else to
253 the thread.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000254
Georg Brandl3591a8f2009-07-26 14:44:23 +0000255 .. method:: start()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000256
Georg Brandl3591a8f2009-07-26 14:44:23 +0000257 Start the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000258
Georg Brandl3591a8f2009-07-26 14:44:23 +0000259 It must be called at most once per thread object. It arranges for the
260 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000261
Georg Brandl3591a8f2009-07-26 14:44:23 +0000262 This method will raise a :exc:`RuntimeException` if called more than once
263 on the same thread object.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000264
Georg Brandl3591a8f2009-07-26 14:44:23 +0000265 .. method:: run()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000266
Georg Brandl3591a8f2009-07-26 14:44:23 +0000267 Method representing the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000268
Georg Brandl3591a8f2009-07-26 14:44:23 +0000269 You may override this method in a subclass. The standard :meth:`run`
270 method invokes the callable object passed to the object's constructor as
271 the *target* argument, if any, with sequential and keyword arguments taken
272 from the *args* and *kwargs* arguments, respectively.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000273
Georg Brandl3591a8f2009-07-26 14:44:23 +0000274 .. method:: join([timeout])
Georg Brandl01ba86a2008-11-06 10:20:49 +0000275
Georg Brandl3591a8f2009-07-26 14:44:23 +0000276 Wait until the thread terminates. This blocks the calling thread until the
277 thread whose :meth:`join` method is called terminates -- either normally
278 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000279
Georg Brandl3591a8f2009-07-26 14:44:23 +0000280 When the *timeout* argument is present and not ``None``, it should be a
281 floating point number specifying a timeout for the operation in seconds
282 (or fractions thereof). As :meth:`join` always returns ``None``, you must
283 call :meth:`isAlive` after :meth:`join` to decide whether a timeout
284 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000285
Georg Brandl3591a8f2009-07-26 14:44:23 +0000286 When the *timeout* argument is not present or ``None``, the operation will
287 block until the thread terminates.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000288
Georg Brandl3591a8f2009-07-26 14:44:23 +0000289 A thread can be :meth:`join`\ ed many times.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000290
Georg Brandl3591a8f2009-07-26 14:44:23 +0000291 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
292 the current thread as that would cause a deadlock. It is also an error to
293 :meth:`join` a thread before it has been started and attempts to do so
294 raises the same exception.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000295
Georg Brandl3591a8f2009-07-26 14:44:23 +0000296 .. method:: getName()
297 setName()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000298
Georg Brandl3591a8f2009-07-26 14:44:23 +0000299 Old API for :attr:`~Thread.name`.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000300
Georg Brandl3591a8f2009-07-26 14:44:23 +0000301 .. attribute:: name
Georg Brandl01ba86a2008-11-06 10:20:49 +0000302
Georg Brandl3591a8f2009-07-26 14:44:23 +0000303 A string used for identification purposes only. It has no semantics.
304 Multiple threads may be given the same name. The initial name is set by
305 the constructor.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000306
Georg Brandl3591a8f2009-07-26 14:44:23 +0000307 .. attribute:: ident
Georg Brandl01ba86a2008-11-06 10:20:49 +0000308
Georg Brandl3591a8f2009-07-26 14:44:23 +0000309 The 'thread identifier' of this thread or ``None`` if the thread has not
310 been started. This is a nonzero integer. See the
311 :func:`thread.get_ident()` function. Thread identifiers may be recycled
312 when a thread exits and another thread is created. The identifier is
313 available even after the thread has exited.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000314
Georg Brandl3591a8f2009-07-26 14:44:23 +0000315 .. versionadded:: 2.6
Georg Brandl01ba86a2008-11-06 10:20:49 +0000316
Georg Brandl3591a8f2009-07-26 14:44:23 +0000317 .. method:: is_alive()
318 isAlive()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000319
Georg Brandl3591a8f2009-07-26 14:44:23 +0000320 Return whether the thread is alive.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000321
Brett Cannon11a30612010-07-23 12:30:10 +0000322 This method returns ``True`` just before the :meth:`run` method starts
323 until just after the :meth:`run` method terminates. The module function
Georg Brandlf4da6662009-09-19 12:04:16 +0000324 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000325
Georg Brandl3591a8f2009-07-26 14:44:23 +0000326 .. method:: isDaemon()
327 setDaemon()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000328
Georg Brandl3591a8f2009-07-26 14:44:23 +0000329 Old API for :attr:`~Thread.daemon`.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000330
Georg Brandl3591a8f2009-07-26 14:44:23 +0000331 .. attribute:: daemon
Georg Brandl01ba86a2008-11-06 10:20:49 +0000332
Georg Brandl3591a8f2009-07-26 14:44:23 +0000333 A boolean value indicating whether this thread is a daemon thread (True)
334 or not (False). This must be set before :meth:`start` is called,
335 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
336 from the creating thread; the main thread is not a daemon thread and
337 therefore all threads created in the main thread default to :attr:`daemon`
338 = ``False``.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000339
Georg Brandl3591a8f2009-07-26 14:44:23 +0000340 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000341
342
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343.. _lock-objects:
344
345Lock Objects
346------------
347
348A primitive lock is a synchronization primitive that is not owned by a
349particular thread when locked. In Python, it is currently the lowest level
350synchronization primitive available, implemented directly by the :mod:`thread`
351extension module.
352
353A primitive lock is in one of two states, "locked" or "unlocked". It is created
354in the unlocked state. It has two basic methods, :meth:`acquire` and
355:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
356to locked and returns immediately. When the state is locked, :meth:`acquire`
357blocks until a call to :meth:`release` in another thread changes it to unlocked,
358then the :meth:`acquire` call resets it to locked and returns. The
359:meth:`release` method should only be called in the locked state; it changes the
360state to unlocked and returns immediately. If an attempt is made to release an
361unlocked lock, a :exc:`RuntimeError` will be raised.
362
363When more than one thread is blocked in :meth:`acquire` waiting for the state to
364turn to unlocked, only one thread proceeds when a :meth:`release` call resets
365the state to unlocked; which one of the waiting threads proceeds is not defined,
366and may vary across implementations.
367
368All methods are executed atomically.
369
370
371.. method:: Lock.acquire([blocking=1])
372
373 Acquire a lock, blocking or non-blocking.
374
375 When invoked without arguments, block until the lock is unlocked, then set it to
376 locked, and return true.
377
378 When invoked with the *blocking* argument set to true, do the same thing as when
379 called without arguments, and return true.
380
381 When invoked with the *blocking* argument set to false, do not block. If a call
382 without an argument would block, return false immediately; otherwise, do the
383 same thing as when called without arguments, and return true.
384
385
386.. method:: Lock.release()
387
388 Release a lock.
389
390 When the lock is locked, reset it to unlocked, and return. If any other threads
391 are blocked waiting for the lock to become unlocked, allow exactly one of them
392 to proceed.
393
394 Do not call this method when the lock is unlocked.
395
396 There is no return value.
397
398
399.. _rlock-objects:
400
401RLock Objects
402-------------
403
404A reentrant lock is a synchronization primitive that may be acquired multiple
405times by the same thread. Internally, it uses the concepts of "owning thread"
406and "recursion level" in addition to the locked/unlocked state used by primitive
407locks. In the locked state, some thread owns the lock; in the unlocked state,
408no thread owns it.
409
410To lock the lock, a thread calls its :meth:`acquire` method; this returns once
411the thread owns the lock. To unlock the lock, a thread calls its
412:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
413nested; only the final :meth:`release` (the :meth:`release` of the outermost
414pair) resets the lock to unlocked and allows another thread blocked in
415:meth:`acquire` to proceed.
416
417
418.. method:: RLock.acquire([blocking=1])
419
420 Acquire a lock, blocking or non-blocking.
421
422 When invoked without arguments: if this thread already owns the lock, increment
423 the recursion level by one, and return immediately. Otherwise, if another
424 thread owns the lock, block until the lock is unlocked. Once the lock is
425 unlocked (not owned by any thread), then grab ownership, set the recursion level
426 to one, and return. If more than one thread is blocked waiting until the lock
427 is unlocked, only one at a time will be able to grab ownership of the lock.
428 There is no return value in this case.
429
430 When invoked with the *blocking* argument set to true, do the same thing as when
431 called without arguments, and return true.
432
433 When invoked with the *blocking* argument set to false, do not block. If a call
434 without an argument would block, return false immediately; otherwise, do the
435 same thing as when called without arguments, and return true.
436
437
438.. method:: RLock.release()
439
440 Release a lock, decrementing the recursion level. If after the decrement it is
441 zero, reset the lock to unlocked (not owned by any thread), and if any other
442 threads are blocked waiting for the lock to become unlocked, allow exactly one
443 of them to proceed. If after the decrement the recursion level is still
444 nonzero, the lock remains locked and owned by the calling thread.
445
446 Only call this method when the calling thread owns the lock. A
447 :exc:`RuntimeError` is raised if this method is called when the lock is
448 unlocked.
449
450 There is no return value.
451
452
453.. _condition-objects:
454
455Condition Objects
456-----------------
457
458A condition variable is always associated with some kind of lock; this can be
459passed in or one will be created by default. (Passing one in is useful when
460several condition variables must share the same lock.)
461
462A condition variable has :meth:`acquire` and :meth:`release` methods that call
463the corresponding methods of the associated lock. It also has a :meth:`wait`
464method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
465be called when the calling thread has acquired the lock, otherwise a
466:exc:`RuntimeError` is raised.
467
468The :meth:`wait` method releases the lock, and then blocks until it is awakened
469by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
470another thread. Once awakened, it re-acquires the lock and returns. It is also
471possible to specify a timeout.
472
473The :meth:`notify` method wakes up one of the threads waiting for the condition
474variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
475waiting for the condition variable.
476
477Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
478this means that the thread or threads awakened will not return from their
479:meth:`wait` call immediately, but only when the thread that called
480:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
481
482Tip: the typical programming style using condition variables uses the lock to
483synchronize access to some shared state; threads that are interested in a
484particular change of state call :meth:`wait` repeatedly until they see the
485desired state, while threads that modify the state call :meth:`notify` or
486:meth:`notifyAll` when they change the state in such a way that it could
487possibly be a desired state for one of the waiters. For example, the following
488code is a generic producer-consumer situation with unlimited buffer capacity::
489
490 # Consume one item
491 cv.acquire()
492 while not an_item_is_available():
493 cv.wait()
494 get_an_available_item()
495 cv.release()
496
497 # Produce one item
498 cv.acquire()
499 make_an_item_available()
500 cv.notify()
501 cv.release()
502
503To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
504state change can be interesting for only one or several waiting threads. E.g.
505in a typical producer-consumer situation, adding one item to the buffer only
506needs to wake up one consumer thread.
507
508
509.. class:: Condition([lock])
510
Georg Brandl3591a8f2009-07-26 14:44:23 +0000511 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
512 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
513 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000514
Georg Brandl3591a8f2009-07-26 14:44:23 +0000515 .. method:: acquire(*args)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000516
Georg Brandl3591a8f2009-07-26 14:44:23 +0000517 Acquire the underlying lock. This method calls the corresponding method on
518 the underlying lock; the return value is whatever that method returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000519
Georg Brandl3591a8f2009-07-26 14:44:23 +0000520 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000521
Georg Brandl3591a8f2009-07-26 14:44:23 +0000522 Release the underlying lock. This method calls the corresponding method on
523 the underlying lock; there is no return value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000524
Georg Brandl3591a8f2009-07-26 14:44:23 +0000525 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000526
Georg Brandl3591a8f2009-07-26 14:44:23 +0000527 Wait until notified or until a timeout occurs. If the calling thread has not
528 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000529
Georg Brandl3591a8f2009-07-26 14:44:23 +0000530 This method releases the underlying lock, and then blocks until it is
531 awakened by a :meth:`notify` or :meth:`notifyAll` call for the same
532 condition variable in another thread, or until the optional timeout
533 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000534
Georg Brandl3591a8f2009-07-26 14:44:23 +0000535 When the *timeout* argument is present and not ``None``, it should be a
536 floating point number specifying a timeout for the operation in seconds
537 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000538
Georg Brandl3591a8f2009-07-26 14:44:23 +0000539 When the underlying lock is an :class:`RLock`, it is not released using
540 its :meth:`release` method, since this may not actually unlock the lock
541 when it was acquired multiple times recursively. Instead, an internal
542 interface of the :class:`RLock` class is used, which really unlocks it
543 even when it has been recursively acquired several times. Another internal
544 interface is then used to restore the recursion level when the lock is
545 reacquired.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
Georg Brandl3591a8f2009-07-26 14:44:23 +0000547 .. method:: notify()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000548
Georg Brandl3591a8f2009-07-26 14:44:23 +0000549 Wake up a thread waiting on this condition, if any. If the calling thread
550 has not acquired the lock when this method is called, a
551 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000552
Georg Brandl3591a8f2009-07-26 14:44:23 +0000553 This method wakes up one of the threads waiting for the condition
554 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000555
Georg Brandl3591a8f2009-07-26 14:44:23 +0000556 The current implementation wakes up exactly one thread, if any are
557 waiting. However, it's not safe to rely on this behavior. A future,
558 optimized implementation may occasionally wake up more than one thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000559
Georg Brandl3591a8f2009-07-26 14:44:23 +0000560 Note: the awakened thread does not actually return from its :meth:`wait`
561 call until it can reacquire the lock. Since :meth:`notify` does not
562 release the lock, its caller should.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000563
Georg Brandl3591a8f2009-07-26 14:44:23 +0000564 .. method:: notify_all()
565 notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000566
Georg Brandl3591a8f2009-07-26 14:44:23 +0000567 Wake up all threads waiting on this condition. This method acts like
568 :meth:`notify`, but wakes up all waiting threads instead of one. If the
569 calling thread has not acquired the lock when this method is called, a
570 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
572
573.. _semaphore-objects:
574
575Semaphore Objects
576-----------------
577
578This is one of the oldest synchronization primitives in the history of computer
579science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
580used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
581
582A semaphore manages an internal counter which is decremented by each
583:meth:`acquire` call and incremented by each :meth:`release` call. The counter
584can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
585waiting until some other thread calls :meth:`release`.
586
587
588.. class:: Semaphore([value])
589
590 The optional argument gives the initial *value* for the internal counter; it
591 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
592 raised.
593
Georg Brandl3591a8f2009-07-26 14:44:23 +0000594 .. method:: acquire([blocking])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000595
Georg Brandl3591a8f2009-07-26 14:44:23 +0000596 Acquire a semaphore.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000597
Georg Brandl3591a8f2009-07-26 14:44:23 +0000598 When invoked without arguments: if the internal counter is larger than
599 zero on entry, decrement it by one and return immediately. If it is zero
600 on entry, block, waiting until some other thread has called
601 :meth:`release` to make it larger than zero. This is done with proper
602 interlocking so that if multiple :meth:`acquire` calls are blocked,
603 :meth:`release` will wake exactly one of them up. The implementation may
604 pick one at random, so the order in which blocked threads are awakened
605 should not be relied on. There is no return value in this case.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000606
Georg Brandl3591a8f2009-07-26 14:44:23 +0000607 When invoked with *blocking* set to true, do the same thing as when called
608 without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
Georg Brandl3591a8f2009-07-26 14:44:23 +0000610 When invoked with *blocking* set to false, do not block. If a call
611 without an argument would block, return false immediately; otherwise, do
612 the same thing as when called without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000613
Georg Brandl3591a8f2009-07-26 14:44:23 +0000614 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615
Georg Brandl3591a8f2009-07-26 14:44:23 +0000616 Release a semaphore, incrementing the internal counter by one. When it
617 was zero on entry and another thread is waiting for it to become larger
618 than zero again, wake up that thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
620
621.. _semaphore-examples:
622
623:class:`Semaphore` Example
624^^^^^^^^^^^^^^^^^^^^^^^^^^
625
626Semaphores are often used to guard resources with limited capacity, for example,
627a database server. In any situation where the size of the resource size is
628fixed, you should use a bounded semaphore. Before spawning any worker threads,
629your main thread would initialize the semaphore::
630
631 maxconnections = 5
632 ...
633 pool_sema = BoundedSemaphore(value=maxconnections)
634
635Once spawned, worker threads call the semaphore's acquire and release methods
636when they need to connect to the server::
637
638 pool_sema.acquire()
639 conn = connectdb()
640 ... use connection ...
641 conn.close()
642 pool_sema.release()
643
644The use of a bounded semaphore reduces the chance that a programming error which
645causes the semaphore to be released more than it's acquired will go undetected.
646
647
648.. _event-objects:
649
650Event Objects
651-------------
652
653This is one of the simplest mechanisms for communication between threads: one
654thread signals an event and other threads wait for it.
655
656An event object manages an internal flag that can be set to true with the
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000657:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl8ec7f652007-08-15 14:28:01 +0000658:meth:`wait` method blocks until the flag is true.
659
660
661.. class:: Event()
662
663 The internal flag is initially false.
664
Georg Brandl3591a8f2009-07-26 14:44:23 +0000665 .. method:: is_set()
666 isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667
Georg Brandl3591a8f2009-07-26 14:44:23 +0000668 Return true if and only if the internal flag is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000669
Facundo Batista47b66592010-01-25 06:15:01 +0000670 .. versionchanged:: 2.6
671 The ``is_set()`` syntax is new.
672
Georg Brandl3591a8f2009-07-26 14:44:23 +0000673 .. method:: set()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674
Georg Brandl3591a8f2009-07-26 14:44:23 +0000675 Set the internal flag to true. All threads waiting for it to become true
676 are awakened. Threads that call :meth:`wait` once the flag is true will
677 not block at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
Georg Brandl3591a8f2009-07-26 14:44:23 +0000679 .. method:: clear()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
Georg Brandl3591a8f2009-07-26 14:44:23 +0000681 Reset the internal flag to false. Subsequently, threads calling
682 :meth:`wait` will block until :meth:`.set` is called to set the internal
683 flag to true again.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000684
Georg Brandl3591a8f2009-07-26 14:44:23 +0000685 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
Georg Brandl3591a8f2009-07-26 14:44:23 +0000687 Block until the internal flag is true. If the internal flag is true on
688 entry, return immediately. Otherwise, block until another thread calls
689 :meth:`.set` to set the flag to true, or until the optional timeout
690 occurs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000691
Georg Brandl3591a8f2009-07-26 14:44:23 +0000692 When the timeout argument is present and not ``None``, it should be a
693 floating point number specifying a timeout for the operation in seconds
694 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695
Georg Brandl3591a8f2009-07-26 14:44:23 +0000696 This method returns the internal flag on exit, so it will always return
697 ``True`` except if a timeout is given and the operation times out.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698
Georg Brandl3591a8f2009-07-26 14:44:23 +0000699 .. versionchanged:: 2.7
700 Previously, the method always returned ``None``.
Georg Brandlef660e82009-03-31 20:41:08 +0000701
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703.. _timer-objects:
704
705Timer Objects
706-------------
707
708This class represents an action that should be run only after a certain amount
709of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
710and as such also functions as an example of creating custom threads.
711
712Timers are started, as with threads, by calling their :meth:`start` method. The
713timer can be stopped (before its action has begun) by calling the :meth:`cancel`
714method. The interval the timer will wait before executing its action may not be
715exactly the same as the interval specified by the user.
716
717For example::
718
719 def hello():
720 print "hello, world"
721
722 t = Timer(30.0, hello)
723 t.start() # after 30 seconds, "hello, world" will be printed
724
725
726.. class:: Timer(interval, function, args=[], kwargs={})
727
728 Create a timer that will run *function* with arguments *args* and keyword
729 arguments *kwargs*, after *interval* seconds have passed.
730
Georg Brandl3591a8f2009-07-26 14:44:23 +0000731 .. method:: cancel()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000732
Georg Brandl3591a8f2009-07-26 14:44:23 +0000733 Stop the timer, and cancel the execution of the timer's action. This will
734 only work if the timer is still in its waiting stage.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735
736
737.. _with-locks:
738
739Using locks, conditions, and semaphores in the :keyword:`with` statement
740------------------------------------------------------------------------
741
742All of the objects provided by this module that have :meth:`acquire` and
743:meth:`release` methods can be used as context managers for a :keyword:`with`
744statement. The :meth:`acquire` method will be called when the block is entered,
745and :meth:`release` will be called when the block is exited.
746
747Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
748:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
749:keyword:`with` statement context managers. For example::
750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751 import threading
752
753 some_rlock = threading.RLock()
754
755 with some_rlock:
756 print "some_rlock is locked while this executes"
757
Georg Brandl2e255512008-03-13 07:21:41 +0000758
759.. _threaded-imports:
760
761Importing in threaded code
762--------------------------
763
764While the import machinery is thread safe, there are two key
765restrictions on threaded imports due to inherent limitations in the way
766that thread safety is provided:
767
768* Firstly, other than in the main module, an import should not have the
769 side effect of spawning a new thread and then waiting for that thread in
770 any way. Failing to abide by this restriction can lead to a deadlock if
771 the spawned thread directly or indirectly attempts to import a module.
772* Secondly, all import attempts must be completed before the interpreter
773 starts shutting itself down. This can be most easily achieved by only
774 performing imports from non-daemon threads created through the threading
775 module. Daemon threads and threads created directly with the thread
776 module will require some other form of synchronization to ensure they do
777 not attempt imports after system shutdown has commenced. Failure to
778 abide by this restriction will lead to intermittent exceptions and
779 crashes during interpreter shutdown (as the late imports attempt to
780 access machinery which is no longer in a valid state).