blob: 33839a4306a130d8fd08c9e30e2d2036bcbc9886 [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
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000128Detailed interfaces for the objects are documented below.
129
130The design of this module is loosely based on Java's threading model.
131However, where Java makes locks and condition variables basic behavior
132of every object, they are separate objects in Python. Python's \class{Thread}
133class supports a subset of the behavior of Java's Thread class;
134currently, there are no priorities, no thread groups, and threads
135cannot be destroyed, stopped, suspended, resumed, or interrupted. The
136static methods of Java's Thread class, when implemented, are mapped to
137module-level functions.
138
139All of the methods described below are executed atomically.
140
Fred Drakebf5a6d21999-03-12 19:57:38 +0000141
142\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000143
144A primitive lock is a synchronization primitive that is not owned
145by a particular thread when locked. In Python, it is currently
146the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000147directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000148
149A primitive lock is in one of two states, ``locked'' or ``unlocked''.
150It is created in the unlocked state. It has two basic methods,
151\method{acquire()} and \method{release()}. When the state is
152unlocked, \method{acquire()} changes the state to locked and returns
153immediately. When the state is locked, \method{acquire()} blocks
154until a call to \method{release()} in another thread changes it to
155unlocked, then the \method{acquire()} call resets it to locked and
156returns. The \method{release()} method should only be called in the
157locked state; it changes the state to unlocked and returns
158immediately. When more than one thread is blocked in
159\method{acquire()} waiting for the state to turn to unlocked, only one
160thread proceeds when a \method{release()} call resets the state to
161unlocked; which one of the waiting threads proceeds is not defined,
162and may vary across implementations.
163
164All methods are executed atomically.
165
Fred Drakebf5a6d21999-03-12 19:57:38 +0000166\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000167Acquire a lock, blocking or non-blocking.
168
169When invoked without arguments, block until the lock is
Andrew M. Kuchling921879a2005-06-02 16:59:18 +0000170unlocked, then set it to locked, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000171
172When invoked with the \var{blocking} argument set to true, do the
173same thing as when called without arguments, and return true.
174
175When invoked with the \var{blocking} argument set to false, do not
176block. If a call without an argument would block, return false
177immediately; otherwise, do the same thing as when called
178without arguments, and return true.
179\end{methoddesc}
180
181\begin{methoddesc}{release}{}
182Release a lock.
183
184When the lock is locked, reset it to unlocked, and return. If
185any other threads are blocked waiting for the lock to become
186unlocked, allow exactly one of them to proceed.
187
188Do not call this method when the lock is unlocked.
189
190There is no return value.
191\end{methoddesc}
192
Fred Drakebf5a6d21999-03-12 19:57:38 +0000193
194\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000195
196A reentrant lock is a synchronization primitive that may be
197acquired multiple times by the same thread. Internally, it uses
198the concepts of ``owning thread'' and ``recursion level'' in
199addition to the locked/unlocked state used by primitive locks. In
200the locked state, some thread owns the lock; in the unlocked
201state, no thread owns it.
202
203To lock the lock, a thread calls its \method{acquire()} method; this
204returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000205thread calls its \method{release()} method.
206\method{acquire()}/\method{release()} call pairs may be nested; only
207the final \method{release()} (the \method{release()} of the outermost
208pair) resets the lock to unlocked and allows another thread blocked in
209\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000210
Fred Drakebf5a6d21999-03-12 19:57:38 +0000211\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000212Acquire a lock, blocking or non-blocking.
213
214When invoked without arguments: if this thread already owns
215the lock, increment the recursion level by one, and return
216immediately. Otherwise, if another thread owns the lock,
217block until the lock is unlocked. Once the lock is unlocked
218(not owned by any thread), then grab ownership, set the
219recursion level to one, and return. If more than one thread
220is blocked waiting until the lock is unlocked, only one at a
221time will be able to grab ownership of the lock. There is no
222return value in this case.
223
224When invoked with the \var{blocking} argument set to true, do the
225same thing as when called without arguments, and return true.
226
227When invoked with the \var{blocking} argument set to false, do not
228block. If a call without an argument would block, return false
229immediately; otherwise, do the same thing as when called
230without arguments, and return true.
231\end{methoddesc}
232
233\begin{methoddesc}{release}{}
234Release a lock, decrementing the recursion level. If after the
235decrement it is zero, reset the lock to unlocked (not owned by any
236thread), and if any other threads are blocked waiting for the lock to
237become unlocked, allow exactly one of them to proceed. If after the
238decrement the recursion level is still nonzero, the lock remains
239locked and owned by the calling thread.
240
241Only call this method when the calling thread owns the lock.
242Do not call this method when the lock is unlocked.
243
244There is no return value.
245\end{methoddesc}
246
Fred Drakebf5a6d21999-03-12 19:57:38 +0000247
248\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000249
250A condition variable is always associated with some kind of lock;
251this can be passed in or one will be created by default. (Passing
252one in is useful when several condition variables must share the
253same lock.)
254
255A condition variable has \method{acquire()} and \method{release()}
256methods that call the corresponding methods of the associated lock.
257It also has a \method{wait()} method, and \method{notify()} and
258\method{notifyAll()} methods. These three must only be called when
259the calling thread has acquired the lock.
260
261The \method{wait()} method releases the lock, and then blocks until it
262is awakened by a \method{notify()} or \method{notifyAll()} call for
263the same condition variable in another thread. Once awakened, it
264re-acquires the lock and returns. It is also possible to specify a
265timeout.
266
267The \method{notify()} method wakes up one of the threads waiting for
268the condition variable, if any are waiting. The \method{notifyAll()}
269method wakes up all threads waiting for the condition variable.
270
271Note: the \method{notify()} and \method{notifyAll()} methods don't
272release the lock; this means that the thread or threads awakened will
273not return from their \method{wait()} call immediately, but only when
274the thread that called \method{notify()} or \method{notifyAll()}
275finally relinquishes ownership of the lock.
276
277Tip: the typical programming style using condition variables uses the
278lock to synchronize access to some shared state; threads that are
279interested in a particular change of state call \method{wait()}
280repeatedly until they see the desired state, while threads that modify
281the state call \method{notify()} or \method{notifyAll()} when they
282change the state in such a way that it could possibly be a desired
283state for one of the waiters. For example, the following code is a
284generic producer-consumer situation with unlimited buffer capacity:
285
286\begin{verbatim}
287# Consume one item
288cv.acquire()
289while not an_item_is_available():
290 cv.wait()
291get_an_available_item()
292cv.release()
293
294# Produce one item
295cv.acquire()
296make_an_item_available()
297cv.notify()
298cv.release()
299\end{verbatim}
300
301To choose between \method{notify()} and \method{notifyAll()}, consider
302whether one state change can be interesting for only one or several
303waiting threads. E.g. in a typical producer-consumer situation,
304adding one item to the buffer only needs to wake up one consumer
305thread.
306
Fred Drakebf5a6d21999-03-12 19:57:38 +0000307\begin{classdesc}{Condition}{\optional{lock}}
308If the \var{lock} argument is given and not \code{None}, it must be a
309\class{Lock} or \class{RLock} object, and it is used as the underlying
310lock. Otherwise, a new \class{RLock} object is created and used as
311the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000312\end{classdesc}
313
314\begin{methoddesc}{acquire}{*args}
315Acquire the underlying lock.
316This method calls the corresponding method on the underlying
317lock; the return value is whatever that method returns.
318\end{methoddesc}
319
320\begin{methoddesc}{release}{}
321Release the underlying lock.
322This method calls the corresponding method on the underlying
323lock; there is no return value.
324\end{methoddesc}
325
Fred Drakebf5a6d21999-03-12 19:57:38 +0000326\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000327Wait until notified or until a timeout occurs.
328This must only be called when the calling thread has acquired the
329lock.
330
331This method releases the underlying lock, and then blocks until it is
332awakened by a \method{notify()} or \method{notifyAll()} call for the
333same condition variable in another thread, or until the optional
334timeout occurs. Once awakened or timed out, it re-acquires the lock
335and returns.
336
Fred Drakebf5a6d21999-03-12 19:57:38 +0000337When the \var{timeout} argument is present and not \code{None}, it
338should be a floating point number specifying a timeout for the
339operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000340
Fred Drakebf5a6d21999-03-12 19:57:38 +0000341When the underlying lock is an \class{RLock}, it is not released using
342its \method{release()} method, since this may not actually unlock the
343lock when it was acquired multiple times recursively. Instead, an
344internal interface of the \class{RLock} class is used, which really
345unlocks it even when it has been recursively acquired several times.
346Another internal interface is then used to restore the recursion level
347when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000348\end{methoddesc}
349
350\begin{methoddesc}{notify}{}
351Wake up a thread waiting on this condition, if any.
352This must only be called when the calling thread has acquired the
353lock.
354
355This method wakes up one of the threads waiting for the condition
356variable, if any are waiting; it is a no-op if no threads are waiting.
357
358The current implementation wakes up exactly one thread, if any are
359waiting. However, it's not safe to rely on this behavior. A future,
360optimized implementation may occasionally wake up more than one
361thread.
362
363Note: the awakened thread does not actually return from its
364\method{wait()} call until it can reacquire the lock. Since
365\method{notify()} does not release the lock, its caller should.
366\end{methoddesc}
367
368\begin{methoddesc}{notifyAll}{}
369Wake up all threads waiting on this condition. This method acts like
370\method{notify()}, but wakes up all waiting threads instead of one.
371\end{methoddesc}
372
Fred Drakebf5a6d21999-03-12 19:57:38 +0000373
374\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000375
376This is one of the oldest synchronization primitives in the history of
377computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000378Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
379\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000380
381A semaphore manages an internal counter which is decremented by each
382\method{acquire()} call and incremented by each \method{release()}
383call. The counter can never go below zero; when \method{acquire()}
384finds that it is zero, it blocks, waiting until some other thread
385calls \method{release()}.
386
Fred Drakebf5a6d21999-03-12 19:57:38 +0000387\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000388The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000389counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000390\end{classdesc}
391
Fred Drakebf5a6d21999-03-12 19:57:38 +0000392\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000393Acquire a semaphore.
394
395When invoked without arguments: if the internal counter is larger than
396zero on entry, decrement it by one and return immediately. If it is
397zero on entry, block, waiting until some other thread has called
398\method{release()} to make it larger than zero. This is done with
399proper interlocking so that if multiple \method{acquire()} calls are
400blocked, \method{release()} will wake exactly one of them up. The
401implementation may pick one at random, so the order in which blocked
402threads are awakened should not be relied on. There is no return
403value in this case.
404
Fred Drakebf5a6d21999-03-12 19:57:38 +0000405When invoked with \var{blocking} set to true, do the same thing as
406when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000407
Fred Drakebf5a6d21999-03-12 19:57:38 +0000408When invoked with \var{blocking} set to false, do not block. If a
409call without an argument would block, return false immediately;
410otherwise, do the same thing as when called without arguments, and
411return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000412\end{methoddesc}
413
414\begin{methoddesc}{release}{}
415Release a semaphore,
416incrementing the internal counter by one. When it was zero on
417entry and another thread is waiting for it to become larger
418than zero again, wake up that thread.
419\end{methoddesc}
420
Fred Drakebf5a6d21999-03-12 19:57:38 +0000421
Fred Drake31d833d2001-08-20 18:49:00 +0000422\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
423
424Semaphores are often used to guard resources with limited capacity, for
425example, a database server. In any situation where the size of the resource
426size is fixed, you should use a bounded semaphore. Before spawning any
427worker threads, your main thread would initialize the semaphore:
428
429\begin{verbatim}
430maxconnections = 5
431...
432pool_sema = BoundedSemaphore(value=maxconnections)
433\end{verbatim}
434
435Once spawned, worker threads call the semaphore's acquire and release
436methods when they need to connect to the server:
437
438\begin{verbatim}
439pool_sema.acquire()
440conn = connectdb()
441... use connection ...
442conn.close()
443pool_sema.release()
444\end{verbatim}
445
446The use of a bounded semaphore reduces the chance that a programming error
447which causes the semaphore to be released more than it's acquired will go
448undetected.
449
Fred Drake12686782002-03-19 14:37:44 +0000450
Fred Drakebf5a6d21999-03-12 19:57:38 +0000451\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000452
453This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000454threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000455
456An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000457the \method{set()} method and reset to false with the \method{clear()}
458method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000459
460
461\begin{classdesc}{Event}{}
462The internal flag is initially false.
463\end{classdesc}
464
465\begin{methoddesc}{isSet}{}
466Return true if and only if the internal flag is true.
467\end{methoddesc}
468
469\begin{methoddesc}{set}{}
470Set the internal flag to true.
471All threads waiting for it to become true are awakened.
472Threads that call \method{wait()} once the flag is true will not block
473at all.
474\end{methoddesc}
475
476\begin{methoddesc}{clear}{}
477Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000478Subsequently, threads calling \method{wait()} will block until
479\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000480\end{methoddesc}
481
Fred Drakebf5a6d21999-03-12 19:57:38 +0000482\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000483Block until the internal flag is true.
484If the internal flag is true on entry, return immediately. Otherwise,
485block until another thread calls \method{set()} to set the flag to
486true, or until the optional timeout occurs.
487
488When the timeout argument is present and not \code{None}, it should be a
489floating point number specifying a timeout for the operation in
490seconds (or fractions thereof).
491\end{methoddesc}
492
Fred Drakebf5a6d21999-03-12 19:57:38 +0000493
494\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000495
496This class represents an activity that is run in a separate thread
497of control. There are two ways to specify the activity: by
498passing a callable object to the constructor, or by overriding the
499\method{run()} method in a subclass. No other methods (except for the
500constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000501\emph{only} override the \method{__init__()} and \method{run()}
502methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000503
504Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000505calling the thread's \method{start()} method. This invokes the
506\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000507
508Once the thread's activity is started, the thread is considered
509'alive' and 'active' (these concepts are almost, but not quite
510exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000511vague). It stops being alive and active when its \method{run()}
512method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000513exception. The \method{isAlive()} method tests whether the thread is
514alive.
515
Fred Drakebf5a6d21999-03-12 19:57:38 +0000516Other threads can call a thread's \method{join()} method. This blocks
517the calling thread until the thread whose \method{join()} method is
518called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000519
520A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000521set with the \method{setName()} method, and retrieved with the
522\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000523
524A thread can be flagged as a ``daemon thread''. The significance
525of this flag is that the entire Python program exits when only
526daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000527creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000528method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000529
530There is a ``main thread'' object; this corresponds to the
531initial thread of control in the Python program. It is not a
532daemon thread.
533
534There is the possibility that ``dummy thread objects'' are
535created. These are thread objects corresponding to ``alien
536threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000537threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000538have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000539active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000540deleted, since it is impossible to detect the termination of alien
541threads.
542
543
544\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000545 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000546This constructor should always be called with keyword
547arguments. Arguments are:
548
Fred Drakec19f3922001-05-31 20:24:07 +0000549\var{group} should be \code{None}; reserved for future extension when
550a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000551
Fred Drakec19f3922001-05-31 20:24:07 +0000552\var{target} is the callable object to be invoked by the
553\method{run()} method. Defaults to \code{None}, meaning nothing is
554called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000555
Fred Drakec19f3922001-05-31 20:24:07 +0000556\var{name} is the thread name. By default, a unique name is
557constructed of the form ``Thread-\var{N}'' where \var{N} is a small
558decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000559
Fred Drakec19f3922001-05-31 20:24:07 +0000560\var{args} is the argument tuple for the target invocation. Defaults
561to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000562
Fred Drakec19f3922001-05-31 20:24:07 +0000563\var{kwargs} is a dictionary of keyword arguments for the target
564invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000565
566If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000567to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000568before doing anything else to the thread.
569\end{classdesc}
570
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000571\begin{methoddesc}{start}{}
572Start the thread's activity.
573
574This must be called at most once per thread object. It
575arranges for the object's \method{run()} method to be invoked in a
576separate thread of control.
577\end{methoddesc}
578
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000579\begin{methoddesc}{run}{}
580Method representing the thread's activity.
581
582You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000583\method{run()} method invokes the callable object passed to the
584object's constructor as the \var{target} argument, if any, with
585sequential and keyword arguments taken from the \var{args} and
586\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000587\end{methoddesc}
588
Fred Drakebf5a6d21999-03-12 19:57:38 +0000589\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000590Wait until the thread terminates.
591This blocks the calling thread until the thread whose \method{join()}
592method is called terminates -- either normally or through an
593unhandled exception -- or until the optional timeout occurs.
594
Fred Drake12686782002-03-19 14:37:44 +0000595When the \var{timeout} argument is present and not \code{None}, it
596should be a floating point number specifying a timeout for the
Georg Brandl75d51062005-07-17 21:00:26 +0000597operation in seconds (or fractions thereof). As \method{join()} always
598returns \code{None}, you must call \method{isAlive()} to decide whether
599a timeout happened.
600
601When the \var{timeout} argument is not present or \code{None}, the
602operation will block until the thread terminates.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000603
604A thread can be \method{join()}ed many times.
605
606A thread cannot join itself because this would cause a
607deadlock.
608
609It is an error to attempt to \method{join()} a thread before it has
610been started.
611\end{methoddesc}
612
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000613\begin{methoddesc}{getName}{}
614Return the thread's name.
615\end{methoddesc}
616
617\begin{methoddesc}{setName}{name}
618Set the thread's name.
619
620The name is a string used for identification purposes only.
621It has no semantics. Multiple threads may be given the same
622name. The initial name is set by the constructor.
623\end{methoddesc}
624
625\begin{methoddesc}{isAlive}{}
626Return whether the thread is alive.
627
628Roughly, a thread is alive from the moment the \method{start()} method
629returns until its \method{run()} method terminates.
630\end{methoddesc}
631
632\begin{methoddesc}{isDaemon}{}
633Return the thread's daemon flag.
634\end{methoddesc}
635
636\begin{methoddesc}{setDaemon}{daemonic}
637Set the thread's daemon flag to the Boolean value \var{daemonic}.
638This must be called before \method{start()} is called.
639
640The initial value is inherited from the creating thread.
641
642The entire Python program exits when no active non-daemon
643threads are left.
644\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000645
646
647\subsection{Timer Objects \label{timer-objects}}
648
Fred Drake12686782002-03-19 14:37:44 +0000649This class represents an action that should be run only after a
650certain amount of time has passed --- a timer. \class{Timer} is a
651subclass of \class{Thread} and as such also functions as an example of
652creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000653
Fred Drake12686782002-03-19 14:37:44 +0000654Timers are started, as with threads, by calling their \method{start()}
655method. The timer can be stopped (before its action has begun) by
656calling the \method{cancel()} method. The interval the timer will
657wait before executing its action may not be exactly the same as the
658interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000659
660For example:
661\begin{verbatim}
662def hello():
663 print "hello, world"
664
665t = Timer(30.0, hello)
666t.start() # after 30 seconds, "hello, world" will be printed
667\end{verbatim}
668
669\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
670Create a timer that will run \var{function} with arguments \var{args} and
671keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
672\end{classdesc}
673
674\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000675Stop the timer, and cancel the execution of the timer's action. This
676will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000677\end{methoddesc}