blob: 033475020ae9a9c4e90377d868b6506a236a58e3 [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}{}
18Return the number of currently active \class{Thread} objects.
19The returned count is equal to the length of the list returned by
20\function{enumerate()}.
21A function that returns the number of currently active threads.
22\end{funcdesc}
23
24\begin{funcdesc}{Condition}{}
25A factory function that returns a new condition variable object.
26A condition variable allows one or more threads to wait until they
27are notified by another thread.
28\end{funcdesc}
29
30\begin{funcdesc}{currentThread}{}
31Return the current \class{Thread} object, corresponding to the
32caller's thread of control. If the caller's thread of control was not
33created through the
34\module{threading} module, a dummy thread object with limited functionality
35is returned.
36\end{funcdesc}
37
38\begin{funcdesc}{enumerate}{}
39Return a list of all currently active \class{Thread} objects.
40The list includes daemonic threads, dummy thread objects created
41by \function{currentThread()}, and the main thread. It excludes terminated
42threads and threads that have not yet been started.
43\end{funcdesc}
44
45\begin{funcdesc}{Event}{}
Fred Drake12686782002-03-19 14:37:44 +000046A factory function that returns a new event object. An event manages
47a flag that can be set to true with the \method{set()} method and
48reset to false with the \method{clear()} method. The \method{wait()}
49method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000050\end{funcdesc}
51
Jim Fultond15dc062004-07-14 19:11:50 +000052\begin{classdesc*}{local}{}
53A class that represents thread-local data. Thread-local data are data
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000054whose values are thread specific. To manage thread-local data, just
Jim Fultond15dc062004-07-14 19:11:50 +000055create an instance of \class{local} (or a subclass) and store
56attributes on it:
57
58\begin{verbatim}
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000059mydata = threading.local()
60mydata.x = 1
Jim Fultond15dc062004-07-14 19:11:50 +000061\end{verbatim}
62
63The instance's values will be different for separate threads.
64
65For more details and extensive examples, see the documentation string
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000066of the \module{_threading_local} module.
Jim Fultond15dc062004-07-14 19:11:50 +000067
68\versionadded{2.4}
69\end{classdesc*}
70
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000071\begin{funcdesc}{Lock}{}
72A factory function that returns a new primitive lock object. Once
73a thread has acquired it, subsequent attempts to acquire it block,
74until it is released; any thread may release it.
75\end{funcdesc}
76
77\begin{funcdesc}{RLock}{}
78A factory function that returns a new reentrant lock object.
79A reentrant lock must be released by the thread that acquired it.
80Once a thread has acquired a reentrant lock, the same thread may
81acquire it again without blocking; the thread must release it once
82for each time it has acquired it.
83\end{funcdesc}
84
Fred Drake31d833d2001-08-20 18:49:00 +000085\begin{funcdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000086A factory function that returns a new semaphore object. A
87semaphore manages a counter representing the number of \method{release()}
88calls minus the number of \method{acquire()} calls, plus an initial value.
89The \method{acquire()} method blocks if necessary until it can return
Fred Drake31d833d2001-08-20 18:49:00 +000090without making the counter negative. If not given, \var{value} defaults to
911.
92\end{funcdesc}
93
94\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
95A factory function that returns a new bounded semaphore object. A bounded
96semaphore checks to make sure its current value doesn't exceed its initial
97value. If it does, \exception{ValueError} is raised. In most situations
98semaphores are used to guard resources with limited capacity. If the
99semaphore is released too many times it's a sign of a bug. If not given,
100\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000101\end{funcdesc}
102
Fred Drakec19f3922001-05-31 20:24:07 +0000103\begin{classdesc*}{Thread}{}
Fred Drake12686782002-03-19 14:37:44 +0000104A class that represents a thread of control. This class can be safely
105subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +0000106\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000107
Martin v. Löwis44f86962001-09-05 13:44:54 +0000108\begin{classdesc*}{Timer}{}
109A thread that executes a function after a specified interval has passed.
110\end{classdesc*}
111
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000112\begin{funcdesc}{settrace}{func}
Fred Drake57288152003-06-29 18:12:23 +0000113Set a trace function\index{trace function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000114from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000115\function{sys.settrace()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000116method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000117\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000118\end{funcdesc}
119
120\begin{funcdesc}{setprofile}{func}
Fred Drake57288152003-06-29 18:12:23 +0000121Set a profile function\index{profile function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000122from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000123\function{sys.setprofile()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000124method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000125\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000126\end{funcdesc}
127
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000128\begin{funcdesc}{stack_size}{\optional{size}}
129Return the thread stack size used when creating new threads. The
130optional \var{size} argument specifies the stack size to be used for
131subsequently created threads, and must be 0 (use platform or
132configured default) or a positive integer value of at least 32,768 (32kB).
133If changing the thread stack size is unsupported, a \exception{ThreadError}
134is raised. If the specified stack size is invalid, a \exception{ValueError}
135is raised and the stack size is unmodified. 32kB is currently the minimum
136supported stack size value to guarantee sufficient stack space for the
137interpreter itself. Note that some platforms may have particular
138restrictions on values for the stack size, such as requiring a minimum
139stack size > 32kB or requiring allocation in multiples of the system
140memory page size - platform documentation should be referred to for
141more information (4kB pages are common; using multiples of 4096 for
142the stack size is the suggested approach in the absence of more
143specific information).
144Availability: Windows, systems with \POSIX{} threads.
145\versionadded{2.5}
146\end{funcdesc}
147
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000148Detailed interfaces for the objects are documented below.
149
150The design of this module is loosely based on Java's threading model.
151However, where Java makes locks and condition variables basic behavior
152of every object, they are separate objects in Python. Python's \class{Thread}
153class supports a subset of the behavior of Java's Thread class;
154currently, there are no priorities, no thread groups, and threads
155cannot be destroyed, stopped, suspended, resumed, or interrupted. The
156static methods of Java's Thread class, when implemented, are mapped to
157module-level functions.
158
159All of the methods described below are executed atomically.
160
Fred Drakebf5a6d21999-03-12 19:57:38 +0000161
162\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000163
164A primitive lock is a synchronization primitive that is not owned
165by a particular thread when locked. In Python, it is currently
166the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000167directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000168
169A primitive lock is in one of two states, ``locked'' or ``unlocked''.
170It is created in the unlocked state. It has two basic methods,
171\method{acquire()} and \method{release()}. When the state is
172unlocked, \method{acquire()} changes the state to locked and returns
173immediately. When the state is locked, \method{acquire()} blocks
174until a call to \method{release()} in another thread changes it to
175unlocked, then the \method{acquire()} call resets it to locked and
176returns. The \method{release()} method should only be called in the
177locked state; it changes the state to unlocked and returns
178immediately. When more than one thread is blocked in
179\method{acquire()} waiting for the state to turn to unlocked, only one
180thread proceeds when a \method{release()} call resets the state to
181unlocked; which one of the waiting threads proceeds is not defined,
182and may vary across implementations.
183
184All methods are executed atomically.
185
Fred Drakebf5a6d21999-03-12 19:57:38 +0000186\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000187Acquire a lock, blocking or non-blocking.
188
189When invoked without arguments, block until the lock is
Andrew M. Kuchling921879a2005-06-02 16:59:18 +0000190unlocked, then set it to locked, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000191
192When invoked with the \var{blocking} argument set to true, do the
193same thing as when called without arguments, and return true.
194
195When invoked with the \var{blocking} argument set to false, do not
196block. If a call without an argument would block, return false
197immediately; otherwise, do the same thing as when called
198without arguments, and return true.
199\end{methoddesc}
200
201\begin{methoddesc}{release}{}
202Release a lock.
203
204When the lock is locked, reset it to unlocked, and return. If
205any other threads are blocked waiting for the lock to become
206unlocked, allow exactly one of them to proceed.
207
208Do not call this method when the lock is unlocked.
209
210There is no return value.
211\end{methoddesc}
212
Fred Drakebf5a6d21999-03-12 19:57:38 +0000213
214\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000215
216A reentrant lock is a synchronization primitive that may be
217acquired multiple times by the same thread. Internally, it uses
218the concepts of ``owning thread'' and ``recursion level'' in
219addition to the locked/unlocked state used by primitive locks. In
220the locked state, some thread owns the lock; in the unlocked
221state, no thread owns it.
222
223To lock the lock, a thread calls its \method{acquire()} method; this
224returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000225thread calls its \method{release()} method.
226\method{acquire()}/\method{release()} call pairs may be nested; only
227the final \method{release()} (the \method{release()} of the outermost
228pair) resets the lock to unlocked and allows another thread blocked in
229\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000230
Fred Drakebf5a6d21999-03-12 19:57:38 +0000231\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000232Acquire a lock, blocking or non-blocking.
233
234When invoked without arguments: if this thread already owns
235the lock, increment the recursion level by one, and return
236immediately. Otherwise, if another thread owns the lock,
237block until the lock is unlocked. Once the lock is unlocked
238(not owned by any thread), then grab ownership, set the
239recursion level to one, and return. If more than one thread
240is blocked waiting until the lock is unlocked, only one at a
241time will be able to grab ownership of the lock. There is no
242return value in this case.
243
244When invoked with the \var{blocking} argument set to true, do the
245same thing as when called without arguments, and return true.
246
247When invoked with the \var{blocking} argument set to false, do not
248block. If a call without an argument would block, return false
249immediately; otherwise, do the same thing as when called
250without arguments, and return true.
251\end{methoddesc}
252
253\begin{methoddesc}{release}{}
254Release a lock, decrementing the recursion level. If after the
255decrement it is zero, reset the lock to unlocked (not owned by any
256thread), and if any other threads are blocked waiting for the lock to
257become unlocked, allow exactly one of them to proceed. If after the
258decrement the recursion level is still nonzero, the lock remains
259locked and owned by the calling thread.
260
261Only call this method when the calling thread owns the lock.
262Do not call this method when the lock is unlocked.
263
264There is no return value.
265\end{methoddesc}
266
Fred Drakebf5a6d21999-03-12 19:57:38 +0000267
268\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000269
270A condition variable is always associated with some kind of lock;
271this can be passed in or one will be created by default. (Passing
272one in is useful when several condition variables must share the
273same lock.)
274
275A condition variable has \method{acquire()} and \method{release()}
276methods that call the corresponding methods of the associated lock.
277It also has a \method{wait()} method, and \method{notify()} and
278\method{notifyAll()} methods. These three must only be called when
279the calling thread has acquired the lock.
280
281The \method{wait()} method releases the lock, and then blocks until it
282is awakened by a \method{notify()} or \method{notifyAll()} call for
283the same condition variable in another thread. Once awakened, it
284re-acquires the lock and returns. It is also possible to specify a
285timeout.
286
287The \method{notify()} method wakes up one of the threads waiting for
288the condition variable, if any are waiting. The \method{notifyAll()}
289method wakes up all threads waiting for the condition variable.
290
291Note: the \method{notify()} and \method{notifyAll()} methods don't
292release the lock; this means that the thread or threads awakened will
293not return from their \method{wait()} call immediately, but only when
294the thread that called \method{notify()} or \method{notifyAll()}
295finally relinquishes ownership of the lock.
296
297Tip: the typical programming style using condition variables uses the
298lock to synchronize access to some shared state; threads that are
299interested in a particular change of state call \method{wait()}
300repeatedly until they see the desired state, while threads that modify
301the state call \method{notify()} or \method{notifyAll()} when they
302change the state in such a way that it could possibly be a desired
303state for one of the waiters. For example, the following code is a
304generic producer-consumer situation with unlimited buffer capacity:
305
306\begin{verbatim}
307# Consume one item
308cv.acquire()
309while not an_item_is_available():
310 cv.wait()
311get_an_available_item()
312cv.release()
313
314# Produce one item
315cv.acquire()
316make_an_item_available()
317cv.notify()
318cv.release()
319\end{verbatim}
320
321To choose between \method{notify()} and \method{notifyAll()}, consider
322whether one state change can be interesting for only one or several
323waiting threads. E.g. in a typical producer-consumer situation,
324adding one item to the buffer only needs to wake up one consumer
325thread.
326
Fred Drakebf5a6d21999-03-12 19:57:38 +0000327\begin{classdesc}{Condition}{\optional{lock}}
328If the \var{lock} argument is given and not \code{None}, it must be a
329\class{Lock} or \class{RLock} object, and it is used as the underlying
330lock. Otherwise, a new \class{RLock} object is created and used as
331the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000332\end{classdesc}
333
334\begin{methoddesc}{acquire}{*args}
335Acquire the underlying lock.
336This method calls the corresponding method on the underlying
337lock; the return value is whatever that method returns.
338\end{methoddesc}
339
340\begin{methoddesc}{release}{}
341Release the underlying lock.
342This method calls the corresponding method on the underlying
343lock; there is no return value.
344\end{methoddesc}
345
Fred Drakebf5a6d21999-03-12 19:57:38 +0000346\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000347Wait until notified or until a timeout occurs.
348This must only be called when the calling thread has acquired the
349lock.
350
351This method releases the underlying lock, and then blocks until it is
352awakened by a \method{notify()} or \method{notifyAll()} call for the
353same condition variable in another thread, or until the optional
354timeout occurs. Once awakened or timed out, it re-acquires the lock
355and returns.
356
Fred Drakebf5a6d21999-03-12 19:57:38 +0000357When the \var{timeout} argument is present and not \code{None}, it
358should be a floating point number specifying a timeout for the
359operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000360
Fred Drakebf5a6d21999-03-12 19:57:38 +0000361When the underlying lock is an \class{RLock}, it is not released using
362its \method{release()} method, since this may not actually unlock the
363lock when it was acquired multiple times recursively. Instead, an
364internal interface of the \class{RLock} class is used, which really
365unlocks it even when it has been recursively acquired several times.
366Another internal interface is then used to restore the recursion level
367when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000368\end{methoddesc}
369
370\begin{methoddesc}{notify}{}
371Wake up a thread waiting on this condition, if any.
372This must only be called when the calling thread has acquired the
373lock.
374
375This method wakes up one of the threads waiting for the condition
376variable, if any are waiting; it is a no-op if no threads are waiting.
377
378The current implementation wakes up exactly one thread, if any are
379waiting. However, it's not safe to rely on this behavior. A future,
380optimized implementation may occasionally wake up more than one
381thread.
382
383Note: the awakened thread does not actually return from its
384\method{wait()} call until it can reacquire the lock. Since
385\method{notify()} does not release the lock, its caller should.
386\end{methoddesc}
387
388\begin{methoddesc}{notifyAll}{}
389Wake up all threads waiting on this condition. This method acts like
390\method{notify()}, but wakes up all waiting threads instead of one.
391\end{methoddesc}
392
Fred Drakebf5a6d21999-03-12 19:57:38 +0000393
394\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000395
396This is one of the oldest synchronization primitives in the history of
397computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000398Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
399\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000400
401A semaphore manages an internal counter which is decremented by each
402\method{acquire()} call and incremented by each \method{release()}
403call. The counter can never go below zero; when \method{acquire()}
404finds that it is zero, it blocks, waiting until some other thread
405calls \method{release()}.
406
Fred Drakebf5a6d21999-03-12 19:57:38 +0000407\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000408The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000409counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000410\end{classdesc}
411
Fred Drakebf5a6d21999-03-12 19:57:38 +0000412\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000413Acquire a semaphore.
414
415When invoked without arguments: if the internal counter is larger than
416zero on entry, decrement it by one and return immediately. If it is
417zero on entry, block, waiting until some other thread has called
418\method{release()} to make it larger than zero. This is done with
419proper interlocking so that if multiple \method{acquire()} calls are
420blocked, \method{release()} will wake exactly one of them up. The
421implementation may pick one at random, so the order in which blocked
422threads are awakened should not be relied on. There is no return
423value in this case.
424
Fred Drakebf5a6d21999-03-12 19:57:38 +0000425When invoked with \var{blocking} set to true, do the same thing as
426when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000427
Fred Drakebf5a6d21999-03-12 19:57:38 +0000428When invoked with \var{blocking} set to false, do not block. If a
429call without an argument would block, return false immediately;
430otherwise, do the same thing as when called without arguments, and
431return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000432\end{methoddesc}
433
434\begin{methoddesc}{release}{}
435Release a semaphore,
436incrementing the internal counter by one. When it was zero on
437entry and another thread is waiting for it to become larger
438than zero again, wake up that thread.
439\end{methoddesc}
440
Fred Drakebf5a6d21999-03-12 19:57:38 +0000441
Fred Drake31d833d2001-08-20 18:49:00 +0000442\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
443
444Semaphores are often used to guard resources with limited capacity, for
445example, a database server. In any situation where the size of the resource
446size is fixed, you should use a bounded semaphore. Before spawning any
447worker threads, your main thread would initialize the semaphore:
448
449\begin{verbatim}
450maxconnections = 5
451...
452pool_sema = BoundedSemaphore(value=maxconnections)
453\end{verbatim}
454
455Once spawned, worker threads call the semaphore's acquire and release
456methods when they need to connect to the server:
457
458\begin{verbatim}
459pool_sema.acquire()
460conn = connectdb()
461... use connection ...
462conn.close()
463pool_sema.release()
464\end{verbatim}
465
466The use of a bounded semaphore reduces the chance that a programming error
467which causes the semaphore to be released more than it's acquired will go
468undetected.
469
Fred Drake12686782002-03-19 14:37:44 +0000470
Fred Drakebf5a6d21999-03-12 19:57:38 +0000471\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000472
473This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000474threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000475
476An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000477the \method{set()} method and reset to false with the \method{clear()}
478method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000479
480
481\begin{classdesc}{Event}{}
482The internal flag is initially false.
483\end{classdesc}
484
485\begin{methoddesc}{isSet}{}
486Return true if and only if the internal flag is true.
487\end{methoddesc}
488
489\begin{methoddesc}{set}{}
490Set the internal flag to true.
491All threads waiting for it to become true are awakened.
492Threads that call \method{wait()} once the flag is true will not block
493at all.
494\end{methoddesc}
495
496\begin{methoddesc}{clear}{}
497Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000498Subsequently, threads calling \method{wait()} will block until
499\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000500\end{methoddesc}
501
Fred Drakebf5a6d21999-03-12 19:57:38 +0000502\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000503Block until the internal flag is true.
504If the internal flag is true on entry, return immediately. Otherwise,
505block until another thread calls \method{set()} to set the flag to
506true, or until the optional timeout occurs.
507
508When the timeout argument is present and not \code{None}, it should be a
509floating point number specifying a timeout for the operation in
510seconds (or fractions thereof).
511\end{methoddesc}
512
Fred Drakebf5a6d21999-03-12 19:57:38 +0000513
514\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000515
516This class represents an activity that is run in a separate thread
517of control. There are two ways to specify the activity: by
518passing a callable object to the constructor, or by overriding the
519\method{run()} method in a subclass. No other methods (except for the
520constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000521\emph{only} override the \method{__init__()} and \method{run()}
522methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000523
524Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000525calling the thread's \method{start()} method. This invokes the
526\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000527
528Once the thread's activity is started, the thread is considered
529'alive' and 'active' (these concepts are almost, but not quite
530exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000531vague). It stops being alive and active when its \method{run()}
532method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000533exception. The \method{isAlive()} method tests whether the thread is
534alive.
535
Fred Drakebf5a6d21999-03-12 19:57:38 +0000536Other threads can call a thread's \method{join()} method. This blocks
537the calling thread until the thread whose \method{join()} method is
538called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000539
540A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000541set with the \method{setName()} method, and retrieved with the
542\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000543
544A thread can be flagged as a ``daemon thread''. The significance
545of this flag is that the entire Python program exits when only
546daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000547creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000548method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000549
550There is a ``main thread'' object; this corresponds to the
551initial thread of control in the Python program. It is not a
552daemon thread.
553
554There is the possibility that ``dummy thread objects'' are
555created. These are thread objects corresponding to ``alien
556threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000557threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000558have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000559active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000560deleted, since it is impossible to detect the termination of alien
561threads.
562
563
564\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000565 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000566This constructor should always be called with keyword
567arguments. Arguments are:
568
Fred Drakec19f3922001-05-31 20:24:07 +0000569\var{group} should be \code{None}; reserved for future extension when
570a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000571
Fred Drakec19f3922001-05-31 20:24:07 +0000572\var{target} is the callable object to be invoked by the
573\method{run()} method. Defaults to \code{None}, meaning nothing is
574called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000575
Fred Drakec19f3922001-05-31 20:24:07 +0000576\var{name} is the thread name. By default, a unique name is
577constructed of the form ``Thread-\var{N}'' where \var{N} is a small
578decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000579
Fred Drakec19f3922001-05-31 20:24:07 +0000580\var{args} is the argument tuple for the target invocation. Defaults
581to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000582
Fred Drakec19f3922001-05-31 20:24:07 +0000583\var{kwargs} is a dictionary of keyword arguments for the target
584invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000585
586If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000587to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000588before doing anything else to the thread.
589\end{classdesc}
590
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000591\begin{methoddesc}{start}{}
592Start the thread's activity.
593
594This must be called at most once per thread object. It
595arranges for the object's \method{run()} method to be invoked in a
596separate thread of control.
597\end{methoddesc}
598
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000599\begin{methoddesc}{run}{}
600Method representing the thread's activity.
601
602You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000603\method{run()} method invokes the callable object passed to the
604object's constructor as the \var{target} argument, if any, with
605sequential and keyword arguments taken from the \var{args} and
606\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000607\end{methoddesc}
608
Fred Drakebf5a6d21999-03-12 19:57:38 +0000609\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000610Wait until the thread terminates.
611This blocks the calling thread until the thread whose \method{join()}
612method is called terminates -- either normally or through an
613unhandled exception -- or until the optional timeout occurs.
614
Fred Drake12686782002-03-19 14:37:44 +0000615When the \var{timeout} argument is present and not \code{None}, it
616should be a floating point number specifying a timeout for the
Georg Brandl75d51062005-07-17 21:00:26 +0000617operation in seconds (or fractions thereof). As \method{join()} always
618returns \code{None}, you must call \method{isAlive()} to decide whether
619a timeout happened.
620
621When the \var{timeout} argument is not present or \code{None}, the
622operation will block until the thread terminates.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000623
624A thread can be \method{join()}ed many times.
625
626A thread cannot join itself because this would cause a
627deadlock.
628
629It is an error to attempt to \method{join()} a thread before it has
630been started.
631\end{methoddesc}
632
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000633\begin{methoddesc}{getName}{}
634Return the thread's name.
635\end{methoddesc}
636
637\begin{methoddesc}{setName}{name}
638Set the thread's name.
639
640The name is a string used for identification purposes only.
641It has no semantics. Multiple threads may be given the same
642name. The initial name is set by the constructor.
643\end{methoddesc}
644
645\begin{methoddesc}{isAlive}{}
646Return whether the thread is alive.
647
648Roughly, a thread is alive from the moment the \method{start()} method
649returns until its \method{run()} method terminates.
650\end{methoddesc}
651
652\begin{methoddesc}{isDaemon}{}
653Return the thread's daemon flag.
654\end{methoddesc}
655
656\begin{methoddesc}{setDaemon}{daemonic}
657Set the thread's daemon flag to the Boolean value \var{daemonic}.
658This must be called before \method{start()} is called.
659
660The initial value is inherited from the creating thread.
661
662The entire Python program exits when no active non-daemon
663threads are left.
664\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000665
666
667\subsection{Timer Objects \label{timer-objects}}
668
Fred Drake12686782002-03-19 14:37:44 +0000669This class represents an action that should be run only after a
670certain amount of time has passed --- a timer. \class{Timer} is a
671subclass of \class{Thread} and as such also functions as an example of
672creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000673
Fred Drake12686782002-03-19 14:37:44 +0000674Timers are started, as with threads, by calling their \method{start()}
675method. The timer can be stopped (before its action has begun) by
676calling the \method{cancel()} method. The interval the timer will
677wait before executing its action may not be exactly the same as the
678interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000679
680For example:
681\begin{verbatim}
682def hello():
683 print "hello, world"
684
685t = Timer(30.0, hello)
686t.start() # after 30 seconds, "hello, world" will be printed
687\end{verbatim}
688
689\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
690Create a timer that will run \var{function} with arguments \var{args} and
691keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
692\end{classdesc}
693
694\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000695Stop the timer, and cancel the execution of the timer's action. This
696will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000697\end{methoddesc}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698
699\subsection{Using locks, conditions, and semaphores in the \keyword{with}
700statement \label{with-locks}}
701
702All of the objects provided by this module that have \method{acquire()} and
703\method{release()} methods can be used as context managers for a \keyword{with}
704statement. The \method{acquire()} method will be called when the block is
705entered, and \method{release()} will be called when the block is exited.
706
707Currently, \class{Lock}, \class{RLock}, \class{Condition}, \class{Semaphore},
708and \class{BoundedSemaphore} objects may be used as \keyword{with}
709statement context managers. For example:
710
711\begin{verbatim}
712from __future__ import with_statement
713import threading
714
715some_rlock = threading.RLock()
716
717with some_rlock:
718 print "some_rlock is locked while this executes"
719\end{verbatim}
720