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