blob: 928b422b58b2f08113746f58cdbd3bcbdc02dbdf [file] [log] [blame]
Andrew M. Kuchling16440e61998-07-20 13:46:10 +00001\section{Standard Module \module{threading}}
Fred Drakeb91e9341998-07-23 17:59:49 +00002\declaremodule{standard}{threading}
3
Fred Drake9643c671998-07-27 22:06:12 +00004\modulesynopsis{Higher-level threading interfaces.}
Fred Drakeb91e9341998-07-23 17:59:49 +00005
Andrew M. Kuchling16440e61998-07-20 13:46:10 +00006
Fred Drake9643c671998-07-27 22:06:12 +00007This module constructs higher-level threading interfaces on top of the
8lower level \module{thread} module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +00009
Fred Drake9643c671998-07-27 22:06:12 +000010This module is safe for use with \samp{from threading import *}. It
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000011defines the following functions and objects:
12
13\begin{funcdesc}{activeCount}{}
14Return the number of currently active \class{Thread} objects.
15The returned count is equal to the length of the list returned by
16\function{enumerate()}.
17A function that returns the number of currently active threads.
18\end{funcdesc}
19
20\begin{funcdesc}{Condition}{}
21A factory function that returns a new condition variable object.
22A condition variable allows one or more threads to wait until they
23are notified by another thread.
24\end{funcdesc}
25
26\begin{funcdesc}{currentThread}{}
27Return the current \class{Thread} object, corresponding to the
28caller's thread of control. If the caller's thread of control was not
29created through the
30\module{threading} module, a dummy thread object with limited functionality
31is returned.
32\end{funcdesc}
33
34\begin{funcdesc}{enumerate}{}
35Return a list of all currently active \class{Thread} objects.
36The list includes daemonic threads, dummy thread objects created
37by \function{currentThread()}, and the main thread. It excludes terminated
38threads and threads that have not yet been started.
39\end{funcdesc}
40
41\begin{funcdesc}{Event}{}
42A factory function that returns a new event object. An event
43manages a flag that can be set to true with the \method{set()} method and
44reset to false with the \method{clear()} method. The \method{wait()} method blocks
45until the flag is true.
46\end{funcdesc}
47
48\begin{funcdesc}{Lock}{}
49A factory function that returns a new primitive lock object. Once
50a thread has acquired it, subsequent attempts to acquire it block,
51until it is released; any thread may release it.
52\end{funcdesc}
53
54\begin{funcdesc}{RLock}{}
55A factory function that returns a new reentrant lock object.
56A reentrant lock must be released by the thread that acquired it.
57Once a thread has acquired a reentrant lock, the same thread may
58acquire it again without blocking; the thread must release it once
59for each time it has acquired it.
60\end{funcdesc}
61
62\begin{funcdesc}{Semaphore}{}
63A factory function that returns a new semaphore object. A
64semaphore manages a counter representing the number of \method{release()}
65calls minus the number of \method{acquire()} calls, plus an initial value.
66The \method{acquire()} method blocks if necessary until it can return
67without making the counter negative.
68\end{funcdesc}
69
70\begin{classdesc}{Thread}{}
71A class that represents a thread of control. This class can be safely subclassed in a limited fashion.
72\end{classdesc}
73
74Detailed interfaces for the objects are documented below.
75
76The design of this module is loosely based on Java's threading model.
77However, where Java makes locks and condition variables basic behavior
78of every object, they are separate objects in Python. Python's \class{Thread}
79class supports a subset of the behavior of Java's Thread class;
80currently, there are no priorities, no thread groups, and threads
81cannot be destroyed, stopped, suspended, resumed, or interrupted. The
82static methods of Java's Thread class, when implemented, are mapped to
83module-level functions.
84
85All of the methods described below are executed atomically.
86
87\subsection{Lock Objects}
88
89A primitive lock is a synchronization primitive that is not owned
90by a particular thread when locked. In Python, it is currently
91the lowest level synchronization primitive available, implemented
92directly by the \module{thread} extension module.
93
94A primitive lock is in one of two states, ``locked'' or ``unlocked''.
95It is created in the unlocked state. It has two basic methods,
96\method{acquire()} and \method{release()}. When the state is
97unlocked, \method{acquire()} changes the state to locked and returns
98immediately. When the state is locked, \method{acquire()} blocks
99until a call to \method{release()} in another thread changes it to
100unlocked, then the \method{acquire()} call resets it to locked and
101returns. The \method{release()} method should only be called in the
102locked state; it changes the state to unlocked and returns
103immediately. When more than one thread is blocked in
104\method{acquire()} waiting for the state to turn to unlocked, only one
105thread proceeds when a \method{release()} call resets the state to
106unlocked; which one of the waiting threads proceeds is not defined,
107and may vary across implementations.
108
109All methods are executed atomically.
110
111\begin{methoddesc}{acquire}{blocking=1}
112Acquire a lock, blocking or non-blocking.
113
114When invoked without arguments, block until the lock is
115unlocked, then set it to locked, and return. There is no
116return value in this case.
117
118When invoked with the \var{blocking} argument set to true, do the
119same thing as when called without arguments, and return true.
120
121When invoked with the \var{blocking} argument set to false, do not
122block. If a call without an argument would block, return false
123immediately; otherwise, do the same thing as when called
124without arguments, and return true.
125\end{methoddesc}
126
127\begin{methoddesc}{release}{}
128Release a lock.
129
130When the lock is locked, reset it to unlocked, and return. If
131any other threads are blocked waiting for the lock to become
132unlocked, allow exactly one of them to proceed.
133
134Do not call this method when the lock is unlocked.
135
136There is no return value.
137\end{methoddesc}
138
139\subsection{RLock Objects}
140
141A reentrant lock is a synchronization primitive that may be
142acquired multiple times by the same thread. Internally, it uses
143the concepts of ``owning thread'' and ``recursion level'' in
144addition to the locked/unlocked state used by primitive locks. In
145the locked state, some thread owns the lock; in the unlocked
146state, no thread owns it.
147
148To lock the lock, a thread calls its \method{acquire()} method; this
149returns once the thread owns the lock. To unlock the lock, a
150thread calls its \method{release()} method. \method{acquire()}/\method{release()} call pairs
151may be nested; only the final \method{release()} (i.e. the \method{release()} of the
152outermost pair) resets the lock to unlocked and allows another
153thread blocked in \method{acquire()} to proceed.
154
155\begin{methoddesc}{acquire}{blocking=1}
156Acquire a lock, blocking or non-blocking.
157
158When invoked without arguments: if this thread already owns
159the lock, increment the recursion level by one, and return
160immediately. Otherwise, if another thread owns the lock,
161block until the lock is unlocked. Once the lock is unlocked
162(not owned by any thread), then grab ownership, set the
163recursion level to one, and return. If more than one thread
164is blocked waiting until the lock is unlocked, only one at a
165time will be able to grab ownership of the lock. There is no
166return value in this case.
167
168When invoked with the \var{blocking} argument set to true, do the
169same thing as when called without arguments, and return true.
170
171When invoked with the \var{blocking} argument set to false, do not
172block. If a call without an argument would block, return false
173immediately; otherwise, do the same thing as when called
174without arguments, and return true.
175\end{methoddesc}
176
177\begin{methoddesc}{release}{}
178Release a lock, decrementing the recursion level. If after the
179decrement it is zero, reset the lock to unlocked (not owned by any
180thread), and if any other threads are blocked waiting for the lock to
181become unlocked, allow exactly one of them to proceed. If after the
182decrement the recursion level is still nonzero, the lock remains
183locked and owned by the calling thread.
184
185Only call this method when the calling thread owns the lock.
186Do not call this method when the lock is unlocked.
187
188There is no return value.
189\end{methoddesc}
190
191\subsection{Condition Objects}
192
193A condition variable is always associated with some kind of lock;
194this can be passed in or one will be created by default. (Passing
195one in is useful when several condition variables must share the
196same lock.)
197
198A condition variable has \method{acquire()} and \method{release()}
199methods that call the corresponding methods of the associated lock.
200It also has a \method{wait()} method, and \method{notify()} and
201\method{notifyAll()} methods. These three must only be called when
202the calling thread has acquired the lock.
203
204The \method{wait()} method releases the lock, and then blocks until it
205is awakened by a \method{notify()} or \method{notifyAll()} call for
206the same condition variable in another thread. Once awakened, it
207re-acquires the lock and returns. It is also possible to specify a
208timeout.
209
210The \method{notify()} method wakes up one of the threads waiting for
211the condition variable, if any are waiting. The \method{notifyAll()}
212method wakes up all threads waiting for the condition variable.
213
214Note: the \method{notify()} and \method{notifyAll()} methods don't
215release the lock; this means that the thread or threads awakened will
216not return from their \method{wait()} call immediately, but only when
217the thread that called \method{notify()} or \method{notifyAll()}
218finally relinquishes ownership of the lock.
219
220Tip: the typical programming style using condition variables uses the
221lock to synchronize access to some shared state; threads that are
222interested in a particular change of state call \method{wait()}
223repeatedly until they see the desired state, while threads that modify
224the state call \method{notify()} or \method{notifyAll()} when they
225change the state in such a way that it could possibly be a desired
226state for one of the waiters. For example, the following code is a
227generic producer-consumer situation with unlimited buffer capacity:
228
229\begin{verbatim}
230# Consume one item
231cv.acquire()
232while not an_item_is_available():
233 cv.wait()
234get_an_available_item()
235cv.release()
236
237# Produce one item
238cv.acquire()
239make_an_item_available()
240cv.notify()
241cv.release()
242\end{verbatim}
243
244To choose between \method{notify()} and \method{notifyAll()}, consider
245whether one state change can be interesting for only one or several
246waiting threads. E.g. in a typical producer-consumer situation,
247adding one item to the buffer only needs to wake up one consumer
248thread.
249
250\begin{classdesc}{Condition}{lock=None}
251If the \var{lock} argument is given and not \code{None}, it must be a \class{Lock}
252or \class{RLock} object, and it is used as the underlying lock.
253Otherwise, a new \class{RLock} object is created and used as the
254underlying lock.
255\end{classdesc}
256
257\begin{methoddesc}{acquire}{*args}
258Acquire the underlying lock.
259This method calls the corresponding method on the underlying
260lock; the return value is whatever that method returns.
261\end{methoddesc}
262
263\begin{methoddesc}{release}{}
264Release the underlying lock.
265This method calls the corresponding method on the underlying
266lock; there is no return value.
267\end{methoddesc}
268
269\begin{methoddesc}{wait}{timeout=None}
270Wait until notified or until a timeout occurs.
271This must only be called when the calling thread has acquired the
272lock.
273
274This method releases the underlying lock, and then blocks until it is
275awakened by a \method{notify()} or \method{notifyAll()} call for the
276same condition variable in another thread, or until the optional
277timeout occurs. Once awakened or timed out, it re-acquires the lock
278and returns.
279
280When the timeout argument is present and not \code{None}, it should be a
281floating point number specifying a timeout for the operation in
282seconds (or fractions thereof).
283
284When the underlying lock is an \class{RLock}, it is not released using its
285\method{release()} method, since this may not actually unlock the lock
286when it was acquired multiple times recursively. Instead, an
287internal interface of the \class{RLock} class is used, which really unlocks it
288even when it has been recursively acquired several times. Another
289internal interface is then used to restore the recursion level when
290the lock is reacquired.
291\end{methoddesc}
292
293\begin{methoddesc}{notify}{}
294Wake up a thread waiting on this condition, if any.
295This must only be called when the calling thread has acquired the
296lock.
297
298This method wakes up one of the threads waiting for the condition
299variable, if any are waiting; it is a no-op if no threads are waiting.
300
301The current implementation wakes up exactly one thread, if any are
302waiting. However, it's not safe to rely on this behavior. A future,
303optimized implementation may occasionally wake up more than one
304thread.
305
306Note: the awakened thread does not actually return from its
307\method{wait()} call until it can reacquire the lock. Since
308\method{notify()} does not release the lock, its caller should.
309\end{methoddesc}
310
311\begin{methoddesc}{notifyAll}{}
312Wake up all threads waiting on this condition. This method acts like
313\method{notify()}, but wakes up all waiting threads instead of one.
314\end{methoddesc}
315
316\subsection{Semaphore Objects}
317
318This is one of the oldest synchronization primitives in the history of
319computer science, invented by the early Dutch computer scientist
320Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of \method{acquire()}
321and \method{release()}).
322
323A semaphore manages an internal counter which is decremented by each
324\method{acquire()} call and incremented by each \method{release()}
325call. The counter can never go below zero; when \method{acquire()}
326finds that it is zero, it blocks, waiting until some other thread
327calls \method{release()}.
328
329\begin{classdesc}{Semaphore}{value=1}
330The optional argument gives the initial value for the internal
331counter; it defaults to 1.
332\end{classdesc}
333
334\begin{methoddesc}{acquire}{blocking=1}
335Acquire a semaphore.
336
337When invoked without arguments: if the internal counter is larger than
338zero on entry, decrement it by one and return immediately. If it is
339zero on entry, block, waiting until some other thread has called
340\method{release()} to make it larger than zero. This is done with
341proper interlocking so that if multiple \method{acquire()} calls are
342blocked, \method{release()} will wake exactly one of them up. The
343implementation may pick one at random, so the order in which blocked
344threads are awakened should not be relied on. There is no return
345value in this case.
346
347When invoked with the \var{blocking} argument set to true, do the same
348thing as when called without arguments, and return true.
349
350When invoked with the \var{blocking} argument set to false, do not
351block. If a call without an argument would block, return false
352immediately; otherwise, do the same thing as when called without
353arguments, and return true.
354\end{methoddesc}
355
356\begin{methoddesc}{release}{}
357Release a semaphore,
358incrementing the internal counter by one. When it was zero on
359entry and another thread is waiting for it to become larger
360than zero again, wake up that thread.
361\end{methoddesc}
362
363\subsection{Event Objects}
364
365This is one of the simplest mechanisms for communication between
366threads: one thread signals an event and one or more other thread
367are waiting for it.
368
369An event object manages an internal flag that can be set to true with
370the \method{set()} method and reset to false with the \method{clear()} method. The
371\method{wait()} method blocks until the flag is true.
372
373
374\begin{classdesc}{Event}{}
375The internal flag is initially false.
376\end{classdesc}
377
378\begin{methoddesc}{isSet}{}
379Return true if and only if the internal flag is true.
380\end{methoddesc}
381
382\begin{methoddesc}{set}{}
383Set the internal flag to true.
384All threads waiting for it to become true are awakened.
385Threads that call \method{wait()} once the flag is true will not block
386at all.
387\end{methoddesc}
388
389\begin{methoddesc}{clear}{}
390Reset the internal flag to false.
391Subsequently, threads calling \method{wait()} will block until \method{set()} is
392called to set the internal flag to true again.
393\end{methoddesc}
394
395\begin{methoddesc}{wait}{timeout=None}
396Block until the internal flag is true.
397If the internal flag is true on entry, return immediately. Otherwise,
398block until another thread calls \method{set()} to set the flag to
399true, or until the optional timeout occurs.
400
401When the timeout argument is present and not \code{None}, it should be a
402floating point number specifying a timeout for the operation in
403seconds (or fractions thereof).
404\end{methoddesc}
405
406\subsection{Thread Objects}
407
408This class represents an activity that is run in a separate thread
409of control. There are two ways to specify the activity: by
410passing a callable object to the constructor, or by overriding the
411\method{run()} method in a subclass. No other methods (except for the
412constructor) should be overridden in a subclass. In other words,
413\emph{only} override the \method{__init__()} and \method{run()} methods of this class.
414
415
416Once a thread object is created, its activity must be started by
417calling the thread's \method{start()} method. This invokes the \method{run()}
418method in a separate thread of control.
419
420Once the thread's activity is started, the thread is considered
421'alive' and 'active' (these concepts are almost, but not quite
422exactly, the same; their definition is intentionally somewhat
423vague). It stops being alive and active when its \method{run()} method
424terminates -- either normally, or by raising an unhandled
425exception. The \method{isAlive()} method tests whether the thread is
426alive.
427
428Other threads can call a thread's \method{join()} method. This blocks the
429calling thread until the thread whose \method{join()} method is called
430is terminated.
431
432A thread has a name. The name can be passed to the constructor,
433set with the \method{setName()} method, and retrieved with the \method{getName()}
434method.
435
436A thread can be flagged as a ``daemon thread''. The significance
437of this flag is that the entire Python program exits when only
438daemon threads are left. The initial value is inherited from the
439creating thread. The flag can be set with the \method{setDaemon()} method
440and retrieved with the \method{getDaemon()} method.
441
442There is a ``main thread'' object; this corresponds to the
443initial thread of control in the Python program. It is not a
444daemon thread.
445
446There is the possibility that ``dummy thread objects'' are
447created. These are thread objects corresponding to ``alien
448threads''. These are threads of control started outside the
449threading module, e.g. directly from C code. Dummy thread objects
450have limited functionality; they are always considered alive,
451active, and daemonic, and cannot be \method{join()}ed. They are never
452deleted, since it is impossible to detect the termination of alien
453threads.
454
455
456\begin{classdesc}{Thread}{group=None, target=None, name=None,
457 args=(), kwargs={}}
458This constructor should always be called with keyword
459arguments. Arguments are:
460
461group
462Should be None; reserved for future extension when a
463ThreadGroup class is implemented.
464
465target
466Callable object to be invoked by the \method{run()} method.
467Defaults to None, meaning nothing is called.
468
469name
470The thread name. By default, a unique name is constructed
471of the form ``Thread-N'' where N is a small decimal
472number.
473
474args
475Argument tuple for the target invocation. Defaults to ().
476
477kwargs
478Keyword argument dictionary for the target invocation.
479Defaults to {}.
480
481If the subclass overrides the constructor, it must make sure
482to invoke the base class constructor (Thread.__init__())
483before doing anything else to the thread.
484\end{classdesc}
485
486
487
488\begin{methoddesc}{start}{}
489Start the thread's activity.
490
491This must be called at most once per thread object. It
492arranges for the object's \method{run()} method to be invoked in a
493separate thread of control.
494\end{methoddesc}
495
496
497
498\begin{methoddesc}{run}{}
499Method representing the thread's activity.
500
501You may override this method in a subclass. The standard
502\method{run()} method invokes the callable object passed to the object's constructor as the
503\var{target} argument, if any, with sequential and keyword
504arguments taken from the \var{args} and \var{kwargs} arguments,
505respectively.
506\end{methoddesc}
507
508
509\begin{methoddesc}{join}{timeout=None}
510Wait until the thread terminates.
511This blocks the calling thread until the thread whose \method{join()}
512method is called terminates -- either normally or through an
513unhandled exception -- or until the optional timeout occurs.
514
515When the \var{timeout} argument is present and not \code{None}, it should
516be a floating point number specifying a timeout for the
517operation in seconds (or fractions thereof).
518
519A thread can be \method{join()}ed many times.
520
521A thread cannot join itself because this would cause a
522deadlock.
523
524It is an error to attempt to \method{join()} a thread before it has
525been started.
526\end{methoddesc}
527
528
529
530\begin{methoddesc}{getName}{}
531Return the thread's name.
532\end{methoddesc}
533
534\begin{methoddesc}{setName}{name}
535Set the thread's name.
536
537The name is a string used for identification purposes only.
538It has no semantics. Multiple threads may be given the same
539name. The initial name is set by the constructor.
540\end{methoddesc}
541
542\begin{methoddesc}{isAlive}{}
543Return whether the thread is alive.
544
545Roughly, a thread is alive from the moment the \method{start()} method
546returns until its \method{run()} method terminates.
547\end{methoddesc}
548
549\begin{methoddesc}{isDaemon}{}
550Return the thread's daemon flag.
551\end{methoddesc}
552
553\begin{methoddesc}{setDaemon}{daemonic}
554Set the thread's daemon flag to the Boolean value \var{daemonic}.
555This must be called before \method{start()} is called.
556
557The initial value is inherited from the creating thread.
558
559The entire Python program exits when no active non-daemon
560threads are left.
561\end{methoddesc}
562