blob: ce91750aa8cd7a0fcdd9f20aa259bf9b3b02cda6 [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
26 count is equal to the length of the list returned by :func:`enumerate`.
27
28
29.. function:: Condition()
30 :noindex:
31
32 A factory function that returns a new condition variable object. A condition
33 variable allows one or more threads to wait until they are notified by another
34 thread.
35
36
Benjamin Peterson672b8032008-06-11 19:14:14 +000037.. function:: current_thread()
Georg Brandl116aa622007-08-15 14:28:22 +000038
39 Return the current :class:`Thread` object, corresponding to the caller's thread
40 of control. If the caller's thread of control was not created through the
41 :mod:`threading` module, a dummy thread object with limited functionality is
42 returned.
43
44
45.. function:: enumerate()
46
Benjamin Peterson672b8032008-06-11 19:14:14 +000047 Return a list of all :class:`Thread` objects currently alive. The list
48 includes daemonic threads, dummy thread objects created by
49 :func:`current_thread`, and the main thread. It excludes terminated threads
50 and threads that have not yet been started.
Georg Brandl116aa622007-08-15 14:28:22 +000051
52
53.. function:: Event()
54 :noindex:
55
56 A factory function that returns a new event object. An event manages a flag
57 that can be set to true with the :meth:`set` method and reset to false with the
58 :meth:`clear` method. The :meth:`wait` method blocks until the flag is true.
59
60
61.. class:: local
62
63 A class that represents thread-local data. Thread-local data are data whose
64 values are thread specific. To manage thread-local data, just create an
65 instance of :class:`local` (or a subclass) and store attributes on it::
66
67 mydata = threading.local()
68 mydata.x = 1
69
70 The instance's values will be different for separate threads.
71
72 For more details and extensive examples, see the documentation string of the
73 :mod:`_threading_local` module.
74
Georg Brandl116aa622007-08-15 14:28:22 +000075
76.. function:: Lock()
77
78 A factory function that returns a new primitive lock object. Once a thread has
79 acquired it, subsequent attempts to acquire it block, until it is released; any
80 thread may release it.
81
82
83.. function:: RLock()
84
85 A factory function that returns a new reentrant lock object. A reentrant lock
86 must be released by the thread that acquired it. Once a thread has acquired a
87 reentrant lock, the same thread may acquire it again without blocking; the
88 thread must release it once for each time it has acquired it.
89
90
91.. function:: Semaphore([value])
92 :noindex:
93
94 A factory function that returns a new semaphore object. A semaphore manages a
95 counter representing the number of :meth:`release` calls minus the number of
96 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
97 if necessary until it can return without making the counter negative. If not
98 given, *value* defaults to 1.
99
100
101.. function:: BoundedSemaphore([value])
102
103 A factory function that returns a new bounded semaphore object. A bounded
104 semaphore checks to make sure its current value doesn't exceed its initial
105 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
106 are used to guard resources with limited capacity. If the semaphore is released
107 too many times it's a sign of a bug. If not given, *value* defaults to 1.
108
109
110.. class:: Thread
111
112 A class that represents a thread of control. This class can be safely
113 subclassed in a limited fashion.
114
115
116.. class:: Timer
117
118 A thread that executes a function after a specified interval has passed.
119
120
121.. function:: settrace(func)
122
123 .. index:: single: trace function
124
125 Set a trace function for all threads started from the :mod:`threading` module.
126 The *func* will be passed to :func:`sys.settrace` for each thread, before its
127 :meth:`run` method is called.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. function:: setprofile(func)
131
132 .. index:: single: profile function
133
134 Set a profile function for all threads started from the :mod:`threading` module.
135 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
136 :meth:`run` method is called.
137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139.. function:: stack_size([size])
140
141 Return the thread stack size used when creating new threads. The optional
142 *size* argument specifies the stack size to be used for subsequently created
143 threads, and must be 0 (use platform or configured default) or a positive
144 integer value of at least 32,768 (32kB). If changing the thread stack size is
145 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
146 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
147 is currently the minimum supported stack size value to guarantee sufficient
148 stack space for the interpreter itself. Note that some platforms may have
149 particular restrictions on values for the stack size, such as requiring a
150 minimum stack size > 32kB or requiring allocation in multiples of the system
151 memory page size - platform documentation should be referred to for more
152 information (4kB pages are common; using multiples of 4096 for the stack size is
153 the suggested approach in the absence of more specific information).
154 Availability: Windows, systems with POSIX threads.
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157Detailed interfaces for the objects are documented below.
158
159The design of this module is loosely based on Java's threading model. However,
160where Java makes locks and condition variables basic behavior of every object,
161they are separate objects in Python. Python's :class:`Thread` class supports a
162subset of the behavior of Java's Thread class; currently, there are no
163priorities, no thread groups, and threads cannot be destroyed, stopped,
164suspended, resumed, or interrupted. The static methods of Java's Thread class,
165when implemented, are mapped to module-level functions.
166
167All of the methods described below are executed atomically.
168
169
Georg Brandla971c652008-11-07 09:39:56 +0000170.. _thread-objects:
171
172Thread Objects
173--------------
174
175This class represents an activity that is run in a separate thread of control.
176There are two ways to specify the activity: by passing a callable object to the
177constructor, or by overriding the :meth:`run` method in a subclass. No other
178methods (except for the constructor) should be overridden in a subclass. In
179other words, *only* override the :meth:`__init__` and :meth:`run` methods of
180this class.
181
182Once a thread object is created, its activity must be started by calling the
183thread's :meth:`start` method. This invokes the :meth:`run` method in a
184separate thread of control.
185
186Once the thread's activity is started, the thread is considered 'alive'. It
187stops being alive when its :meth:`run` method terminates -- either normally, or
188by raising an unhandled exception. The :meth:`is_alive` method tests whether the
189thread is alive.
190
191Other threads can call a thread's :meth:`join` method. This blocks the calling
192thread until the thread whose :meth:`join` method is called is terminated.
193
194A thread has a name. The name can be passed to the constructor, and read or
195changed through the :attr:`name` attribute.
196
197A thread can be flagged as a "daemon thread". The significance of this flag is
198that the entire Python program exits when only daemon threads are left. The
199initial value is inherited from the creating thread. The flag can be set
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000200through the :attr:`daemon` property.
Georg Brandla971c652008-11-07 09:39:56 +0000201
202There is a "main thread" object; this corresponds to the initial thread of
203control in the Python program. It is not a daemon thread.
204
205There is the possibility that "dummy thread objects" are created. These are
206thread objects corresponding to "alien threads", which are threads of control
207started outside the threading module, such as directly from C code. Dummy
208thread objects have limited functionality; they are always considered alive and
209daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
210impossible to detect the termination of alien threads.
211
212
213.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
214
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000215 This constructor should always be called with keyword arguments. Arguments
216 are:
Georg Brandla971c652008-11-07 09:39:56 +0000217
218 *group* should be ``None``; reserved for future extension when a
219 :class:`ThreadGroup` class is implemented.
220
221 *target* is the callable object to be invoked by the :meth:`run` method.
222 Defaults to ``None``, meaning nothing is called.
223
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000224 *name* is the thread name. By default, a unique name is constructed of the
225 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandla971c652008-11-07 09:39:56 +0000226
227 *args* is the argument tuple for the target invocation. Defaults to ``()``.
228
229 *kwargs* is a dictionary of keyword arguments for the target invocation.
230 Defaults to ``{}``.
231
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000232 If the subclass overrides the constructor, it must make sure to invoke the
233 base class constructor (``Thread.__init__()``) before doing anything else to
234 the thread.
Georg Brandla971c652008-11-07 09:39:56 +0000235
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000236 .. method:: start()
Georg Brandla971c652008-11-07 09:39:56 +0000237
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000238 Start the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000239
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000240 It must be called at most once per thread object. It arranges for the
241 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandla971c652008-11-07 09:39:56 +0000242
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000243 This method will raise a :exc:`RuntimeException` if called more than once
244 on the same thread object.
Georg Brandla971c652008-11-07 09:39:56 +0000245
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000246 .. method:: run()
Georg Brandla971c652008-11-07 09:39:56 +0000247
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000248 Method representing the thread's activity.
Georg Brandla971c652008-11-07 09:39:56 +0000249
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000250 You may override this method in a subclass. The standard :meth:`run`
251 method invokes the callable object passed to the object's constructor as
252 the *target* argument, if any, with sequential and keyword arguments taken
253 from the *args* and *kwargs* arguments, respectively.
Georg Brandla971c652008-11-07 09:39:56 +0000254
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000255 .. method:: join([timeout])
Georg Brandla971c652008-11-07 09:39:56 +0000256
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000257 Wait until the thread terminates. This blocks the calling thread until the
258 thread whose :meth:`join` method is called terminates -- either normally
259 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandla971c652008-11-07 09:39:56 +0000260
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000261 When the *timeout* argument is present and not ``None``, it should be a
262 floating point number specifying a timeout for the operation in seconds
263 (or fractions thereof). As :meth:`join` always returns ``None``, you must
264 call :meth:`is_alive` after :meth:`join` to decide whether a timeout
265 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandla971c652008-11-07 09:39:56 +0000266
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000267 When the *timeout* argument is not present or ``None``, the operation will
268 block until the thread terminates.
Georg Brandla971c652008-11-07 09:39:56 +0000269
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000270 A thread can be :meth:`join`\ ed many times.
Georg Brandla971c652008-11-07 09:39:56 +0000271
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000272 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
273 the current thread as that would cause a deadlock. It is also an error to
274 :meth:`join` a thread before it has been started and attempts to do so
275 raises the same exception.
Georg Brandla971c652008-11-07 09:39:56 +0000276
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000277 .. attribute:: name
Georg Brandla971c652008-11-07 09:39:56 +0000278
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000279 A string used for identification purposes only. It has no semantics.
280 Multiple threads may be given the same name. The initial name is set by
281 the constructor.
Georg Brandla971c652008-11-07 09:39:56 +0000282
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000283 .. method:: getName()
284 setName()
Georg Brandla971c652008-11-07 09:39:56 +0000285
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000286 Old getter/setter API for :attr:`~Thread.name`; use it directly as a
287 property instead.
Georg Brandla971c652008-11-07 09:39:56 +0000288
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000289 .. attribute:: ident
Georg Brandla971c652008-11-07 09:39:56 +0000290
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000291 The 'thread identifier' of this thread or ``None`` if the thread has not
292 been started. This is a nonzero integer. See the
293 :func:`thread.get_ident()` function. Thread identifiers may be recycled
294 when a thread exits and another thread is created. The identifier is
295 available even after the thread has exited.
Georg Brandla971c652008-11-07 09:39:56 +0000296
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000297 .. method:: is_alive()
Georg Brandla971c652008-11-07 09:39:56 +0000298
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000299 Return whether the thread is alive.
Georg Brandl770b0be2009-01-02 20:10:05 +0000300
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000301 Roughly, a thread is alive from the moment the :meth:`start` method
302 returns until its :meth:`run` method terminates. The module function
303 :func:`enumerate` returns a list of all alive threads.
Georg Brandl770b0be2009-01-02 20:10:05 +0000304
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000305 .. attribute:: daemon
Georg Brandl770b0be2009-01-02 20:10:05 +0000306
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000307 A boolean value indicating whether this thread is a daemon thread (True)
308 or not (False). This must be set before :meth:`start` is called,
309 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
310 from the creating thread; the main thread is not a daemon thread and
311 therefore all threads created in the main thread default to :attr:`daemon`
312 = ``False``.
Georg Brandla971c652008-11-07 09:39:56 +0000313
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000314 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandla971c652008-11-07 09:39:56 +0000315
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000316 .. method:: isDaemon()
317 setDaemon()
Georg Brandla971c652008-11-07 09:39:56 +0000318
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000319 Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
320 property instead.
Georg Brandl770b0be2009-01-02 20:10:05 +0000321
322
Georg Brandl116aa622007-08-15 14:28:22 +0000323.. _lock-objects:
324
325Lock Objects
326------------
327
328A primitive lock is a synchronization primitive that is not owned by a
329particular thread when locked. In Python, it is currently the lowest level
Georg Brandl2067bfd2008-05-25 13:05:15 +0000330synchronization primitive available, implemented directly by the :mod:`_thread`
Georg Brandl116aa622007-08-15 14:28:22 +0000331extension module.
332
333A primitive lock is in one of two states, "locked" or "unlocked". It is created
334in the unlocked state. It has two basic methods, :meth:`acquire` and
335:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
336to locked and returns immediately. When the state is locked, :meth:`acquire`
337blocks until a call to :meth:`release` in another thread changes it to unlocked,
338then the :meth:`acquire` call resets it to locked and returns. The
339:meth:`release` method should only be called in the locked state; it changes the
340state to unlocked and returns immediately. If an attempt is made to release an
341unlocked lock, a :exc:`RuntimeError` will be raised.
342
343When more than one thread is blocked in :meth:`acquire` waiting for the state to
344turn to unlocked, only one thread proceeds when a :meth:`release` call resets
345the state to unlocked; which one of the waiting threads proceeds is not defined,
346and may vary across implementations.
347
348All methods are executed atomically.
349
350
351.. method:: Lock.acquire([blocking=1])
352
353 Acquire a lock, blocking or non-blocking.
354
355 When invoked without arguments, block until the lock is unlocked, then set it to
356 locked, and return true.
357
358 When invoked with the *blocking* argument set to true, do the same thing as when
359 called without arguments, and return true.
360
361 When invoked with the *blocking* argument set to false, do not block. If a call
362 without an argument would block, return false immediately; otherwise, do the
363 same thing as when called without arguments, and return true.
364
365
366.. method:: Lock.release()
367
368 Release a lock.
369
370 When the lock is locked, reset it to unlocked, and return. If any other threads
371 are blocked waiting for the lock to become unlocked, allow exactly one of them
372 to proceed.
373
374 Do not call this method when the lock is unlocked.
375
376 There is no return value.
377
378
379.. _rlock-objects:
380
381RLock Objects
382-------------
383
384A reentrant lock is a synchronization primitive that may be acquired multiple
385times by the same thread. Internally, it uses the concepts of "owning thread"
386and "recursion level" in addition to the locked/unlocked state used by primitive
387locks. In the locked state, some thread owns the lock; in the unlocked state,
388no thread owns it.
389
390To lock the lock, a thread calls its :meth:`acquire` method; this returns once
391the thread owns the lock. To unlock the lock, a thread calls its
392:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
393nested; only the final :meth:`release` (the :meth:`release` of the outermost
394pair) resets the lock to unlocked and allows another thread blocked in
395:meth:`acquire` to proceed.
396
397
398.. method:: RLock.acquire([blocking=1])
399
400 Acquire a lock, blocking or non-blocking.
401
402 When invoked without arguments: if this thread already owns the lock, increment
403 the recursion level by one, and return immediately. Otherwise, if another
404 thread owns the lock, block until the lock is unlocked. Once the lock is
405 unlocked (not owned by any thread), then grab ownership, set the recursion level
406 to one, and return. If more than one thread is blocked waiting until the lock
407 is unlocked, only one at a time will be able to grab ownership of the lock.
408 There is no return value in this case.
409
410 When invoked with the *blocking* argument set to true, do the same thing as when
411 called without arguments, and return true.
412
413 When invoked with the *blocking* argument set to false, do not block. If a call
414 without an argument would block, return false immediately; otherwise, do the
415 same thing as when called without arguments, and return true.
416
417
418.. method:: RLock.release()
419
420 Release a lock, decrementing the recursion level. If after the decrement it is
421 zero, reset the lock to unlocked (not owned by any thread), and if any other
422 threads are blocked waiting for the lock to become unlocked, allow exactly one
423 of them to proceed. If after the decrement the recursion level is still
424 nonzero, the lock remains locked and owned by the calling thread.
425
426 Only call this method when the calling thread owns the lock. A
427 :exc:`RuntimeError` is raised if this method is called when the lock is
428 unlocked.
429
430 There is no return value.
431
432
433.. _condition-objects:
434
435Condition Objects
436-----------------
437
438A condition variable is always associated with some kind of lock; this can be
439passed in or one will be created by default. (Passing one in is useful when
440several condition variables must share the same lock.)
441
442A condition variable has :meth:`acquire` and :meth:`release` methods that call
443the corresponding methods of the associated lock. It also has a :meth:`wait`
Georg Brandlf9926402008-06-13 06:32:25 +0000444method, and :meth:`notify` and :meth:`notify_all` methods. These three must only
Georg Brandl116aa622007-08-15 14:28:22 +0000445be called when the calling thread has acquired the lock, otherwise a
446:exc:`RuntimeError` is raised.
447
448The :meth:`wait` method releases the lock, and then blocks until it is awakened
Georg Brandlf9926402008-06-13 06:32:25 +0000449by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
Georg Brandl116aa622007-08-15 14:28:22 +0000450another thread. Once awakened, it re-acquires the lock and returns. It is also
451possible to specify a timeout.
452
453The :meth:`notify` method wakes up one of the threads waiting for the condition
Georg Brandlf9926402008-06-13 06:32:25 +0000454variable, if any are waiting. The :meth:`notify_all` method wakes up all threads
Georg Brandl116aa622007-08-15 14:28:22 +0000455waiting for the condition variable.
456
Georg Brandlf9926402008-06-13 06:32:25 +0000457Note: the :meth:`notify` and :meth:`notify_all` methods don't release the lock;
Georg Brandl116aa622007-08-15 14:28:22 +0000458this means that the thread or threads awakened will not return from their
459:meth:`wait` call immediately, but only when the thread that called
Georg Brandlf9926402008-06-13 06:32:25 +0000460:meth:`notify` or :meth:`notify_all` finally relinquishes ownership of the lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462Tip: the typical programming style using condition variables uses the lock to
463synchronize access to some shared state; threads that are interested in a
464particular change of state call :meth:`wait` repeatedly until they see the
465desired state, while threads that modify the state call :meth:`notify` or
Georg Brandlf9926402008-06-13 06:32:25 +0000466:meth:`notify_all` when they change the state in such a way that it could
Georg Brandl116aa622007-08-15 14:28:22 +0000467possibly be a desired state for one of the waiters. For example, the following
468code is a generic producer-consumer situation with unlimited buffer capacity::
469
470 # Consume one item
471 cv.acquire()
472 while not an_item_is_available():
473 cv.wait()
474 get_an_available_item()
475 cv.release()
476
477 # Produce one item
478 cv.acquire()
479 make_an_item_available()
480 cv.notify()
481 cv.release()
482
Georg Brandlf9926402008-06-13 06:32:25 +0000483To choose between :meth:`notify` and :meth:`notify_all`, consider whether one
Georg Brandl116aa622007-08-15 14:28:22 +0000484state change can be interesting for only one or several waiting threads. E.g.
485in a typical producer-consumer situation, adding one item to the buffer only
486needs to wake up one consumer thread.
487
488
489.. class:: Condition([lock])
490
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000491 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
492 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
493 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000495 .. method:: acquire(*args)
Georg Brandl116aa622007-08-15 14:28:22 +0000496
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000497 Acquire the underlying lock. This method calls the corresponding method on
498 the underlying lock; the return value is whatever that method returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000500 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000502 Release the underlying lock. This method calls the corresponding method on
503 the underlying lock; there is no return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000505 .. method:: wait([timeout])
Georg Brandl116aa622007-08-15 14:28:22 +0000506
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000507 Wait until notified or until a timeout occurs. If the calling thread has
508 not acquired the lock when this method is called, a :exc:`RuntimeError` is
509 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000511 This method releases the underlying lock, and then blocks until it is
512 awakened by a :meth:`notify` or :meth:`notify_all` call for the same
513 condition variable in another thread, or until the optional timeout
514 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000516 When the *timeout* argument is present and not ``None``, it should be a
517 floating point number specifying a timeout for the operation in seconds
518 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000519
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000520 When the underlying lock is an :class:`RLock`, it is not released using
521 its :meth:`release` method, since this may not actually unlock the lock
522 when it was acquired multiple times recursively. Instead, an internal
523 interface of the :class:`RLock` class is used, which really unlocks it
524 even when it has been recursively acquired several times. Another internal
525 interface is then used to restore the recursion level when the lock is
526 reacquired.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000528 .. method:: notify()
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000530 Wake up a thread waiting on this condition, if any. If the calling thread
531 has not acquired the lock when this method is called, a
532 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000534 This method wakes up one of the threads waiting for the condition
535 variable, if any are waiting; it is a no-op if no threads are waiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000537 The current implementation wakes up exactly one thread, if any are
538 waiting. However, it's not safe to rely on this behavior. A future,
539 optimized implementation may occasionally wake up more than one thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000541 Note: the awakened thread does not actually return from its :meth:`wait`
542 call until it can reacquire the lock. Since :meth:`notify` does not
543 release the lock, its caller should.
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000545 .. method:: notify_all()
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000547 Wake up all threads waiting on this condition. This method acts like
548 :meth:`notify`, but wakes up all waiting threads instead of one. If the
549 calling thread has not acquired the lock when this method is called, a
550 :exc:`RuntimeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552
553.. _semaphore-objects:
554
555Semaphore Objects
556-----------------
557
558This is one of the oldest synchronization primitives in the history of computer
559science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
560used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
561
562A semaphore manages an internal counter which is decremented by each
563:meth:`acquire` call and incremented by each :meth:`release` call. The counter
564can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
565waiting until some other thread calls :meth:`release`.
566
567
568.. class:: Semaphore([value])
569
570 The optional argument gives the initial *value* for the internal counter; it
571 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
572 raised.
573
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000574 .. method:: acquire([blocking])
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000576 Acquire a semaphore.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000578 When invoked without arguments: if the internal counter is larger than
579 zero on entry, decrement it by one and return immediately. If it is zero
580 on entry, block, waiting until some other thread has called
581 :meth:`release` to make it larger than zero. This is done with proper
582 interlocking so that if multiple :meth:`acquire` calls are blocked,
583 :meth:`release` will wake exactly one of them up. The implementation may
584 pick one at random, so the order in which blocked threads are awakened
585 should not be relied on. There is no return value in this case.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000587 When invoked with *blocking* set to true, do the same thing as when called
588 without arguments, and return true.
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000590 When invoked with *blocking* set to false, do not block. If a call
591 without an argument would block, return false immediately; otherwise, do
592 the same thing as when called without arguments, and return true.
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000594 .. method:: release()
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000596 Release a semaphore, incrementing the internal counter by one. When it
597 was zero on entry and another thread is waiting for it to become larger
598 than zero again, wake up that thread.
Georg Brandl116aa622007-08-15 14:28:22 +0000599
600
601.. _semaphore-examples:
602
603:class:`Semaphore` Example
604^^^^^^^^^^^^^^^^^^^^^^^^^^
605
606Semaphores are often used to guard resources with limited capacity, for example,
607a database server. In any situation where the size of the resource size is
608fixed, you should use a bounded semaphore. Before spawning any worker threads,
609your main thread would initialize the semaphore::
610
611 maxconnections = 5
612 ...
613 pool_sema = BoundedSemaphore(value=maxconnections)
614
615Once spawned, worker threads call the semaphore's acquire and release methods
616when they need to connect to the server::
617
618 pool_sema.acquire()
619 conn = connectdb()
620 ... use connection ...
621 conn.close()
622 pool_sema.release()
623
624The use of a bounded semaphore reduces the chance that a programming error which
625causes the semaphore to be released more than it's acquired will go undetected.
626
627
628.. _event-objects:
629
630Event Objects
631-------------
632
633This is one of the simplest mechanisms for communication between threads: one
634thread signals an event and other threads wait for it.
635
636An event object manages an internal flag that can be set to true with the
637:meth:`set` method and reset to false with the :meth:`clear` method. The
638:meth:`wait` method blocks until the flag is true.
639
640
641.. class:: Event()
642
643 The internal flag is initially false.
644
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000645 .. method:: is_set()
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000647 Return true if and only if the internal flag is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000649 .. method:: set()
Georg Brandl116aa622007-08-15 14:28:22 +0000650
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000651 Set the internal flag to true. All threads waiting for it to become true
652 are awakened. Threads that call :meth:`wait` once the flag is true will
653 not block at all.
Georg Brandl116aa622007-08-15 14:28:22 +0000654
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000655 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000656
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000657 Reset the internal flag to false. Subsequently, threads calling
658 :meth:`wait` will block until :meth:`set` is called to set the internal
659 flag to true again.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000661 .. method:: wait([timeout])
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000663 Block until the internal flag is true. If the internal flag is true on
664 entry, return immediately. Otherwise, block until another thread calls
665 :meth:`set` to set the flag to true, or until the optional timeout occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000666
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000667 When the timeout argument is present and not ``None``, it should be a
668 floating point number specifying a timeout for the operation in seconds
669 (or fractions thereof).
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000671 This method returns the internal flag on exit, so it will always return
672 ``True`` except if a timeout is given and the operation times out.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000674 .. versionchanged:: 3.1
675 Previously, the method always returned ``None``.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000676
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Georg Brandl116aa622007-08-15 14:28:22 +0000678.. _timer-objects:
679
680Timer Objects
681-------------
682
683This class represents an action that should be run only after a certain amount
684of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
685and as such also functions as an example of creating custom threads.
686
687Timers are started, as with threads, by calling their :meth:`start` method. The
688timer can be stopped (before its action has begun) by calling the :meth:`cancel`
689method. The interval the timer will wait before executing its action may not be
690exactly the same as the interval specified by the user.
691
692For example::
693
694 def hello():
Collin Winterc79461b2007-09-01 23:34:30 +0000695 print("hello, world")
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697 t = Timer(30.0, hello)
698 t.start() # after 30 seconds, "hello, world" will be printed
699
700
701.. class:: Timer(interval, function, args=[], kwargs={})
702
703 Create a timer that will run *function* with arguments *args* and keyword
704 arguments *kwargs*, after *interval* seconds have passed.
705
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000706 .. method:: cancel()
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Georg Brandl7a72b3a2009-07-26 14:48:09 +0000708 Stop the timer, and cancel the execution of the timer's action. This will
709 only work if the timer is still in its waiting stage.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711
712.. _with-locks:
713
714Using locks, conditions, and semaphores in the :keyword:`with` statement
715------------------------------------------------------------------------
716
717All of the objects provided by this module that have :meth:`acquire` and
718:meth:`release` methods can be used as context managers for a :keyword:`with`
719statement. The :meth:`acquire` method will be called when the block is entered,
720and :meth:`release` will be called when the block is exited.
721
722Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
723:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
724:keyword:`with` statement context managers. For example::
725
Georg Brandl116aa622007-08-15 14:28:22 +0000726 import threading
727
728 some_rlock = threading.RLock()
729
730 with some_rlock:
Collin Winterc79461b2007-09-01 23:34:30 +0000731 print("some_rlock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000733
734.. _threaded-imports:
735
736Importing in threaded code
737--------------------------
738
739While the import machinery is thread safe, there are two key
740restrictions on threaded imports due to inherent limitations in the way
741that thread safety is provided:
742
743* Firstly, other than in the main module, an import should not have the
744 side effect of spawning a new thread and then waiting for that thread in
745 any way. Failing to abide by this restriction can lead to a deadlock if
746 the spawned thread directly or indirectly attempts to import a module.
747* Secondly, all import attempts must be completed before the interpreter
748 starts shutting itself down. This can be most easily achieved by only
749 performing imports from non-daemon threads created through the threading
750 module. Daemon threads and threads created directly with the thread
751 module will require some other form of synchronization to ensure they do
752 not attempt imports after system shutdown has commenced. Failure to
753 abide by this restriction will lead to intermittent exceptions and
754 crashes during interpreter shutdown (as the late imports attempt to
755 access machinery which is no longer in a valid state).