blob: f6d7e4d90a3817682bd7e0a907237eebb7032c25 [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
52\begin{funcdesc}{Lock}{}
53A factory function that returns a new primitive lock object. Once
54a thread has acquired it, subsequent attempts to acquire it block,
55until it is released; any thread may release it.
56\end{funcdesc}
57
58\begin{funcdesc}{RLock}{}
59A factory function that returns a new reentrant lock object.
60A reentrant lock must be released by the thread that acquired it.
61Once a thread has acquired a reentrant lock, the same thread may
62acquire it again without blocking; the thread must release it once
63for each time it has acquired it.
64\end{funcdesc}
65
Fred Drake31d833d2001-08-20 18:49:00 +000066\begin{funcdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000067A factory function that returns a new semaphore object. A
68semaphore manages a counter representing the number of \method{release()}
69calls minus the number of \method{acquire()} calls, plus an initial value.
70The \method{acquire()} method blocks if necessary until it can return
Fred Drake31d833d2001-08-20 18:49:00 +000071without making the counter negative. If not given, \var{value} defaults to
721.
73\end{funcdesc}
74
75\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
76A factory function that returns a new bounded semaphore object. A bounded
77semaphore checks to make sure its current value doesn't exceed its initial
78value. If it does, \exception{ValueError} is raised. In most situations
79semaphores are used to guard resources with limited capacity. If the
80semaphore is released too many times it's a sign of a bug. If not given,
81\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000082\end{funcdesc}
83
Fred Drakec19f3922001-05-31 20:24:07 +000084\begin{classdesc*}{Thread}{}
Fred Drake12686782002-03-19 14:37:44 +000085A class that represents a thread of control. This class can be safely
86subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +000087\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000088
Martin v. Löwis44f86962001-09-05 13:44:54 +000089\begin{classdesc*}{Timer}{}
90A thread that executes a function after a specified interval has passed.
91\end{classdesc*}
92
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000093\begin{funcdesc}{settrace}{func}
Fred Drake57288152003-06-29 18:12:23 +000094Set a trace function\index{trace function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000095from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +000096\function{sys.settrace()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000097method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +000098\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000099\end{funcdesc}
100
101\begin{funcdesc}{setprofile}{func}
Fred Drake57288152003-06-29 18:12:23 +0000102Set a profile function\index{profile function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000103from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000104\function{sys.setprofile()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000105method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000106\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000107\end{funcdesc}
108
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000109Detailed interfaces for the objects are documented below.
110
111The design of this module is loosely based on Java's threading model.
112However, where Java makes locks and condition variables basic behavior
113of every object, they are separate objects in Python. Python's \class{Thread}
114class supports a subset of the behavior of Java's Thread class;
115currently, there are no priorities, no thread groups, and threads
116cannot be destroyed, stopped, suspended, resumed, or interrupted. The
117static methods of Java's Thread class, when implemented, are mapped to
118module-level functions.
119
120All of the methods described below are executed atomically.
121
Fred Drakebf5a6d21999-03-12 19:57:38 +0000122
123\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000124
125A primitive lock is a synchronization primitive that is not owned
126by a particular thread when locked. In Python, it is currently
127the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000128directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000129
130A primitive lock is in one of two states, ``locked'' or ``unlocked''.
131It is created in the unlocked state. It has two basic methods,
132\method{acquire()} and \method{release()}. When the state is
133unlocked, \method{acquire()} changes the state to locked and returns
134immediately. When the state is locked, \method{acquire()} blocks
135until a call to \method{release()} in another thread changes it to
136unlocked, then the \method{acquire()} call resets it to locked and
137returns. The \method{release()} method should only be called in the
138locked state; it changes the state to unlocked and returns
139immediately. When more than one thread is blocked in
140\method{acquire()} waiting for the state to turn to unlocked, only one
141thread proceeds when a \method{release()} call resets the state to
142unlocked; which one of the waiting threads proceeds is not defined,
143and may vary across implementations.
144
145All methods are executed atomically.
146
Fred Drakebf5a6d21999-03-12 19:57:38 +0000147\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000148Acquire a lock, blocking or non-blocking.
149
150When invoked without arguments, block until the lock is
151unlocked, then set it to locked, and return. There is no
152return value in this case.
153
154When invoked with the \var{blocking} argument set to true, do the
155same thing as when called without arguments, and return true.
156
157When invoked with the \var{blocking} argument set to false, do not
158block. If a call without an argument would block, return false
159immediately; otherwise, do the same thing as when called
160without arguments, and return true.
161\end{methoddesc}
162
163\begin{methoddesc}{release}{}
164Release a lock.
165
166When the lock is locked, reset it to unlocked, and return. If
167any other threads are blocked waiting for the lock to become
168unlocked, allow exactly one of them to proceed.
169
170Do not call this method when the lock is unlocked.
171
172There is no return value.
173\end{methoddesc}
174
Fred Drakebf5a6d21999-03-12 19:57:38 +0000175
176\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000177
178A reentrant lock is a synchronization primitive that may be
179acquired multiple times by the same thread. Internally, it uses
180the concepts of ``owning thread'' and ``recursion level'' in
181addition to the locked/unlocked state used by primitive locks. In
182the locked state, some thread owns the lock; in the unlocked
183state, no thread owns it.
184
185To lock the lock, a thread calls its \method{acquire()} method; this
186returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000187thread calls its \method{release()} method.
188\method{acquire()}/\method{release()} call pairs may be nested; only
189the final \method{release()} (the \method{release()} of the outermost
190pair) resets the lock to unlocked and allows another thread blocked in
191\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000192
Fred Drakebf5a6d21999-03-12 19:57:38 +0000193\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000194Acquire a lock, blocking or non-blocking.
195
196When invoked without arguments: if this thread already owns
197the lock, increment the recursion level by one, and return
198immediately. Otherwise, if another thread owns the lock,
199block until the lock is unlocked. Once the lock is unlocked
200(not owned by any thread), then grab ownership, set the
201recursion level to one, and return. If more than one thread
202is blocked waiting until the lock is unlocked, only one at a
203time will be able to grab ownership of the lock. There is no
204return value in this case.
205
206When invoked with the \var{blocking} argument set to true, do the
207same thing as when called without arguments, and return true.
208
209When invoked with the \var{blocking} argument set to false, do not
210block. If a call without an argument would block, return false
211immediately; otherwise, do the same thing as when called
212without arguments, and return true.
213\end{methoddesc}
214
215\begin{methoddesc}{release}{}
216Release a lock, decrementing the recursion level. If after the
217decrement it is zero, reset the lock to unlocked (not owned by any
218thread), and if any other threads are blocked waiting for the lock to
219become unlocked, allow exactly one of them to proceed. If after the
220decrement the recursion level is still nonzero, the lock remains
221locked and owned by the calling thread.
222
223Only call this method when the calling thread owns the lock.
224Do not call this method when the lock is unlocked.
225
226There is no return value.
227\end{methoddesc}
228
Fred Drakebf5a6d21999-03-12 19:57:38 +0000229
230\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000231
232A condition variable is always associated with some kind of lock;
233this can be passed in or one will be created by default. (Passing
234one in is useful when several condition variables must share the
235same lock.)
236
237A condition variable has \method{acquire()} and \method{release()}
238methods that call the corresponding methods of the associated lock.
239It also has a \method{wait()} method, and \method{notify()} and
240\method{notifyAll()} methods. These three must only be called when
241the calling thread has acquired the lock.
242
243The \method{wait()} method releases the lock, and then blocks until it
244is awakened by a \method{notify()} or \method{notifyAll()} call for
245the same condition variable in another thread. Once awakened, it
246re-acquires the lock and returns. It is also possible to specify a
247timeout.
248
249The \method{notify()} method wakes up one of the threads waiting for
250the condition variable, if any are waiting. The \method{notifyAll()}
251method wakes up all threads waiting for the condition variable.
252
253Note: the \method{notify()} and \method{notifyAll()} methods don't
254release the lock; this means that the thread or threads awakened will
255not return from their \method{wait()} call immediately, but only when
256the thread that called \method{notify()} or \method{notifyAll()}
257finally relinquishes ownership of the lock.
258
259Tip: the typical programming style using condition variables uses the
260lock to synchronize access to some shared state; threads that are
261interested in a particular change of state call \method{wait()}
262repeatedly until they see the desired state, while threads that modify
263the state call \method{notify()} or \method{notifyAll()} when they
264change the state in such a way that it could possibly be a desired
265state for one of the waiters. For example, the following code is a
266generic producer-consumer situation with unlimited buffer capacity:
267
268\begin{verbatim}
269# Consume one item
270cv.acquire()
271while not an_item_is_available():
272 cv.wait()
273get_an_available_item()
274cv.release()
275
276# Produce one item
277cv.acquire()
278make_an_item_available()
279cv.notify()
280cv.release()
281\end{verbatim}
282
283To choose between \method{notify()} and \method{notifyAll()}, consider
284whether one state change can be interesting for only one or several
285waiting threads. E.g. in a typical producer-consumer situation,
286adding one item to the buffer only needs to wake up one consumer
287thread.
288
Fred Drakebf5a6d21999-03-12 19:57:38 +0000289\begin{classdesc}{Condition}{\optional{lock}}
290If the \var{lock} argument is given and not \code{None}, it must be a
291\class{Lock} or \class{RLock} object, and it is used as the underlying
292lock. Otherwise, a new \class{RLock} object is created and used as
293the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000294\end{classdesc}
295
296\begin{methoddesc}{acquire}{*args}
297Acquire the underlying lock.
298This method calls the corresponding method on the underlying
299lock; the return value is whatever that method returns.
300\end{methoddesc}
301
302\begin{methoddesc}{release}{}
303Release the underlying lock.
304This method calls the corresponding method on the underlying
305lock; there is no return value.
306\end{methoddesc}
307
Fred Drakebf5a6d21999-03-12 19:57:38 +0000308\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000309Wait until notified or until a timeout occurs.
310This must only be called when the calling thread has acquired the
311lock.
312
313This method releases the underlying lock, and then blocks until it is
314awakened by a \method{notify()} or \method{notifyAll()} call for the
315same condition variable in another thread, or until the optional
316timeout occurs. Once awakened or timed out, it re-acquires the lock
317and returns.
318
Fred Drakebf5a6d21999-03-12 19:57:38 +0000319When the \var{timeout} argument is present and not \code{None}, it
320should be a floating point number specifying a timeout for the
321operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000322
Fred Drakebf5a6d21999-03-12 19:57:38 +0000323When the underlying lock is an \class{RLock}, it is not released using
324its \method{release()} method, since this may not actually unlock the
325lock when it was acquired multiple times recursively. Instead, an
326internal interface of the \class{RLock} class is used, which really
327unlocks it even when it has been recursively acquired several times.
328Another internal interface is then used to restore the recursion level
329when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000330\end{methoddesc}
331
332\begin{methoddesc}{notify}{}
333Wake up a thread waiting on this condition, if any.
334This must only be called when the calling thread has acquired the
335lock.
336
337This method wakes up one of the threads waiting for the condition
338variable, if any are waiting; it is a no-op if no threads are waiting.
339
340The current implementation wakes up exactly one thread, if any are
341waiting. However, it's not safe to rely on this behavior. A future,
342optimized implementation may occasionally wake up more than one
343thread.
344
345Note: the awakened thread does not actually return from its
346\method{wait()} call until it can reacquire the lock. Since
347\method{notify()} does not release the lock, its caller should.
348\end{methoddesc}
349
350\begin{methoddesc}{notifyAll}{}
351Wake up all threads waiting on this condition. This method acts like
352\method{notify()}, but wakes up all waiting threads instead of one.
353\end{methoddesc}
354
Fred Drakebf5a6d21999-03-12 19:57:38 +0000355
356\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000357
358This is one of the oldest synchronization primitives in the history of
359computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000360Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
361\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000362
363A semaphore manages an internal counter which is decremented by each
364\method{acquire()} call and incremented by each \method{release()}
365call. The counter can never go below zero; when \method{acquire()}
366finds that it is zero, it blocks, waiting until some other thread
367calls \method{release()}.
368
Fred Drakebf5a6d21999-03-12 19:57:38 +0000369\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000370The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000371counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000372\end{classdesc}
373
Fred Drakebf5a6d21999-03-12 19:57:38 +0000374\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000375Acquire a semaphore.
376
377When invoked without arguments: if the internal counter is larger than
378zero on entry, decrement it by one and return immediately. If it is
379zero on entry, block, waiting until some other thread has called
380\method{release()} to make it larger than zero. This is done with
381proper interlocking so that if multiple \method{acquire()} calls are
382blocked, \method{release()} will wake exactly one of them up. The
383implementation may pick one at random, so the order in which blocked
384threads are awakened should not be relied on. There is no return
385value in this case.
386
Fred Drakebf5a6d21999-03-12 19:57:38 +0000387When invoked with \var{blocking} set to true, do the same thing as
388when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000389
Fred Drakebf5a6d21999-03-12 19:57:38 +0000390When invoked with \var{blocking} set to false, do not block. If a
391call without an argument would block, return false immediately;
392otherwise, do the same thing as when called without arguments, and
393return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000394\end{methoddesc}
395
396\begin{methoddesc}{release}{}
397Release a semaphore,
398incrementing the internal counter by one. When it was zero on
399entry and another thread is waiting for it to become larger
400than zero again, wake up that thread.
401\end{methoddesc}
402
Fred Drakebf5a6d21999-03-12 19:57:38 +0000403
Fred Drake31d833d2001-08-20 18:49:00 +0000404\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
405
406Semaphores are often used to guard resources with limited capacity, for
407example, a database server. In any situation where the size of the resource
408size is fixed, you should use a bounded semaphore. Before spawning any
409worker threads, your main thread would initialize the semaphore:
410
411\begin{verbatim}
412maxconnections = 5
413...
414pool_sema = BoundedSemaphore(value=maxconnections)
415\end{verbatim}
416
417Once spawned, worker threads call the semaphore's acquire and release
418methods when they need to connect to the server:
419
420\begin{verbatim}
421pool_sema.acquire()
422conn = connectdb()
423... use connection ...
424conn.close()
425pool_sema.release()
426\end{verbatim}
427
428The use of a bounded semaphore reduces the chance that a programming error
429which causes the semaphore to be released more than it's acquired will go
430undetected.
431
Fred Drake12686782002-03-19 14:37:44 +0000432
Fred Drakebf5a6d21999-03-12 19:57:38 +0000433\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000434
435This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000436threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000437
438An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000439the \method{set()} method and reset to false with the \method{clear()}
440method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000441
442
443\begin{classdesc}{Event}{}
444The internal flag is initially false.
445\end{classdesc}
446
447\begin{methoddesc}{isSet}{}
448Return true if and only if the internal flag is true.
449\end{methoddesc}
450
451\begin{methoddesc}{set}{}
452Set the internal flag to true.
453All threads waiting for it to become true are awakened.
454Threads that call \method{wait()} once the flag is true will not block
455at all.
456\end{methoddesc}
457
458\begin{methoddesc}{clear}{}
459Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000460Subsequently, threads calling \method{wait()} will block until
461\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000462\end{methoddesc}
463
Fred Drakebf5a6d21999-03-12 19:57:38 +0000464\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000465Block until the internal flag is true.
466If the internal flag is true on entry, return immediately. Otherwise,
467block until another thread calls \method{set()} to set the flag to
468true, or until the optional timeout occurs.
469
470When the timeout argument is present and not \code{None}, it should be a
471floating point number specifying a timeout for the operation in
472seconds (or fractions thereof).
473\end{methoddesc}
474
Fred Drakebf5a6d21999-03-12 19:57:38 +0000475
476\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000477
478This class represents an activity that is run in a separate thread
479of control. There are two ways to specify the activity: by
480passing a callable object to the constructor, or by overriding the
481\method{run()} method in a subclass. No other methods (except for the
482constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000483\emph{only} override the \method{__init__()} and \method{run()}
484methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000485
486Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000487calling the thread's \method{start()} method. This invokes the
488\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000489
490Once the thread's activity is started, the thread is considered
491'alive' and 'active' (these concepts are almost, but not quite
492exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000493vague). It stops being alive and active when its \method{run()}
494method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000495exception. The \method{isAlive()} method tests whether the thread is
496alive.
497
Fred Drakebf5a6d21999-03-12 19:57:38 +0000498Other threads can call a thread's \method{join()} method. This blocks
499the calling thread until the thread whose \method{join()} method is
500called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000501
502A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000503set with the \method{setName()} method, and retrieved with the
504\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000505
506A thread can be flagged as a ``daemon thread''. The significance
507of this flag is that the entire Python program exits when only
508daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000509creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000510method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000511
512There is a ``main thread'' object; this corresponds to the
513initial thread of control in the Python program. It is not a
514daemon thread.
515
516There is the possibility that ``dummy thread objects'' are
517created. These are thread objects corresponding to ``alien
518threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000519threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000520have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000521active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000522deleted, since it is impossible to detect the termination of alien
523threads.
524
525
526\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000527 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000528This constructor should always be called with keyword
529arguments. Arguments are:
530
Fred Drakec19f3922001-05-31 20:24:07 +0000531\var{group} should be \code{None}; reserved for future extension when
532a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000533
Fred Drakec19f3922001-05-31 20:24:07 +0000534\var{target} is the callable object to be invoked by the
535\method{run()} method. Defaults to \code{None}, meaning nothing is
536called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000537
Fred Drakec19f3922001-05-31 20:24:07 +0000538\var{name} is the thread name. By default, a unique name is
539constructed of the form ``Thread-\var{N}'' where \var{N} is a small
540decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000541
Fred Drakec19f3922001-05-31 20:24:07 +0000542\var{args} is the argument tuple for the target invocation. Defaults
543to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000544
Fred Drakec19f3922001-05-31 20:24:07 +0000545\var{kwargs} is a dictionary of keyword arguments for the target
546invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000547
548If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000549to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000550before doing anything else to the thread.
551\end{classdesc}
552
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000553\begin{methoddesc}{start}{}
554Start the thread's activity.
555
556This must be called at most once per thread object. It
557arranges for the object's \method{run()} method to be invoked in a
558separate thread of control.
559\end{methoddesc}
560
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000561\begin{methoddesc}{run}{}
562Method representing the thread's activity.
563
564You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000565\method{run()} method invokes the callable object passed to the
566object's constructor as the \var{target} argument, if any, with
567sequential and keyword arguments taken from the \var{args} and
568\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000569\end{methoddesc}
570
Fred Drakebf5a6d21999-03-12 19:57:38 +0000571\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000572Wait until the thread terminates.
573This blocks the calling thread until the thread whose \method{join()}
574method is called terminates -- either normally or through an
575unhandled exception -- or until the optional timeout occurs.
576
Fred Drake12686782002-03-19 14:37:44 +0000577When the \var{timeout} argument is present and not \code{None}, it
578should be a floating point number specifying a timeout for the
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000579operation in seconds (or fractions thereof).
580
581A thread can be \method{join()}ed many times.
582
583A thread cannot join itself because this would cause a
584deadlock.
585
586It is an error to attempt to \method{join()} a thread before it has
587been started.
588\end{methoddesc}
589
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000590\begin{methoddesc}{getName}{}
591Return the thread's name.
592\end{methoddesc}
593
594\begin{methoddesc}{setName}{name}
595Set the thread's name.
596
597The name is a string used for identification purposes only.
598It has no semantics. Multiple threads may be given the same
599name. The initial name is set by the constructor.
600\end{methoddesc}
601
602\begin{methoddesc}{isAlive}{}
603Return whether the thread is alive.
604
605Roughly, a thread is alive from the moment the \method{start()} method
606returns until its \method{run()} method terminates.
607\end{methoddesc}
608
609\begin{methoddesc}{isDaemon}{}
610Return the thread's daemon flag.
611\end{methoddesc}
612
613\begin{methoddesc}{setDaemon}{daemonic}
614Set the thread's daemon flag to the Boolean value \var{daemonic}.
615This must be called before \method{start()} is called.
616
617The initial value is inherited from the creating thread.
618
619The entire Python program exits when no active non-daemon
620threads are left.
621\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000622
623
624\subsection{Timer Objects \label{timer-objects}}
625
Fred Drake12686782002-03-19 14:37:44 +0000626This class represents an action that should be run only after a
627certain amount of time has passed --- a timer. \class{Timer} is a
628subclass of \class{Thread} and as such also functions as an example of
629creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000630
Fred Drake12686782002-03-19 14:37:44 +0000631Timers are started, as with threads, by calling their \method{start()}
632method. The timer can be stopped (before its action has begun) by
633calling the \method{cancel()} method. The interval the timer will
634wait before executing its action may not be exactly the same as the
635interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000636
637For example:
638\begin{verbatim}
639def hello():
640 print "hello, world"
641
642t = Timer(30.0, hello)
643t.start() # after 30 seconds, "hello, world" will be printed
644\end{verbatim}
645
646\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
647Create a timer that will run \var{function} with arguments \var{args} and
648keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
649\end{classdesc}
650
651\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000652Stop the timer, and cancel the execution of the timer's action. This
653will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000654\end{methoddesc}