blob: 68eb32ca6b40b157ec9a738c29e8bfb31c592b24 [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
Éric Araujo29a0b572011-08-19 02:14:03 +02007**Source code:** :source:`Lib/threading.py`
8
9--------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000010
11This module constructs higher-level threading interfaces on top of the lower
12level :mod:`thread` module.
Georg Brandla6168f92008-05-25 07:20:14 +000013See also the :mod:`mutex` and :mod:`Queue` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
15The :mod:`dummy_threading` module is provided for situations where
16:mod:`threading` cannot be used because :mod:`thread` is missing.
17
Benjamin Petersonf4395602008-06-11 17:50:00 +000018.. note::
19
Victor Stinner8ded4772010-05-14 14:20:07 +000020 Starting with Python 2.6, this module provides :pep:`8` compliant aliases and
Benjamin Peterson973e6c22008-09-01 23:12:58 +000021 properties to replace the ``camelCase`` names that were inspired by Java's
22 threading API. This updated API is compatible with that of the
23 :mod:`multiprocessing` module. However, no schedule has been set for the
24 deprecation of the ``camelCase`` names and they remain fully supported in
25 both Python 2.x and 3.x.
Benjamin Petersonf4395602008-06-11 17:50:00 +000026
Georg Brandl2cd82a82009-03-09 14:25:07 +000027.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000028
Georg Brandl2cd82a82009-03-09 14:25:07 +000029 Starting with Python 2.5, several Thread methods raise :exc:`RuntimeError`
30 instead of :exc:`AssertionError` if called erroneously.
31
Antoine Pitrou9f41bb32011-01-06 16:35:14 +000032.. impl-detail::
33
Ezio Melotti9e0f4622013-01-18 19:55:46 +020034 In CPython, due to the :term:`Global Interpreter Lock`, only one thread
Antoine Pitrou9f41bb32011-01-06 16:35:14 +000035 can execute Python code at once (even though certain performance-oriented
36 libraries might overcome this limitation).
Ezio Melotti9e0f4622013-01-18 19:55:46 +020037 If you want your application to make better use of the computational
Antoine Pitrou9f41bb32011-01-06 16:35:14 +000038 resources of multi-core machines, you are advised to use
39 :mod:`multiprocessing`. However, threading is still an appropriate model
40 if you want to run multiple I/O-bound tasks simultaneously.
41
Antoine Pitrou9f41bb32011-01-06 16:35:14 +000042
Georg Brandl2cd82a82009-03-09 14:25:07 +000043This module defines the following functions and objects:
Georg Brandl8ec7f652007-08-15 14:28:01 +000044
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000045.. function:: active_count()
Benjamin Petersonf4395602008-06-11 17:50:00 +000046 activeCount()
Georg Brandl8ec7f652007-08-15 14:28:01 +000047
48 Return the number of :class:`Thread` objects currently alive. The returned
Georg Brandlf4da6662009-09-19 12:04:16 +000049 count is equal to the length of the list returned by :func:`.enumerate`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000050
Georg Brandl52fa1722013-10-13 10:07:31 +020051 .. versionchanged:: 2.6
52 Added ``active_count()`` spelling.
53
Georg Brandl8ec7f652007-08-15 14:28:01 +000054
55.. function:: Condition()
56 :noindex:
57
58 A factory function that returns a new condition variable object. A condition
59 variable allows one or more threads to wait until they are notified by another
60 thread.
61
Georg Brandl21946af2010-10-06 09:28:45 +000062 See :ref:`condition-objects`.
63
Georg Brandl8ec7f652007-08-15 14:28:01 +000064
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000065.. function:: current_thread()
Benjamin Petersonf4395602008-06-11 17:50:00 +000066 currentThread()
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
68 Return the current :class:`Thread` object, corresponding to the caller's thread
69 of control. If the caller's thread of control was not created through the
70 :mod:`threading` module, a dummy thread object with limited functionality is
71 returned.
72
Georg Brandl52fa1722013-10-13 10:07:31 +020073 .. versionchanged:: 2.6
74 Added ``current_thread()`` spelling.
75
Georg Brandl8ec7f652007-08-15 14:28:01 +000076
77.. function:: enumerate()
78
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000079 Return a list of all :class:`Thread` objects currently alive. The list
80 includes daemonic threads, dummy thread objects created by
81 :func:`current_thread`, and the main thread. It excludes terminated threads
82 and threads that have not yet been started.
Georg Brandl8ec7f652007-08-15 14:28:01 +000083
84
85.. function:: Event()
86 :noindex:
87
88 A factory function that returns a new event object. An event manages a flag
Georg Brandl9fa61bb2009-07-26 14:19:57 +000089 that can be set to true with the :meth:`~Event.set` method and reset to false
90 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
91 is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
Georg Brandl21946af2010-10-06 09:28:45 +000093 See :ref:`event-objects`.
94
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96.. class:: local
97
98 A class that represents thread-local data. Thread-local data are data whose
99 values are thread specific. To manage thread-local data, just create an
100 instance of :class:`local` (or a subclass) and store attributes on it::
101
102 mydata = threading.local()
103 mydata.x = 1
104
105 The instance's values will be different for separate threads.
106
107 For more details and extensive examples, see the documentation string of the
108 :mod:`_threading_local` module.
109
110 .. versionadded:: 2.4
111
112
113.. function:: Lock()
114
115 A factory function that returns a new primitive lock object. Once a thread has
116 acquired it, subsequent attempts to acquire it block, until it is released; any
117 thread may release it.
118
Georg Brandl21946af2010-10-06 09:28:45 +0000119 See :ref:`lock-objects`.
120
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121
122.. function:: RLock()
123
124 A factory function that returns a new reentrant lock object. A reentrant lock
125 must be released by the thread that acquired it. Once a thread has acquired a
126 reentrant lock, the same thread may acquire it again without blocking; the
127 thread must release it once for each time it has acquired it.
128
Georg Brandl21946af2010-10-06 09:28:45 +0000129 See :ref:`rlock-objects`.
130
Georg Brandl8ec7f652007-08-15 14:28:01 +0000131
132.. function:: Semaphore([value])
133 :noindex:
134
135 A factory function that returns a new semaphore object. A semaphore manages a
136 counter representing the number of :meth:`release` calls minus the number of
137 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
138 if necessary until it can return without making the counter negative. If not
139 given, *value* defaults to 1.
140
Georg Brandl21946af2010-10-06 09:28:45 +0000141 See :ref:`semaphore-objects`.
142
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
144.. function:: BoundedSemaphore([value])
145
146 A factory function that returns a new bounded semaphore object. A bounded
147 semaphore checks to make sure its current value doesn't exceed its initial
148 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
149 are used to guard resources with limited capacity. If the semaphore is released
150 too many times it's a sign of a bug. If not given, *value* defaults to 1.
151
152
153.. class:: Thread
Georg Brandl21946af2010-10-06 09:28:45 +0000154 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155
156 A class that represents a thread of control. This class can be safely
157 subclassed in a limited fashion.
158
Georg Brandl21946af2010-10-06 09:28:45 +0000159 See :ref:`thread-objects`.
160
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162.. class:: Timer
Georg Brandl21946af2010-10-06 09:28:45 +0000163 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000164
165 A thread that executes a function after a specified interval has passed.
166
Georg Brandl21946af2010-10-06 09:28:45 +0000167 See :ref:`timer-objects`.
168
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
170.. function:: settrace(func)
171
172 .. index:: single: trace function
173
174 Set a trace function for all threads started from the :mod:`threading` module.
175 The *func* will be passed to :func:`sys.settrace` for each thread, before its
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300176 :meth:`~Thread.run` method is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
178 .. versionadded:: 2.3
179
180
181.. function:: setprofile(func)
182
183 .. index:: single: profile function
184
185 Set a profile function for all threads started from the :mod:`threading` module.
186 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300187 :meth:`~Thread.run` method is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188
189 .. versionadded:: 2.3
190
191
192.. function:: stack_size([size])
193
194 Return the thread stack size used when creating new threads. The optional
195 *size* argument specifies the stack size to be used for subsequently created
196 threads, and must be 0 (use platform or configured default) or a positive
197 integer value of at least 32,768 (32kB). If changing the thread stack size is
198 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
199 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
200 is currently the minimum supported stack size value to guarantee sufficient
201 stack space for the interpreter itself. Note that some platforms may have
202 particular restrictions on values for the stack size, such as requiring a
203 minimum stack size > 32kB or requiring allocation in multiples of the system
204 memory page size - platform documentation should be referred to for more
205 information (4kB pages are common; using multiples of 4096 for the stack size is
206 the suggested approach in the absence of more specific information).
207 Availability: Windows, systems with POSIX threads.
208
209 .. versionadded:: 2.5
210
211Detailed interfaces for the objects are documented below.
212
213The design of this module is loosely based on Java's threading model. However,
214where Java makes locks and condition variables basic behavior of every object,
215they are separate objects in Python. Python's :class:`Thread` class supports a
216subset of the behavior of Java's Thread class; currently, there are no
217priorities, no thread groups, and threads cannot be destroyed, stopped,
218suspended, resumed, or interrupted. The static methods of Java's Thread class,
219when implemented, are mapped to module-level functions.
220
221All of the methods described below are executed atomically.
222
223
Georg Brandl01ba86a2008-11-06 10:20:49 +0000224.. _thread-objects:
225
226Thread Objects
227--------------
228
229This class represents an activity that is run in a separate thread of control.
230There are two ways to specify the activity: by passing a callable object to the
231constructor, or by overriding the :meth:`run` method in a subclass. No other
232methods (except for the constructor) should be overridden in a subclass. In
233other words, *only* override the :meth:`__init__` and :meth:`run` methods of
234this class.
235
236Once a thread object is created, its activity must be started by calling the
237thread's :meth:`start` method. This invokes the :meth:`run` method in a
238separate thread of control.
239
240Once the thread's activity is started, the thread is considered 'alive'. It
241stops being alive when its :meth:`run` method terminates -- either normally, or
242by raising an unhandled exception. The :meth:`is_alive` method tests whether the
243thread is alive.
244
245Other threads can call a thread's :meth:`join` method. This blocks the calling
246thread until the thread whose :meth:`join` method is called is terminated.
247
248A thread has a name. The name can be passed to the constructor, and read or
249changed through the :attr:`name` attribute.
250
251A thread can be flagged as a "daemon thread". The significance of this flag is
252that the entire Python program exits when only daemon threads are left. The
253initial value is inherited from the creating thread. The flag can be set
Georg Brandlecd2afa2009-02-05 11:40:35 +0000254through the :attr:`daemon` property.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000255
Antoine Pitrouf1575712013-02-15 21:27:18 +0100256.. note::
257 Daemon threads are abruptly stopped at shutdown. Their resources (such
258 as open files, database transactions, etc.) may not be released properly.
259 If you want your threads to stop gracefully, make them non-daemonic and
260 use a suitable signalling mechanism such as an :class:`Event`.
261
Georg Brandl01ba86a2008-11-06 10:20:49 +0000262There is a "main thread" object; this corresponds to the initial thread of
263control in the Python program. It is not a daemon thread.
264
265There is the possibility that "dummy thread objects" are created. These are
266thread objects corresponding to "alien threads", which are threads of control
267started outside the threading module, such as directly from C code. Dummy
268thread objects have limited functionality; they are always considered alive and
269daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
270impossible to detect the termination of alien threads.
271
272
273.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
274
Georg Brandl3591a8f2009-07-26 14:44:23 +0000275 This constructor should always be called with keyword arguments. Arguments
276 are:
Georg Brandl01ba86a2008-11-06 10:20:49 +0000277
278 *group* should be ``None``; reserved for future extension when a
279 :class:`ThreadGroup` class is implemented.
280
281 *target* is the callable object to be invoked by the :meth:`run` method.
282 Defaults to ``None``, meaning nothing is called.
283
Georg Brandl3591a8f2009-07-26 14:44:23 +0000284 *name* is the thread name. By default, a unique name is constructed of the
285 form "Thread-*N*" where *N* is a small decimal number.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000286
287 *args* is the argument tuple for the target invocation. Defaults to ``()``.
288
289 *kwargs* is a dictionary of keyword arguments for the target invocation.
290 Defaults to ``{}``.
291
Georg Brandl3591a8f2009-07-26 14:44:23 +0000292 If the subclass overrides the constructor, it must make sure to invoke the
293 base class constructor (``Thread.__init__()``) before doing anything else to
294 the thread.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000295
Georg Brandl3591a8f2009-07-26 14:44:23 +0000296 .. method:: start()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000297
Georg Brandl3591a8f2009-07-26 14:44:23 +0000298 Start the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000299
Georg Brandl3591a8f2009-07-26 14:44:23 +0000300 It must be called at most once per thread object. It arranges for the
301 object's :meth:`run` method to be invoked in a separate thread of control.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000302
Brian Curtin37c4a722011-01-31 19:55:14 +0000303 This method will raise a :exc:`RuntimeError` if called more than once
Georg Brandl3591a8f2009-07-26 14:44:23 +0000304 on the same thread object.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000305
Georg Brandl3591a8f2009-07-26 14:44:23 +0000306 .. method:: run()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000307
Georg Brandl3591a8f2009-07-26 14:44:23 +0000308 Method representing the thread's activity.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000309
Georg Brandl3591a8f2009-07-26 14:44:23 +0000310 You may override this method in a subclass. The standard :meth:`run`
311 method invokes the callable object passed to the object's constructor as
312 the *target* argument, if any, with sequential and keyword arguments taken
313 from the *args* and *kwargs* arguments, respectively.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000314
Georg Brandl3591a8f2009-07-26 14:44:23 +0000315 .. method:: join([timeout])
Georg Brandl01ba86a2008-11-06 10:20:49 +0000316
Georg Brandl3591a8f2009-07-26 14:44:23 +0000317 Wait until the thread terminates. This blocks the calling thread until the
318 thread whose :meth:`join` method is called terminates -- either normally
319 or through an unhandled exception -- or until the optional timeout occurs.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000320
Georg Brandl3591a8f2009-07-26 14:44:23 +0000321 When the *timeout* argument is present and not ``None``, it should be a
322 floating point number specifying a timeout for the operation in seconds
323 (or fractions thereof). As :meth:`join` always returns ``None``, you must
324 call :meth:`isAlive` after :meth:`join` to decide whether a timeout
325 happened -- if the thread is still alive, the :meth:`join` call timed out.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000326
Georg Brandl3591a8f2009-07-26 14:44:23 +0000327 When the *timeout* argument is not present or ``None``, the operation will
328 block until the thread terminates.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000329
Georg Brandl3591a8f2009-07-26 14:44:23 +0000330 A thread can be :meth:`join`\ ed many times.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000331
Georg Brandl3591a8f2009-07-26 14:44:23 +0000332 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
333 the current thread as that would cause a deadlock. It is also an error to
334 :meth:`join` a thread before it has been started and attempts to do so
335 raises the same exception.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000336
Georg Brandl3591a8f2009-07-26 14:44:23 +0000337 .. attribute:: name
Georg Brandl01ba86a2008-11-06 10:20:49 +0000338
Georg Brandl3591a8f2009-07-26 14:44:23 +0000339 A string used for identification purposes only. It has no semantics.
340 Multiple threads may be given the same name. The initial name is set by
341 the constructor.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000342
Georg Brandl52fa1722013-10-13 10:07:31 +0200343 .. versionadded:: 2.6
344
345 .. method:: getName()
346 setName()
347
348 Pre-2.6 API for :attr:`~Thread.name`.
349
Georg Brandl3591a8f2009-07-26 14:44:23 +0000350 .. attribute:: ident
Georg Brandl01ba86a2008-11-06 10:20:49 +0000351
Georg Brandl3591a8f2009-07-26 14:44:23 +0000352 The 'thread identifier' of this thread or ``None`` if the thread has not
353 been started. This is a nonzero integer. See the
354 :func:`thread.get_ident()` function. Thread identifiers may be recycled
355 when a thread exits and another thread is created. The identifier is
356 available even after the thread has exited.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000357
Georg Brandl3591a8f2009-07-26 14:44:23 +0000358 .. versionadded:: 2.6
Georg Brandl01ba86a2008-11-06 10:20:49 +0000359
Georg Brandl3591a8f2009-07-26 14:44:23 +0000360 .. method:: is_alive()
361 isAlive()
Georg Brandl01ba86a2008-11-06 10:20:49 +0000362
Georg Brandl3591a8f2009-07-26 14:44:23 +0000363 Return whether the thread is alive.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000364
Brett Cannon11a30612010-07-23 12:30:10 +0000365 This method returns ``True`` just before the :meth:`run` method starts
366 until just after the :meth:`run` method terminates. The module function
Georg Brandlf4da6662009-09-19 12:04:16 +0000367 :func:`.enumerate` returns a list of all alive threads.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000368
Georg Brandl52fa1722013-10-13 10:07:31 +0200369 .. versionchanged:: 2.6
370 Added ``is_alive()`` spelling.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000371
Georg Brandl3591a8f2009-07-26 14:44:23 +0000372 .. attribute:: daemon
Georg Brandl01ba86a2008-11-06 10:20:49 +0000373
Georg Brandl3591a8f2009-07-26 14:44:23 +0000374 A boolean value indicating whether this thread is a daemon thread (True)
375 or not (False). This must be set before :meth:`start` is called,
376 otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
377 from the creating thread; the main thread is not a daemon thread and
378 therefore all threads created in the main thread default to :attr:`daemon`
379 = ``False``.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000380
Georg Brandl3591a8f2009-07-26 14:44:23 +0000381 The entire Python program exits when no alive non-daemon threads are left.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000382
Georg Brandl52fa1722013-10-13 10:07:31 +0200383 .. versionadded:: 2.6
384
385 .. method:: isDaemon()
386 setDaemon()
387
388 Pre-2.6 API for :attr:`~Thread.daemon`.
389
Georg Brandl01ba86a2008-11-06 10:20:49 +0000390
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391.. _lock-objects:
392
393Lock Objects
394------------
395
396A primitive lock is a synchronization primitive that is not owned by a
397particular thread when locked. In Python, it is currently the lowest level
398synchronization primitive available, implemented directly by the :mod:`thread`
399extension module.
400
401A primitive lock is in one of two states, "locked" or "unlocked". It is created
402in the unlocked state. It has two basic methods, :meth:`acquire` and
403:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
404to locked and returns immediately. When the state is locked, :meth:`acquire`
405blocks until a call to :meth:`release` in another thread changes it to unlocked,
406then the :meth:`acquire` call resets it to locked and returns. The
407:meth:`release` method should only be called in the locked state; it changes the
408state to unlocked and returns immediately. If an attempt is made to release an
409unlocked lock, a :exc:`RuntimeError` will be raised.
410
411When more than one thread is blocked in :meth:`acquire` waiting for the state to
412turn to unlocked, only one thread proceeds when a :meth:`release` call resets
413the state to unlocked; which one of the waiting threads proceeds is not defined,
414and may vary across implementations.
415
416All methods are executed atomically.
417
418
Terry Reedyc0b35442011-01-01 00:36:18 +0000419.. method:: Lock.acquire([blocking])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420
421 Acquire a lock, blocking or non-blocking.
422
R David Murray1bddab72012-05-17 09:15:02 -0400423 When invoked with the *blocking* argument set to ``True`` (the default),
424 block until the lock is unlocked, then set it to locked and return ``True``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
R David Murray1bddab72012-05-17 09:15:02 -0400426 When invoked with the *blocking* argument set to ``False``, do not block.
427 If a call with *blocking* set to ``True`` would block, return ``False``
428 immediately; otherwise, set the lock to locked and return ``True``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
430
431.. method:: Lock.release()
432
433 Release a lock.
434
435 When the lock is locked, reset it to unlocked, and return. If any other threads
436 are blocked waiting for the lock to become unlocked, allow exactly one of them
437 to proceed.
438
Sandro Tosiceeb47d2012-04-05 22:51:00 +0200439 When invoked on an unlocked lock, a :exc:`ThreadError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440
441 There is no return value.
442
443
444.. _rlock-objects:
445
446RLock Objects
447-------------
448
449A reentrant lock is a synchronization primitive that may be acquired multiple
450times by the same thread. Internally, it uses the concepts of "owning thread"
451and "recursion level" in addition to the locked/unlocked state used by primitive
452locks. In the locked state, some thread owns the lock; in the unlocked state,
453no thread owns it.
454
455To lock the lock, a thread calls its :meth:`acquire` method; this returns once
456the thread owns the lock. To unlock the lock, a thread calls its
457:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
458nested; only the final :meth:`release` (the :meth:`release` of the outermost
459pair) resets the lock to unlocked and allows another thread blocked in
460:meth:`acquire` to proceed.
461
462
463.. method:: RLock.acquire([blocking=1])
464
465 Acquire a lock, blocking or non-blocking.
466
467 When invoked without arguments: if this thread already owns the lock, increment
468 the recursion level by one, and return immediately. Otherwise, if another
469 thread owns the lock, block until the lock is unlocked. Once the lock is
470 unlocked (not owned by any thread), then grab ownership, set the recursion level
471 to one, and return. If more than one thread is blocked waiting until the lock
472 is unlocked, only one at a time will be able to grab ownership of the lock.
473 There is no return value in this case.
474
475 When invoked with the *blocking* argument set to true, do the same thing as when
476 called without arguments, and return true.
477
478 When invoked with the *blocking* argument set to false, do not block. If a call
479 without an argument would block, return false immediately; otherwise, do the
480 same thing as when called without arguments, and return true.
481
482
483.. method:: RLock.release()
484
485 Release a lock, decrementing the recursion level. If after the decrement it is
486 zero, reset the lock to unlocked (not owned by any thread), and if any other
487 threads are blocked waiting for the lock to become unlocked, allow exactly one
488 of them to proceed. If after the decrement the recursion level is still
489 nonzero, the lock remains locked and owned by the calling thread.
490
491 Only call this method when the calling thread owns the lock. A
492 :exc:`RuntimeError` is raised if this method is called when the lock is
493 unlocked.
494
495 There is no return value.
496
497
498.. _condition-objects:
499
500Condition Objects
501-----------------
502
503A condition variable is always associated with some kind of lock; this can be
504passed in or one will be created by default. (Passing one in is useful when
505several condition variables must share the same lock.)
506
507A condition variable has :meth:`acquire` and :meth:`release` methods that call
508the corresponding methods of the associated lock. It also has a :meth:`wait`
509method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
510be called when the calling thread has acquired the lock, otherwise a
511:exc:`RuntimeError` is raised.
512
513The :meth:`wait` method releases the lock, and then blocks until it is awakened
514by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
515another thread. Once awakened, it re-acquires the lock and returns. It is also
516possible to specify a timeout.
517
518The :meth:`notify` method wakes up one of the threads waiting for the condition
519variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
520waiting for the condition variable.
521
522Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
523this means that the thread or threads awakened will not return from their
524:meth:`wait` call immediately, but only when the thread that called
525:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
526
527Tip: the typical programming style using condition variables uses the lock to
528synchronize access to some shared state; threads that are interested in a
529particular change of state call :meth:`wait` repeatedly until they see the
530desired state, while threads that modify the state call :meth:`notify` or
531:meth:`notifyAll` when they change the state in such a way that it could
532possibly be a desired state for one of the waiters. For example, the following
533code is a generic producer-consumer situation with unlimited buffer capacity::
534
535 # Consume one item
536 cv.acquire()
537 while not an_item_is_available():
538 cv.wait()
539 get_an_available_item()
540 cv.release()
541
542 # Produce one item
543 cv.acquire()
544 make_an_item_available()
545 cv.notify()
546 cv.release()
547
548To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
549state change can be interesting for only one or several waiting threads. E.g.
550in a typical producer-consumer situation, adding one item to the buffer only
551needs to wake up one consumer thread.
552
553
554.. class:: Condition([lock])
555
Georg Brandl3591a8f2009-07-26 14:44:23 +0000556 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
557 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
558 a new :class:`RLock` object is created and used as the underlying lock.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000559
Georg Brandl3591a8f2009-07-26 14:44:23 +0000560 .. method:: acquire(*args)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561
Georg Brandl3591a8f2009-07-26 14:44:23 +0000562 Acquire the underlying lock. This method calls the corresponding method on
563 the underlying lock; the return value is whatever that method returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564
Georg Brandl3591a8f2009-07-26 14:44:23 +0000565 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000566
Georg Brandl3591a8f2009-07-26 14:44:23 +0000567 Release the underlying lock. This method calls the corresponding method on
568 the underlying lock; there is no return value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000569
Georg Brandl3591a8f2009-07-26 14:44:23 +0000570 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
Georg Brandl3591a8f2009-07-26 14:44:23 +0000572 Wait until notified or until a timeout occurs. If the calling thread has not
573 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000574
Georg Brandl3591a8f2009-07-26 14:44:23 +0000575 This method releases the underlying lock, and then blocks until it is
576 awakened by a :meth:`notify` or :meth:`notifyAll` call for the same
577 condition variable in another thread, or until the optional timeout
578 occurs. Once awakened or timed out, it re-acquires the lock and returns.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579
Georg Brandl3591a8f2009-07-26 14:44:23 +0000580 When the *timeout* argument is present and not ``None``, it should be a
581 floating point number specifying a timeout for the operation in seconds
582 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000583
Georg Brandl3591a8f2009-07-26 14:44:23 +0000584 When the underlying lock is an :class:`RLock`, it is not released using
585 its :meth:`release` method, since this may not actually unlock the lock
586 when it was acquired multiple times recursively. Instead, an internal
587 interface of the :class:`RLock` class is used, which really unlocks it
588 even when it has been recursively acquired several times. Another internal
589 interface is then used to restore the recursion level when the lock is
590 reacquired.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000591
Eli Bendersky3a8501e2011-11-12 20:51:54 +0200592 .. method:: notify(n=1)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000593
Eli Bendersky3a8501e2011-11-12 20:51:54 +0200594 By default, wake up one thread waiting on this condition, if any. If the
595 calling thread has not acquired the lock when this method is called, a
Georg Brandl3591a8f2009-07-26 14:44:23 +0000596 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000597
Eli Bendersky3a8501e2011-11-12 20:51:54 +0200598 This method wakes up at most *n* of the threads waiting for the condition
599 variable; it is a no-op if no threads are waiting.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000600
Eli Bendersky3a8501e2011-11-12 20:51:54 +0200601 The current implementation wakes up exactly *n* threads, if at least *n*
602 threads are waiting. However, it's not safe to rely on this behavior.
603 A future, optimized implementation may occasionally wake up more than
604 *n* threads.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000605
Eli Bendersky3a8501e2011-11-12 20:51:54 +0200606 Note: an awakened thread does not actually return from its :meth:`wait`
Georg Brandl3591a8f2009-07-26 14:44:23 +0000607 call until it can reacquire the lock. Since :meth:`notify` does not
608 release the lock, its caller should.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
Georg Brandl3591a8f2009-07-26 14:44:23 +0000610 .. method:: notify_all()
611 notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000612
Georg Brandl3591a8f2009-07-26 14:44:23 +0000613 Wake up all threads waiting on this condition. This method acts like
614 :meth:`notify`, but wakes up all waiting threads instead of one. If the
615 calling thread has not acquired the lock when this method is called, a
616 :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
Georg Brandl52fa1722013-10-13 10:07:31 +0200618 .. versionchanged:: 2.6
619 Added ``notify_all()`` spelling.
620
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621
622.. _semaphore-objects:
623
624Semaphore Objects
625-----------------
626
627This is one of the oldest synchronization primitives in the history of computer
628science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
629used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
630
631A semaphore manages an internal counter which is decremented by each
632:meth:`acquire` call and incremented by each :meth:`release` call. The counter
633can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
634waiting until some other thread calls :meth:`release`.
635
636
637.. class:: Semaphore([value])
638
639 The optional argument gives the initial *value* for the internal counter; it
640 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
641 raised.
642
Georg Brandl3591a8f2009-07-26 14:44:23 +0000643 .. method:: acquire([blocking])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000644
Georg Brandl3591a8f2009-07-26 14:44:23 +0000645 Acquire a semaphore.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000646
Georg Brandl3591a8f2009-07-26 14:44:23 +0000647 When invoked without arguments: if the internal counter is larger than
648 zero on entry, decrement it by one and return immediately. If it is zero
649 on entry, block, waiting until some other thread has called
650 :meth:`release` to make it larger than zero. This is done with proper
651 interlocking so that if multiple :meth:`acquire` calls are blocked,
652 :meth:`release` will wake exactly one of them up. The implementation may
653 pick one at random, so the order in which blocked threads are awakened
654 should not be relied on. There is no return value in this case.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000655
Georg Brandl3591a8f2009-07-26 14:44:23 +0000656 When invoked with *blocking* set to true, do the same thing as when called
657 without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000658
Georg Brandl3591a8f2009-07-26 14:44:23 +0000659 When invoked with *blocking* set to false, do not block. If a call
660 without an argument would block, return false immediately; otherwise, do
661 the same thing as when called without arguments, and return true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000662
Georg Brandl3591a8f2009-07-26 14:44:23 +0000663 .. method:: release()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664
Georg Brandl3591a8f2009-07-26 14:44:23 +0000665 Release a semaphore, incrementing the internal counter by one. When it
666 was zero on entry and another thread is waiting for it to become larger
667 than zero again, wake up that thread.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000668
669
670.. _semaphore-examples:
671
672:class:`Semaphore` Example
673^^^^^^^^^^^^^^^^^^^^^^^^^^
674
675Semaphores are often used to guard resources with limited capacity, for example,
Georg Brandl335d4f52011-01-09 07:58:45 +0000676a database server. In any situation where the size of the resource is fixed,
677you should use a bounded semaphore. Before spawning any worker threads, your
678main thread would initialize the semaphore::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679
680 maxconnections = 5
681 ...
682 pool_sema = BoundedSemaphore(value=maxconnections)
683
684Once spawned, worker threads call the semaphore's acquire and release methods
685when they need to connect to the server::
686
687 pool_sema.acquire()
688 conn = connectdb()
689 ... use connection ...
690 conn.close()
691 pool_sema.release()
692
693The use of a bounded semaphore reduces the chance that a programming error which
694causes the semaphore to be released more than it's acquired will go undetected.
695
696
697.. _event-objects:
698
699Event Objects
700-------------
701
702This is one of the simplest mechanisms for communication between threads: one
703thread signals an event and other threads wait for it.
704
705An event object manages an internal flag that can be set to true with the
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000706:meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
Georg Brandl8ec7f652007-08-15 14:28:01 +0000707:meth:`wait` method blocks until the flag is true.
708
709
710.. class:: Event()
711
712 The internal flag is initially false.
713
Georg Brandl3591a8f2009-07-26 14:44:23 +0000714 .. method:: is_set()
715 isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000716
Georg Brandl3591a8f2009-07-26 14:44:23 +0000717 Return true if and only if the internal flag is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
Facundo Batista47b66592010-01-25 06:15:01 +0000719 .. versionchanged:: 2.6
Georg Brandl52fa1722013-10-13 10:07:31 +0200720 Added ``is_set()`` spelling.
Facundo Batista47b66592010-01-25 06:15:01 +0000721
Georg Brandl3591a8f2009-07-26 14:44:23 +0000722 .. method:: set()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000723
Georg Brandl3591a8f2009-07-26 14:44:23 +0000724 Set the internal flag to true. All threads waiting for it to become true
725 are awakened. Threads that call :meth:`wait` once the flag is true will
726 not block at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
Georg Brandl3591a8f2009-07-26 14:44:23 +0000728 .. method:: clear()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729
Georg Brandl3591a8f2009-07-26 14:44:23 +0000730 Reset the internal flag to false. Subsequently, threads calling
731 :meth:`wait` will block until :meth:`.set` is called to set the internal
732 flag to true again.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000733
Georg Brandl3591a8f2009-07-26 14:44:23 +0000734 .. method:: wait([timeout])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735
Georg Brandl3591a8f2009-07-26 14:44:23 +0000736 Block until the internal flag is true. If the internal flag is true on
737 entry, return immediately. Otherwise, block until another thread calls
738 :meth:`.set` to set the flag to true, or until the optional timeout
739 occurs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000740
Georg Brandl3591a8f2009-07-26 14:44:23 +0000741 When the timeout argument is present and not ``None``, it should be a
742 floating point number specifying a timeout for the operation in seconds
743 (or fractions thereof).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000744
Georg Brandl3591a8f2009-07-26 14:44:23 +0000745 This method returns the internal flag on exit, so it will always return
746 ``True`` except if a timeout is given and the operation times out.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747
Georg Brandl3591a8f2009-07-26 14:44:23 +0000748 .. versionchanged:: 2.7
749 Previously, the method always returned ``None``.
Georg Brandlef660e82009-03-31 20:41:08 +0000750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
Georg Brandl8ec7f652007-08-15 14:28:01 +0000752.. _timer-objects:
753
754Timer Objects
755-------------
756
757This class represents an action that should be run only after a certain amount
758of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
759and as such also functions as an example of creating custom threads.
760
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300761Timers are started, as with threads, by calling their :meth:`~Timer.start`
762method. The timer can be stopped (before its action has begun) by calling the
763:meth:`~Timer.cancel` method. The interval the timer will wait before
764executing its action may not be exactly the same as the interval specified by
765the user.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000766
767For example::
768
769 def hello():
770 print "hello, world"
771
772 t = Timer(30.0, hello)
773 t.start() # after 30 seconds, "hello, world" will be printed
774
775
776.. class:: Timer(interval, function, args=[], kwargs={})
777
778 Create a timer that will run *function* with arguments *args* and keyword
779 arguments *kwargs*, after *interval* seconds have passed.
780
Georg Brandl3591a8f2009-07-26 14:44:23 +0000781 .. method:: cancel()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
Georg Brandl3591a8f2009-07-26 14:44:23 +0000783 Stop the timer, and cancel the execution of the timer's action. This will
784 only work if the timer is still in its waiting stage.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785
786
787.. _with-locks:
788
789Using locks, conditions, and semaphores in the :keyword:`with` statement
790------------------------------------------------------------------------
791
792All of the objects provided by this module that have :meth:`acquire` and
793:meth:`release` methods can be used as context managers for a :keyword:`with`
794statement. The :meth:`acquire` method will be called when the block is entered,
795and :meth:`release` will be called when the block is exited.
796
797Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
798:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
799:keyword:`with` statement context managers. For example::
800
Georg Brandl8ec7f652007-08-15 14:28:01 +0000801 import threading
802
803 some_rlock = threading.RLock()
804
805 with some_rlock:
806 print "some_rlock is locked while this executes"
807
Georg Brandl2e255512008-03-13 07:21:41 +0000808
809.. _threaded-imports:
810
811Importing in threaded code
812--------------------------
813
Georg Brandl837fbb02010-11-26 07:58:55 +0000814While the import machinery is thread-safe, there are two key restrictions on
815threaded imports due to inherent limitations in the way that thread-safety is
816provided:
Georg Brandl2e255512008-03-13 07:21:41 +0000817
818* Firstly, other than in the main module, an import should not have the
819 side effect of spawning a new thread and then waiting for that thread in
820 any way. Failing to abide by this restriction can lead to a deadlock if
821 the spawned thread directly or indirectly attempts to import a module.
822* Secondly, all import attempts must be completed before the interpreter
823 starts shutting itself down. This can be most easily achieved by only
824 performing imports from non-daemon threads created through the threading
825 module. Daemon threads and threads created directly with the thread
826 module will require some other form of synchronization to ensure they do
827 not attempt imports after system shutdown has commenced. Failure to
828 abide by this restriction will lead to intermittent exceptions and
829 crashes during interpreter shutdown (as the late imports attempt to
830 access machinery which is no longer in a valid state).