blob: 522ea2f99591fdb36cb59d3e0c0863b22fafce4a [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{threading} ---
Fred Drakebf5a6d21999-03-12 19:57:38 +00002 Higher-level threading interface}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drakebf5a6d21999-03-12 19:57:38 +00004\declaremodule{standard}{threading}
5\modulesynopsis{Higher-level threading interface.}
Fred Drakeb91e9341998-07-23 17:59:49 +00006
Andrew M. Kuchling16440e61998-07-20 13:46:10 +00007
Fred Drake9643c671998-07-27 22:06:12 +00008This module constructs higher-level threading interfaces on top of the
Fred Drakeffbe6871999-04-22 21:23:22 +00009lower level \refmodule{thread} module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000010
Fred Drake740f8002002-12-30 23:00:36 +000011The \refmodule[dummythreading]{dummy_threading} module is provided for
12situations where \module{threading} cannot be used because
13\refmodule{thread} is missing.
Guido van Rossum29692332002-12-30 22:34:10 +000014
Fred Drake11f89b72003-01-06 16:38:10 +000015This module defines the following functions and objects:
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000016
17\begin{funcdesc}{activeCount}{}
Guido van Rossumd8faa362007-04-27 19:54:29 +000018Return the number of \class{Thread} objects currently alive. The
19returned count is equal to the length of the list returned by
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000020\function{enumerate()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000021\end{funcdesc}
22
Guido van Rossumd8faa362007-04-27 19:54:29 +000023\begin{funcdescni}{Condition}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000024A factory function that returns a new condition variable object.
25A condition variable allows one or more threads to wait until they
26are notified by another thread.
Guido van Rossumd8faa362007-04-27 19:54:29 +000027\end{funcdescni}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000028
29\begin{funcdesc}{currentThread}{}
30Return the current \class{Thread} object, corresponding to the
31caller's thread of control. If the caller's thread of control was not
32created through the
33\module{threading} module, a dummy thread object with limited functionality
34is returned.
35\end{funcdesc}
36
37\begin{funcdesc}{enumerate}{}
Guido van Rossumd8faa362007-04-27 19:54:29 +000038Return a list of all \class{Thread} objects currently alive. The list
39includes daemonic threads, dummy thread objects created by
40\function{currentThread()}, and the main thread. It excludes
41terminated threads and threads that have not yet been started.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000042\end{funcdesc}
43
Guido van Rossumd8faa362007-04-27 19:54:29 +000044\begin{funcdescni}{Event}{}
Fred Drake12686782002-03-19 14:37:44 +000045A factory function that returns a new event object. An event manages
46a flag that can be set to true with the \method{set()} method and
47reset to false with the \method{clear()} method. The \method{wait()}
48method blocks until the flag is true.
Guido van Rossumd8faa362007-04-27 19:54:29 +000049\end{funcdescni}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000050
Jim Fultond15dc062004-07-14 19:11:50 +000051\begin{classdesc*}{local}{}
52A class that represents thread-local data. Thread-local data are data
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000053whose values are thread specific. To manage thread-local data, just
Jim Fultond15dc062004-07-14 19:11:50 +000054create an instance of \class{local} (or a subclass) and store
55attributes on it:
56
57\begin{verbatim}
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000058mydata = threading.local()
59mydata.x = 1
Jim Fultond15dc062004-07-14 19:11:50 +000060\end{verbatim}
61
62The instance's values will be different for separate threads.
63
64For more details and extensive examples, see the documentation string
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000065of the \module{_threading_local} module.
Jim Fultond15dc062004-07-14 19:11:50 +000066
67\versionadded{2.4}
68\end{classdesc*}
69
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000070\begin{funcdesc}{Lock}{}
71A factory function that returns a new primitive lock object. Once
72a thread has acquired it, subsequent attempts to acquire it block,
73until it is released; any thread may release it.
74\end{funcdesc}
75
76\begin{funcdesc}{RLock}{}
77A factory function that returns a new reentrant lock object.
78A reentrant lock must be released by the thread that acquired it.
79Once a thread has acquired a reentrant lock, the same thread may
80acquire it again without blocking; the thread must release it once
81for each time it has acquired it.
82\end{funcdesc}
83
Guido van Rossumd8faa362007-04-27 19:54:29 +000084\begin{funcdescni}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000085A factory function that returns a new semaphore object. A
86semaphore manages a counter representing the number of \method{release()}
87calls minus the number of \method{acquire()} calls, plus an initial value.
88The \method{acquire()} method blocks if necessary until it can return
Fred Drake31d833d2001-08-20 18:49:00 +000089without making the counter negative. If not given, \var{value} defaults to
901.
Guido van Rossumd8faa362007-04-27 19:54:29 +000091\end{funcdescni}
Fred Drake31d833d2001-08-20 18:49:00 +000092
93\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
94A factory function that returns a new bounded semaphore object. A bounded
95semaphore checks to make sure its current value doesn't exceed its initial
96value. If it does, \exception{ValueError} is raised. In most situations
97semaphores are used to guard resources with limited capacity. If the
98semaphore is released too many times it's a sign of a bug. If not given,
99\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000100\end{funcdesc}
101
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102\begin{classdesc*}{Thread}
Fred Drake12686782002-03-19 14:37:44 +0000103A class that represents a thread of control. This class can be safely
104subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +0000105\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000106
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107\begin{classdesc*}{Timer}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000108A thread that executes a function after a specified interval has passed.
109\end{classdesc*}
110
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000111\begin{funcdesc}{settrace}{func}
Fred Drake57288152003-06-29 18:12:23 +0000112Set a trace function\index{trace function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000113from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000114\function{sys.settrace()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000115method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000116\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000117\end{funcdesc}
118
119\begin{funcdesc}{setprofile}{func}
Fred Drake57288152003-06-29 18:12:23 +0000120Set a profile function\index{profile function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000121from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000122\function{sys.setprofile()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000123method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000124\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000125\end{funcdesc}
126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127\begin{funcdesc}{stack_size}{\optional{size}}
128Return the thread stack size used when creating new threads. The
129optional \var{size} argument specifies the stack size to be used for
130subsequently created threads, and must be 0 (use platform or
131configured default) or a positive integer value of at least 32,768 (32kB).
132If changing the thread stack size is unsupported, a \exception{ThreadError}
133is raised. If the specified stack size is invalid, a \exception{ValueError}
134is raised and the stack size is unmodified. 32kB is currently the minimum
135supported stack size value to guarantee sufficient stack space for the
136interpreter itself. Note that some platforms may have particular
137restrictions on values for the stack size, such as requiring a minimum
138stack size > 32kB or requiring allocation in multiples of the system
139memory page size - platform documentation should be referred to for
140more information (4kB pages are common; using multiples of 4096 for
141the stack size is the suggested approach in the absence of more
142specific information).
143Availability: Windows, systems with \POSIX{} threads.
144\versionadded{2.5}
145\end{funcdesc}
146
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000147Detailed interfaces for the objects are documented below.
148
149The design of this module is loosely based on Java's threading model.
150However, where Java makes locks and condition variables basic behavior
151of every object, they are separate objects in Python. Python's \class{Thread}
152class supports a subset of the behavior of Java's Thread class;
153currently, there are no priorities, no thread groups, and threads
154cannot be destroyed, stopped, suspended, resumed, or interrupted. The
155static methods of Java's Thread class, when implemented, are mapped to
156module-level functions.
157
158All of the methods described below are executed atomically.
159
Fred Drakebf5a6d21999-03-12 19:57:38 +0000160
161\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000162
163A primitive lock is a synchronization primitive that is not owned
164by a particular thread when locked. In Python, it is currently
165the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000166directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000167
168A primitive lock is in one of two states, ``locked'' or ``unlocked''.
169It is created in the unlocked state. It has two basic methods,
170\method{acquire()} and \method{release()}. When the state is
171unlocked, \method{acquire()} changes the state to locked and returns
172immediately. When the state is locked, \method{acquire()} blocks
173until a call to \method{release()} in another thread changes it to
174unlocked, then the \method{acquire()} call resets it to locked and
175returns. The \method{release()} method should only be called in the
176locked state; it changes the state to unlocked and returns
177immediately. When more than one thread is blocked in
178\method{acquire()} waiting for the state to turn to unlocked, only one
179thread proceeds when a \method{release()} call resets the state to
180unlocked; which one of the waiting threads proceeds is not defined,
181and may vary across implementations.
182
183All methods are executed atomically.
184
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185\begin{methoddesc}[Lock]{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000186Acquire a lock, blocking or non-blocking.
187
188When invoked without arguments, block until the lock is
Andrew M. Kuchling921879a2005-06-02 16:59:18 +0000189unlocked, then set it to locked, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000190
191When invoked with the \var{blocking} argument set to true, do the
192same thing as when called without arguments, and return true.
193
194When invoked with the \var{blocking} argument set to false, do not
195block. If a call without an argument would block, return false
196immediately; otherwise, do the same thing as when called
197without arguments, and return true.
198\end{methoddesc}
199
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200\begin{methoddesc}[Lock]{release}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000201Release a lock.
202
203When the lock is locked, reset it to unlocked, and return. If
204any other threads are blocked waiting for the lock to become
205unlocked, allow exactly one of them to proceed.
206
207Do not call this method when the lock is unlocked.
208
209There is no return value.
210\end{methoddesc}
211
Fred Drakebf5a6d21999-03-12 19:57:38 +0000212
213\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000214
215A reentrant lock is a synchronization primitive that may be
216acquired multiple times by the same thread. Internally, it uses
217the concepts of ``owning thread'' and ``recursion level'' in
218addition to the locked/unlocked state used by primitive locks. In
219the locked state, some thread owns the lock; in the unlocked
220state, no thread owns it.
221
222To lock the lock, a thread calls its \method{acquire()} method; this
223returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000224thread calls its \method{release()} method.
225\method{acquire()}/\method{release()} call pairs may be nested; only
226the final \method{release()} (the \method{release()} of the outermost
227pair) resets the lock to unlocked and allows another thread blocked in
228\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000229
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230\begin{methoddesc}[RLock]{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000231Acquire a lock, blocking or non-blocking.
232
233When invoked without arguments: if this thread already owns
234the lock, increment the recursion level by one, and return
235immediately. Otherwise, if another thread owns the lock,
236block until the lock is unlocked. Once the lock is unlocked
237(not owned by any thread), then grab ownership, set the
238recursion level to one, and return. If more than one thread
239is blocked waiting until the lock is unlocked, only one at a
240time will be able to grab ownership of the lock. There is no
241return value in this case.
242
243When invoked with the \var{blocking} argument set to true, do the
244same thing as when called without arguments, and return true.
245
246When invoked with the \var{blocking} argument set to false, do not
247block. If a call without an argument would block, return false
248immediately; otherwise, do the same thing as when called
249without arguments, and return true.
250\end{methoddesc}
251
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252\begin{methoddesc}[RLock]{release}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000253Release a lock, decrementing the recursion level. If after the
254decrement it is zero, reset the lock to unlocked (not owned by any
255thread), and if any other threads are blocked waiting for the lock to
256become unlocked, allow exactly one of them to proceed. If after the
257decrement the recursion level is still nonzero, the lock remains
258locked and owned by the calling thread.
259
260Only call this method when the calling thread owns the lock.
261Do not call this method when the lock is unlocked.
262
263There is no return value.
264\end{methoddesc}
265
Fred Drakebf5a6d21999-03-12 19:57:38 +0000266
267\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000268
269A condition variable is always associated with some kind of lock;
270this can be passed in or one will be created by default. (Passing
271one in is useful when several condition variables must share the
272same lock.)
273
274A condition variable has \method{acquire()} and \method{release()}
275methods that call the corresponding methods of the associated lock.
276It also has a \method{wait()} method, and \method{notify()} and
277\method{notifyAll()} methods. These three must only be called when
278the calling thread has acquired the lock.
279
280The \method{wait()} method releases the lock, and then blocks until it
281is awakened by a \method{notify()} or \method{notifyAll()} call for
282the same condition variable in another thread. Once awakened, it
283re-acquires the lock and returns. It is also possible to specify a
284timeout.
285
286The \method{notify()} method wakes up one of the threads waiting for
287the condition variable, if any are waiting. The \method{notifyAll()}
288method wakes up all threads waiting for the condition variable.
289
290Note: the \method{notify()} and \method{notifyAll()} methods don't
291release the lock; this means that the thread or threads awakened will
292not return from their \method{wait()} call immediately, but only when
293the thread that called \method{notify()} or \method{notifyAll()}
294finally relinquishes ownership of the lock.
295
296Tip: the typical programming style using condition variables uses the
297lock to synchronize access to some shared state; threads that are
298interested in a particular change of state call \method{wait()}
299repeatedly until they see the desired state, while threads that modify
300the state call \method{notify()} or \method{notifyAll()} when they
301change the state in such a way that it could possibly be a desired
302state for one of the waiters. For example, the following code is a
303generic producer-consumer situation with unlimited buffer capacity:
304
305\begin{verbatim}
306# Consume one item
307cv.acquire()
308while not an_item_is_available():
309 cv.wait()
310get_an_available_item()
311cv.release()
312
313# Produce one item
314cv.acquire()
315make_an_item_available()
316cv.notify()
317cv.release()
318\end{verbatim}
319
320To choose between \method{notify()} and \method{notifyAll()}, consider
321whether one state change can be interesting for only one or several
322waiting threads. E.g. in a typical producer-consumer situation,
323adding one item to the buffer only needs to wake up one consumer
324thread.
325
Fred Drakebf5a6d21999-03-12 19:57:38 +0000326\begin{classdesc}{Condition}{\optional{lock}}
327If the \var{lock} argument is given and not \code{None}, it must be a
328\class{Lock} or \class{RLock} object, and it is used as the underlying
329lock. Otherwise, a new \class{RLock} object is created and used as
330the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000331\end{classdesc}
332
333\begin{methoddesc}{acquire}{*args}
334Acquire the underlying lock.
335This method calls the corresponding method on the underlying
336lock; the return value is whatever that method returns.
337\end{methoddesc}
338
339\begin{methoddesc}{release}{}
340Release the underlying lock.
341This method calls the corresponding method on the underlying
342lock; there is no return value.
343\end{methoddesc}
344
Fred Drakebf5a6d21999-03-12 19:57:38 +0000345\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000346Wait until notified or until a timeout occurs.
347This must only be called when the calling thread has acquired the
348lock.
349
350This method releases the underlying lock, and then blocks until it is
351awakened by a \method{notify()} or \method{notifyAll()} call for the
352same condition variable in another thread, or until the optional
353timeout occurs. Once awakened or timed out, it re-acquires the lock
354and returns.
355
Fred Drakebf5a6d21999-03-12 19:57:38 +0000356When the \var{timeout} argument is present and not \code{None}, it
357should be a floating point number specifying a timeout for the
358operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000359
Fred Drakebf5a6d21999-03-12 19:57:38 +0000360When the underlying lock is an \class{RLock}, it is not released using
361its \method{release()} method, since this may not actually unlock the
362lock when it was acquired multiple times recursively. Instead, an
363internal interface of the \class{RLock} class is used, which really
364unlocks it even when it has been recursively acquired several times.
365Another internal interface is then used to restore the recursion level
366when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000367\end{methoddesc}
368
369\begin{methoddesc}{notify}{}
370Wake up a thread waiting on this condition, if any.
371This must only be called when the calling thread has acquired the
372lock.
373
374This method wakes up one of the threads waiting for the condition
375variable, if any are waiting; it is a no-op if no threads are waiting.
376
377The current implementation wakes up exactly one thread, if any are
378waiting. However, it's not safe to rely on this behavior. A future,
379optimized implementation may occasionally wake up more than one
380thread.
381
382Note: the awakened thread does not actually return from its
383\method{wait()} call until it can reacquire the lock. Since
384\method{notify()} does not release the lock, its caller should.
385\end{methoddesc}
386
387\begin{methoddesc}{notifyAll}{}
388Wake up all threads waiting on this condition. This method acts like
389\method{notify()}, but wakes up all waiting threads instead of one.
390\end{methoddesc}
391
Fred Drakebf5a6d21999-03-12 19:57:38 +0000392
393\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000394
395This is one of the oldest synchronization primitives in the history of
396computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000397Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
398\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000399
400A semaphore manages an internal counter which is decremented by each
401\method{acquire()} call and incremented by each \method{release()}
402call. The counter can never go below zero; when \method{acquire()}
403finds that it is zero, it blocks, waiting until some other thread
404calls \method{release()}.
405
Fred Drakebf5a6d21999-03-12 19:57:38 +0000406\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000407The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000408counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000409\end{classdesc}
410
Fred Drakebf5a6d21999-03-12 19:57:38 +0000411\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000412Acquire a semaphore.
413
414When invoked without arguments: if the internal counter is larger than
415zero on entry, decrement it by one and return immediately. If it is
416zero on entry, block, waiting until some other thread has called
417\method{release()} to make it larger than zero. This is done with
418proper interlocking so that if multiple \method{acquire()} calls are
419blocked, \method{release()} will wake exactly one of them up. The
420implementation may pick one at random, so the order in which blocked
421threads are awakened should not be relied on. There is no return
422value in this case.
423
Fred Drakebf5a6d21999-03-12 19:57:38 +0000424When invoked with \var{blocking} set to true, do the same thing as
425when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000426
Fred Drakebf5a6d21999-03-12 19:57:38 +0000427When invoked with \var{blocking} set to false, do not block. If a
428call without an argument would block, return false immediately;
429otherwise, do the same thing as when called without arguments, and
430return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000431\end{methoddesc}
432
433\begin{methoddesc}{release}{}
434Release a semaphore,
435incrementing the internal counter by one. When it was zero on
436entry and another thread is waiting for it to become larger
437than zero again, wake up that thread.
438\end{methoddesc}
439
Fred Drakebf5a6d21999-03-12 19:57:38 +0000440
Fred Drake31d833d2001-08-20 18:49:00 +0000441\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
442
443Semaphores are often used to guard resources with limited capacity, for
444example, a database server. In any situation where the size of the resource
445size is fixed, you should use a bounded semaphore. Before spawning any
446worker threads, your main thread would initialize the semaphore:
447
448\begin{verbatim}
449maxconnections = 5
450...
451pool_sema = BoundedSemaphore(value=maxconnections)
452\end{verbatim}
453
454Once spawned, worker threads call the semaphore's acquire and release
455methods when they need to connect to the server:
456
457\begin{verbatim}
458pool_sema.acquire()
459conn = connectdb()
460... use connection ...
461conn.close()
462pool_sema.release()
463\end{verbatim}
464
465The use of a bounded semaphore reduces the chance that a programming error
466which causes the semaphore to be released more than it's acquired will go
467undetected.
468
Fred Drake12686782002-03-19 14:37:44 +0000469
Fred Drakebf5a6d21999-03-12 19:57:38 +0000470\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000471
472This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000473threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000474
475An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000476the \method{set()} method and reset to false with the \method{clear()}
477method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000478
479
480\begin{classdesc}{Event}{}
481The internal flag is initially false.
482\end{classdesc}
483
484\begin{methoddesc}{isSet}{}
485Return true if and only if the internal flag is true.
486\end{methoddesc}
487
488\begin{methoddesc}{set}{}
489Set the internal flag to true.
490All threads waiting for it to become true are awakened.
491Threads that call \method{wait()} once the flag is true will not block
492at all.
493\end{methoddesc}
494
495\begin{methoddesc}{clear}{}
496Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000497Subsequently, threads calling \method{wait()} will block until
498\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000499\end{methoddesc}
500
Fred Drakebf5a6d21999-03-12 19:57:38 +0000501\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000502Block until the internal flag is true.
503If the internal flag is true on entry, return immediately. Otherwise,
504block until another thread calls \method{set()} to set the flag to
505true, or until the optional timeout occurs.
506
507When the timeout argument is present and not \code{None}, it should be a
508floating point number specifying a timeout for the operation in
509seconds (or fractions thereof).
510\end{methoddesc}
511
Fred Drakebf5a6d21999-03-12 19:57:38 +0000512
513\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000514
515This class represents an activity that is run in a separate thread
516of control. There are two ways to specify the activity: by
517passing a callable object to the constructor, or by overriding the
518\method{run()} method in a subclass. No other methods (except for the
519constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000520\emph{only} override the \method{__init__()} and \method{run()}
521methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000522
523Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000524calling the thread's \method{start()} method. This invokes the
525\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000526
527Once the thread's activity is started, the thread is considered
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528'alive'. It stops being alive when its \method{run()} method terminates
529-- either normally, or by raising an unhandled exception. The
530\method{isAlive()} method tests whether the thread is alive.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000531
Fred Drakebf5a6d21999-03-12 19:57:38 +0000532Other threads can call a thread's \method{join()} method. This blocks
533the calling thread until the thread whose \method{join()} method is
534called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000535
536A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000537set with the \method{setName()} method, and retrieved with the
538\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000539
540A thread can be flagged as a ``daemon thread''. The significance
541of this flag is that the entire Python program exits when only
542daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000543creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000544method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000545
546There is a ``main thread'' object; this corresponds to the
547initial thread of control in the Python program. It is not a
548daemon thread.
549
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550There is the possibility that ``dummy thread objects'' are created.
551These are thread objects corresponding to ``alien threads'', which
552are threads of control started outside the threading module, such as
553directly from C code. Dummy thread objects have limited
554functionality; they are always considered alive and daemonic, and
555cannot be \method{join()}ed. They are never deleted, since it is
556impossible to detect the termination of alien threads.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000557
558
559\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000560 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000561This constructor should always be called with keyword
562arguments. Arguments are:
563
Fred Drakec19f3922001-05-31 20:24:07 +0000564\var{group} should be \code{None}; reserved for future extension when
565a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000566
Fred Drakec19f3922001-05-31 20:24:07 +0000567\var{target} is the callable object to be invoked by the
568\method{run()} method. Defaults to \code{None}, meaning nothing is
569called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000570
Fred Drakec19f3922001-05-31 20:24:07 +0000571\var{name} is the thread name. By default, a unique name is
572constructed of the form ``Thread-\var{N}'' where \var{N} is a small
573decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000574
Fred Drakec19f3922001-05-31 20:24:07 +0000575\var{args} is the argument tuple for the target invocation. Defaults
576to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000577
Fred Drakec19f3922001-05-31 20:24:07 +0000578\var{kwargs} is a dictionary of keyword arguments for the target
579invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000580
581If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000582to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000583before doing anything else to the thread.
584\end{classdesc}
585
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000586\begin{methoddesc}{start}{}
587Start the thread's activity.
588
589This must be called at most once per thread object. It
590arranges for the object's \method{run()} method to be invoked in a
591separate thread of control.
592\end{methoddesc}
593
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000594\begin{methoddesc}{run}{}
595Method representing the thread's activity.
596
597You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000598\method{run()} method invokes the callable object passed to the
599object's constructor as the \var{target} argument, if any, with
600sequential and keyword arguments taken from the \var{args} and
601\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000602\end{methoddesc}
603
Fred Drakebf5a6d21999-03-12 19:57:38 +0000604\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000605Wait until the thread terminates.
606This blocks the calling thread until the thread whose \method{join()}
607method is called terminates -- either normally or through an
608unhandled exception -- or until the optional timeout occurs.
609
Fred Drake12686782002-03-19 14:37:44 +0000610When the \var{timeout} argument is present and not \code{None}, it
611should be a floating point number specifying a timeout for the
Georg Brandl75d51062005-07-17 21:00:26 +0000612operation in seconds (or fractions thereof). As \method{join()} always
613returns \code{None}, you must call \method{isAlive()} to decide whether
614a timeout happened.
615
616When the \var{timeout} argument is not present or \code{None}, the
617operation will block until the thread terminates.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000618
619A thread can be \method{join()}ed many times.
620
621A thread cannot join itself because this would cause a
622deadlock.
623
624It is an error to attempt to \method{join()} a thread before it has
625been started.
626\end{methoddesc}
627
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000628\begin{methoddesc}{getName}{}
629Return the thread's name.
630\end{methoddesc}
631
632\begin{methoddesc}{setName}{name}
633Set the thread's name.
634
635The name is a string used for identification purposes only.
636It has no semantics. Multiple threads may be given the same
637name. The initial name is set by the constructor.
638\end{methoddesc}
639
640\begin{methoddesc}{isAlive}{}
641Return whether the thread is alive.
642
643Roughly, a thread is alive from the moment the \method{start()} method
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644returns until its \method{run()} method terminates. The module
645function \function{enumerate()} returns a list of all alive threads.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000646\end{methoddesc}
647
648\begin{methoddesc}{isDaemon}{}
649Return the thread's daemon flag.
650\end{methoddesc}
651
652\begin{methoddesc}{setDaemon}{daemonic}
653Set the thread's daemon flag to the Boolean value \var{daemonic}.
654This must be called before \method{start()} is called.
655
656The initial value is inherited from the creating thread.
657
Guido van Rossumd8faa362007-04-27 19:54:29 +0000658The entire Python program exits when no alive non-daemon threads are
659left.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000660\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000661
662
663\subsection{Timer Objects \label{timer-objects}}
664
Fred Drake12686782002-03-19 14:37:44 +0000665This class represents an action that should be run only after a
666certain amount of time has passed --- a timer. \class{Timer} is a
667subclass of \class{Thread} and as such also functions as an example of
668creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000669
Fred Drake12686782002-03-19 14:37:44 +0000670Timers are started, as with threads, by calling their \method{start()}
671method. The timer can be stopped (before its action has begun) by
672calling the \method{cancel()} method. The interval the timer will
673wait before executing its action may not be exactly the same as the
674interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000675
676For example:
677\begin{verbatim}
678def hello():
679 print "hello, world"
680
681t = Timer(30.0, hello)
682t.start() # after 30 seconds, "hello, world" will be printed
683\end{verbatim}
684
685\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
686Create a timer that will run \var{function} with arguments \var{args} and
687keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
688\end{classdesc}
689
690\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000691Stop the timer, and cancel the execution of the timer's action. This
692will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000693\end{methoddesc}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694
695\subsection{Using locks, conditions, and semaphores in the \keyword{with}
696statement \label{with-locks}}
697
698All of the objects provided by this module that have \method{acquire()} and
699\method{release()} methods can be used as context managers for a \keyword{with}
700statement. The \method{acquire()} method will be called when the block is
701entered, and \method{release()} will be called when the block is exited.
702
703Currently, \class{Lock}, \class{RLock}, \class{Condition}, \class{Semaphore},
704and \class{BoundedSemaphore} objects may be used as \keyword{with}
705statement context managers. For example:
706
707\begin{verbatim}
708from __future__ import with_statement
709import threading
710
711some_rlock = threading.RLock()
712
713with some_rlock:
714 print "some_rlock is locked while this executes"
715\end{verbatim}
716