blob: cd77246dddd58d46da5f65206fe4b5b07d0e9a15 [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 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
Fred Drake31d833d2001-08-20 18:49:00 +000063\begin{funcdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000064A 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
Fred Drake31d833d2001-08-20 18:49:00 +000068without making the counter negative. If not given, \var{value} defaults to
691.
70\end{funcdesc}
71
72\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
73A factory function that returns a new bounded semaphore object. A bounded
74semaphore checks to make sure its current value doesn't exceed its initial
75value. If it does, \exception{ValueError} is raised. In most situations
76semaphores are used to guard resources with limited capacity. If the
77semaphore is released too many times it's a sign of a bug. If not given,
78\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000079\end{funcdesc}
80
Fred Drakec19f3922001-05-31 20:24:07 +000081\begin{classdesc*}{Thread}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000082A class that represents a thread of control. This class can be safely subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +000083\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000084
Martin v. Löwis44f86962001-09-05 13:44:54 +000085\begin{classdesc*}{Timer}{}
86A thread that executes a function after a specified interval has passed.
87\end{classdesc*}
88
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000089Detailed interfaces for the objects are documented below.
90
91The design of this module is loosely based on Java's threading model.
92However, where Java makes locks and condition variables basic behavior
93of every object, they are separate objects in Python. Python's \class{Thread}
94class supports a subset of the behavior of Java's Thread class;
95currently, there are no priorities, no thread groups, and threads
96cannot be destroyed, stopped, suspended, resumed, or interrupted. The
97static methods of Java's Thread class, when implemented, are mapped to
98module-level functions.
99
100All of the methods described below are executed atomically.
101
Fred Drakebf5a6d21999-03-12 19:57:38 +0000102
103\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000104
105A primitive lock is a synchronization primitive that is not owned
106by a particular thread when locked. In Python, it is currently
107the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000108directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000109
110A primitive lock is in one of two states, ``locked'' or ``unlocked''.
111It is created in the unlocked state. It has two basic methods,
112\method{acquire()} and \method{release()}. When the state is
113unlocked, \method{acquire()} changes the state to locked and returns
114immediately. When the state is locked, \method{acquire()} blocks
115until a call to \method{release()} in another thread changes it to
116unlocked, then the \method{acquire()} call resets it to locked and
117returns. The \method{release()} method should only be called in the
118locked state; it changes the state to unlocked and returns
119immediately. When more than one thread is blocked in
120\method{acquire()} waiting for the state to turn to unlocked, only one
121thread proceeds when a \method{release()} call resets the state to
122unlocked; which one of the waiting threads proceeds is not defined,
123and may vary across implementations.
124
125All methods are executed atomically.
126
Fred Drakebf5a6d21999-03-12 19:57:38 +0000127\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000128Acquire a lock, blocking or non-blocking.
129
130When invoked without arguments, block until the lock is
131unlocked, then set it to locked, and return. There is no
132return value in this case.
133
134When invoked with the \var{blocking} argument set to true, do the
135same thing as when called without arguments, and return true.
136
137When invoked with the \var{blocking} argument set to false, do not
138block. If a call without an argument would block, return false
139immediately; otherwise, do the same thing as when called
140without arguments, and return true.
141\end{methoddesc}
142
143\begin{methoddesc}{release}{}
144Release a lock.
145
146When the lock is locked, reset it to unlocked, and return. If
147any other threads are blocked waiting for the lock to become
148unlocked, allow exactly one of them to proceed.
149
150Do not call this method when the lock is unlocked.
151
152There is no return value.
153\end{methoddesc}
154
Fred Drakebf5a6d21999-03-12 19:57:38 +0000155
156\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000157
158A reentrant lock is a synchronization primitive that may be
159acquired multiple times by the same thread. Internally, it uses
160the concepts of ``owning thread'' and ``recursion level'' in
161addition to the locked/unlocked state used by primitive locks. In
162the locked state, some thread owns the lock; in the unlocked
163state, no thread owns it.
164
165To lock the lock, a thread calls its \method{acquire()} method; this
166returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000167thread calls its \method{release()} method.
168\method{acquire()}/\method{release()} call pairs may be nested; only
169the final \method{release()} (the \method{release()} of the outermost
170pair) resets the lock to unlocked and allows another thread blocked in
171\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000172
Fred Drakebf5a6d21999-03-12 19:57:38 +0000173\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000174Acquire a lock, blocking or non-blocking.
175
176When invoked without arguments: if this thread already owns
177the lock, increment the recursion level by one, and return
178immediately. Otherwise, if another thread owns the lock,
179block until the lock is unlocked. Once the lock is unlocked
180(not owned by any thread), then grab ownership, set the
181recursion level to one, and return. If more than one thread
182is blocked waiting until the lock is unlocked, only one at a
183time will be able to grab ownership of the lock. There is no
184return value in this case.
185
186When invoked with the \var{blocking} argument set to true, do the
187same thing as when called without arguments, and return true.
188
189When invoked with the \var{blocking} argument set to false, do not
190block. If a call without an argument would block, return false
191immediately; otherwise, do the same thing as when called
192without arguments, and return true.
193\end{methoddesc}
194
195\begin{methoddesc}{release}{}
196Release a lock, decrementing the recursion level. If after the
197decrement it is zero, reset the lock to unlocked (not owned by any
198thread), and if any other threads are blocked waiting for the lock to
199become unlocked, allow exactly one of them to proceed. If after the
200decrement the recursion level is still nonzero, the lock remains
201locked and owned by the calling thread.
202
203Only call this method when the calling thread owns the lock.
204Do not call this method when the lock is unlocked.
205
206There is no return value.
207\end{methoddesc}
208
Fred Drakebf5a6d21999-03-12 19:57:38 +0000209
210\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000211
212A condition variable is always associated with some kind of lock;
213this can be passed in or one will be created by default. (Passing
214one in is useful when several condition variables must share the
215same lock.)
216
217A condition variable has \method{acquire()} and \method{release()}
218methods that call the corresponding methods of the associated lock.
219It also has a \method{wait()} method, and \method{notify()} and
220\method{notifyAll()} methods. These three must only be called when
221the calling thread has acquired the lock.
222
223The \method{wait()} method releases the lock, and then blocks until it
224is awakened by a \method{notify()} or \method{notifyAll()} call for
225the same condition variable in another thread. Once awakened, it
226re-acquires the lock and returns. It is also possible to specify a
227timeout.
228
229The \method{notify()} method wakes up one of the threads waiting for
230the condition variable, if any are waiting. The \method{notifyAll()}
231method wakes up all threads waiting for the condition variable.
232
233Note: the \method{notify()} and \method{notifyAll()} methods don't
234release the lock; this means that the thread or threads awakened will
235not return from their \method{wait()} call immediately, but only when
236the thread that called \method{notify()} or \method{notifyAll()}
237finally relinquishes ownership of the lock.
238
239Tip: the typical programming style using condition variables uses the
240lock to synchronize access to some shared state; threads that are
241interested in a particular change of state call \method{wait()}
242repeatedly until they see the desired state, while threads that modify
243the state call \method{notify()} or \method{notifyAll()} when they
244change the state in such a way that it could possibly be a desired
245state for one of the waiters. For example, the following code is a
246generic producer-consumer situation with unlimited buffer capacity:
247
248\begin{verbatim}
249# Consume one item
250cv.acquire()
251while not an_item_is_available():
252 cv.wait()
253get_an_available_item()
254cv.release()
255
256# Produce one item
257cv.acquire()
258make_an_item_available()
259cv.notify()
260cv.release()
261\end{verbatim}
262
263To choose between \method{notify()} and \method{notifyAll()}, consider
264whether one state change can be interesting for only one or several
265waiting threads. E.g. in a typical producer-consumer situation,
266adding one item to the buffer only needs to wake up one consumer
267thread.
268
Fred Drakebf5a6d21999-03-12 19:57:38 +0000269\begin{classdesc}{Condition}{\optional{lock}}
270If the \var{lock} argument is given and not \code{None}, it must be a
271\class{Lock} or \class{RLock} object, and it is used as the underlying
272lock. Otherwise, a new \class{RLock} object is created and used as
273the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000274\end{classdesc}
275
276\begin{methoddesc}{acquire}{*args}
277Acquire the underlying lock.
278This method calls the corresponding method on the underlying
279lock; the return value is whatever that method returns.
280\end{methoddesc}
281
282\begin{methoddesc}{release}{}
283Release the underlying lock.
284This method calls the corresponding method on the underlying
285lock; there is no return value.
286\end{methoddesc}
287
Fred Drakebf5a6d21999-03-12 19:57:38 +0000288\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000289Wait until notified or until a timeout occurs.
290This must only be called when the calling thread has acquired the
291lock.
292
293This method releases the underlying lock, and then blocks until it is
294awakened by a \method{notify()} or \method{notifyAll()} call for the
295same condition variable in another thread, or until the optional
296timeout occurs. Once awakened or timed out, it re-acquires the lock
297and returns.
298
Fred Drakebf5a6d21999-03-12 19:57:38 +0000299When the \var{timeout} argument is present and not \code{None}, it
300should be a floating point number specifying a timeout for the
301operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000302
Fred Drakebf5a6d21999-03-12 19:57:38 +0000303When the underlying lock is an \class{RLock}, it is not released using
304its \method{release()} method, since this may not actually unlock the
305lock when it was acquired multiple times recursively. Instead, an
306internal interface of the \class{RLock} class is used, which really
307unlocks it even when it has been recursively acquired several times.
308Another internal interface is then used to restore the recursion level
309when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000310\end{methoddesc}
311
312\begin{methoddesc}{notify}{}
313Wake up a thread waiting on this condition, if any.
314This must only be called when the calling thread has acquired the
315lock.
316
317This method wakes up one of the threads waiting for the condition
318variable, if any are waiting; it is a no-op if no threads are waiting.
319
320The current implementation wakes up exactly one thread, if any are
321waiting. However, it's not safe to rely on this behavior. A future,
322optimized implementation may occasionally wake up more than one
323thread.
324
325Note: the awakened thread does not actually return from its
326\method{wait()} call until it can reacquire the lock. Since
327\method{notify()} does not release the lock, its caller should.
328\end{methoddesc}
329
330\begin{methoddesc}{notifyAll}{}
331Wake up all threads waiting on this condition. This method acts like
332\method{notify()}, but wakes up all waiting threads instead of one.
333\end{methoddesc}
334
Fred Drakebf5a6d21999-03-12 19:57:38 +0000335
336\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000337
338This is one of the oldest synchronization primitives in the history of
339computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000340Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
341\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000342
343A semaphore manages an internal counter which is decremented by each
344\method{acquire()} call and incremented by each \method{release()}
345call. The counter can never go below zero; when \method{acquire()}
346finds that it is zero, it blocks, waiting until some other thread
347calls \method{release()}.
348
Fred Drakebf5a6d21999-03-12 19:57:38 +0000349\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000350The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000351counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000352\end{classdesc}
353
Fred Drakebf5a6d21999-03-12 19:57:38 +0000354\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000355Acquire a semaphore.
356
357When invoked without arguments: if the internal counter is larger than
358zero on entry, decrement it by one and return immediately. If it is
359zero on entry, block, waiting until some other thread has called
360\method{release()} to make it larger than zero. This is done with
361proper interlocking so that if multiple \method{acquire()} calls are
362blocked, \method{release()} will wake exactly one of them up. The
363implementation may pick one at random, so the order in which blocked
364threads are awakened should not be relied on. There is no return
365value in this case.
366
Fred Drakebf5a6d21999-03-12 19:57:38 +0000367When invoked with \var{blocking} set to true, do the same thing as
368when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000369
Fred Drakebf5a6d21999-03-12 19:57:38 +0000370When invoked with \var{blocking} set to false, do not block. If a
371call without an argument would block, return false immediately;
372otherwise, do the same thing as when called without arguments, and
373return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000374\end{methoddesc}
375
376\begin{methoddesc}{release}{}
377Release a semaphore,
378incrementing the internal counter by one. When it was zero on
379entry and another thread is waiting for it to become larger
380than zero again, wake up that thread.
381\end{methoddesc}
382
Fred Drakebf5a6d21999-03-12 19:57:38 +0000383
Fred Drake31d833d2001-08-20 18:49:00 +0000384\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
385
386Semaphores are often used to guard resources with limited capacity, for
387example, a database server. In any situation where the size of the resource
388size is fixed, you should use a bounded semaphore. Before spawning any
389worker threads, your main thread would initialize the semaphore:
390
391\begin{verbatim}
392maxconnections = 5
393...
394pool_sema = BoundedSemaphore(value=maxconnections)
395\end{verbatim}
396
397Once spawned, worker threads call the semaphore's acquire and release
398methods when they need to connect to the server:
399
400\begin{verbatim}
401pool_sema.acquire()
402conn = connectdb()
403... use connection ...
404conn.close()
405pool_sema.release()
406\end{verbatim}
407
408The use of a bounded semaphore reduces the chance that a programming error
409which causes the semaphore to be released more than it's acquired will go
410undetected.
411
Fred Drakebf5a6d21999-03-12 19:57:38 +0000412\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000413
414This is one of the simplest mechanisms for communication between
Fred Drake86119211999-04-23 20:07:02 +0000415threads: one thread signals an event and one or more other threads
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000416are waiting for it.
417
418An event object manages an internal flag that can be set to true with
419the \method{set()} method and reset to false with the \method{clear()} method. The
420\method{wait()} method blocks until the flag is true.
421
422
423\begin{classdesc}{Event}{}
424The internal flag is initially false.
425\end{classdesc}
426
427\begin{methoddesc}{isSet}{}
428Return true if and only if the internal flag is true.
429\end{methoddesc}
430
431\begin{methoddesc}{set}{}
432Set the internal flag to true.
433All threads waiting for it to become true are awakened.
434Threads that call \method{wait()} once the flag is true will not block
435at all.
436\end{methoddesc}
437
438\begin{methoddesc}{clear}{}
439Reset the internal flag to false.
440Subsequently, threads calling \method{wait()} will block until \method{set()} is
441called to set the internal flag to true again.
442\end{methoddesc}
443
Fred Drakebf5a6d21999-03-12 19:57:38 +0000444\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000445Block until the internal flag is true.
446If the internal flag is true on entry, return immediately. Otherwise,
447block until another thread calls \method{set()} to set the flag to
448true, or until the optional timeout occurs.
449
450When the timeout argument is present and not \code{None}, it should be a
451floating point number specifying a timeout for the operation in
452seconds (or fractions thereof).
453\end{methoddesc}
454
Fred Drakebf5a6d21999-03-12 19:57:38 +0000455
456\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000457
458This class represents an activity that is run in a separate thread
459of control. There are two ways to specify the activity: by
460passing a callable object to the constructor, or by overriding the
461\method{run()} method in a subclass. No other methods (except for the
462constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000463\emph{only} override the \method{__init__()} and \method{run()}
464methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000465
466Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000467calling the thread's \method{start()} method. This invokes the
468\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000469
470Once the thread's activity is started, the thread is considered
471'alive' and 'active' (these concepts are almost, but not quite
472exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000473vague). It stops being alive and active when its \method{run()}
474method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000475exception. The \method{isAlive()} method tests whether the thread is
476alive.
477
Fred Drakebf5a6d21999-03-12 19:57:38 +0000478Other threads can call a thread's \method{join()} method. This blocks
479the calling thread until the thread whose \method{join()} method is
480called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000481
482A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000483set with the \method{setName()} method, and retrieved with the
484\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000485
486A thread can be flagged as a ``daemon thread''. The significance
487of this flag is that the entire Python program exits when only
488daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000489creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000490method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000491
492There is a ``main thread'' object; this corresponds to the
493initial thread of control in the Python program. It is not a
494daemon thread.
495
496There is the possibility that ``dummy thread objects'' are
497created. These are thread objects corresponding to ``alien
498threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000499threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000500have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000501active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000502deleted, since it is impossible to detect the termination of alien
503threads.
504
505
506\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000507 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000508This constructor should always be called with keyword
509arguments. Arguments are:
510
Fred Drakec19f3922001-05-31 20:24:07 +0000511\var{group} should be \code{None}; reserved for future extension when
512a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000513
Fred Drakec19f3922001-05-31 20:24:07 +0000514\var{target} is the callable object to be invoked by the
515\method{run()} method. Defaults to \code{None}, meaning nothing is
516called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000517
Fred Drakec19f3922001-05-31 20:24:07 +0000518\var{name} is the thread name. By default, a unique name is
519constructed of the form ``Thread-\var{N}'' where \var{N} is a small
520decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000521
Fred Drakec19f3922001-05-31 20:24:07 +0000522\var{args} is the argument tuple for the target invocation. Defaults
523to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000524
Fred Drakec19f3922001-05-31 20:24:07 +0000525\var{kwargs} is a dictionary of keyword arguments for the target
526invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000527
528If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000529to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000530before doing anything else to the thread.
531\end{classdesc}
532
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000533\begin{methoddesc}{start}{}
534Start the thread's activity.
535
536This must be called at most once per thread object. It
537arranges for the object's \method{run()} method to be invoked in a
538separate thread of control.
539\end{methoddesc}
540
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000541\begin{methoddesc}{run}{}
542Method representing the thread's activity.
543
544You may override this method in a subclass. The standard
545\method{run()} method invokes the callable object passed to the object's constructor as the
546\var{target} argument, if any, with sequential and keyword
547arguments taken from the \var{args} and \var{kwargs} arguments,
548respectively.
549\end{methoddesc}
550
Fred Drakebf5a6d21999-03-12 19:57:38 +0000551\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000552Wait until the thread terminates.
553This blocks the calling thread until the thread whose \method{join()}
554method is called terminates -- either normally or through an
555unhandled exception -- or until the optional timeout occurs.
556
557When the \var{timeout} argument is present and not \code{None}, it should
558be a floating point number specifying a timeout for the
559operation in seconds (or fractions thereof).
560
561A thread can be \method{join()}ed many times.
562
563A thread cannot join itself because this would cause a
564deadlock.
565
566It is an error to attempt to \method{join()} a thread before it has
567been started.
568\end{methoddesc}
569
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000570\begin{methoddesc}{getName}{}
571Return the thread's name.
572\end{methoddesc}
573
574\begin{methoddesc}{setName}{name}
575Set the thread's name.
576
577The name is a string used for identification purposes only.
578It has no semantics. Multiple threads may be given the same
579name. The initial name is set by the constructor.
580\end{methoddesc}
581
582\begin{methoddesc}{isAlive}{}
583Return whether the thread is alive.
584
585Roughly, a thread is alive from the moment the \method{start()} method
586returns until its \method{run()} method terminates.
587\end{methoddesc}
588
589\begin{methoddesc}{isDaemon}{}
590Return the thread's daemon flag.
591\end{methoddesc}
592
593\begin{methoddesc}{setDaemon}{daemonic}
594Set the thread's daemon flag to the Boolean value \var{daemonic}.
595This must be called before \method{start()} is called.
596
597The initial value is inherited from the creating thread.
598
599The entire Python program exits when no active non-daemon
600threads are left.
601\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000602
603
604\subsection{Timer Objects \label{timer-objects}}
605
606This class represents an action that should be run only after a certain amount
607of time has passed --- a timer. \class{Timer} is a subclass of \class{Thread} and
608as such also functions as an example of creating custom threads.
609
610Timers are started, as with threads, by calling their \method{start()} method. The
611timer can be stopped (before its action has begun) by calling the
612\method{cancel()} method. The interval the timer will wait before executing
613its action may not be exactly the same as the interval specified by the
614user.
615
616For example:
617\begin{verbatim}
618def hello():
619 print "hello, world"
620
621t = Timer(30.0, hello)
622t.start() # after 30 seconds, "hello, world" will be printed
623\end{verbatim}
624
625\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
626Create a timer that will run \var{function} with arguments \var{args} and
627keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
628\end{classdesc}
629
630\begin{methoddesc}{cancel}{}
631Stop the timer, and cancel the execution of the timer's action. This will only
632work if the timer is still in its waiting stage.
633\end{methoddesc}