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