blob: 478ca84f7f276d4cef821c2f679f368f85376149 [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 Drake9643c671998-07-27 22:06:12 +000015This module is safe for use with \samp{from threading import *}. It
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000016defines the following functions and objects:
17
18\begin{funcdesc}{activeCount}{}
19Return the number of currently active \class{Thread} objects.
20The returned count is equal to the length of the list returned by
21\function{enumerate()}.
22A function that returns the number of currently active threads.
23\end{funcdesc}
24
25\begin{funcdesc}{Condition}{}
26A factory function that returns a new condition variable object.
27A condition variable allows one or more threads to wait until they
28are notified by another thread.
29\end{funcdesc}
30
31\begin{funcdesc}{currentThread}{}
32Return the current \class{Thread} object, corresponding to the
33caller's thread of control. If the caller's thread of control was not
34created through the
35\module{threading} module, a dummy thread object with limited functionality
36is returned.
37\end{funcdesc}
38
39\begin{funcdesc}{enumerate}{}
40Return a list of all currently active \class{Thread} objects.
41The list includes daemonic threads, dummy thread objects created
42by \function{currentThread()}, and the main thread. It excludes terminated
43threads and threads that have not yet been started.
44\end{funcdesc}
45
46\begin{funcdesc}{Event}{}
Fred Drake12686782002-03-19 14:37:44 +000047A factory function that returns a new event object. An event manages
48a flag that can be set to true with the \method{set()} method and
49reset to false with the \method{clear()} method. The \method{wait()}
50method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000051\end{funcdesc}
52
53\begin{funcdesc}{Lock}{}
54A factory function that returns a new primitive lock object. Once
55a thread has acquired it, subsequent attempts to acquire it block,
56until it is released; any thread may release it.
57\end{funcdesc}
58
59\begin{funcdesc}{RLock}{}
60A factory function that returns a new reentrant lock object.
61A reentrant lock must be released by the thread that acquired it.
62Once a thread has acquired a reentrant lock, the same thread may
63acquire it again without blocking; the thread must release it once
64for each time it has acquired it.
65\end{funcdesc}
66
Fred Drake31d833d2001-08-20 18:49:00 +000067\begin{funcdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000068A factory function that returns a new semaphore object. A
69semaphore manages a counter representing the number of \method{release()}
70calls minus the number of \method{acquire()} calls, plus an initial value.
71The \method{acquire()} method blocks if necessary until it can return
Fred Drake31d833d2001-08-20 18:49:00 +000072without making the counter negative. If not given, \var{value} defaults to
731.
74\end{funcdesc}
75
76\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
77A factory function that returns a new bounded semaphore object. A bounded
78semaphore checks to make sure its current value doesn't exceed its initial
79value. If it does, \exception{ValueError} is raised. In most situations
80semaphores are used to guard resources with limited capacity. If the
81semaphore is released too many times it's a sign of a bug. If not given,
82\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000083\end{funcdesc}
84
Fred Drakec19f3922001-05-31 20:24:07 +000085\begin{classdesc*}{Thread}{}
Fred Drake12686782002-03-19 14:37:44 +000086A class that represents a thread of control. This class can be safely
87subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +000088\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000089
Martin v. Löwis44f86962001-09-05 13:44:54 +000090\begin{classdesc*}{Timer}{}
91A thread that executes a function after a specified interval has passed.
92\end{classdesc*}
93
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000094Detailed interfaces for the objects are documented below.
95
96The design of this module is loosely based on Java's threading model.
97However, where Java makes locks and condition variables basic behavior
98of every object, they are separate objects in Python. Python's \class{Thread}
99class supports a subset of the behavior of Java's Thread class;
100currently, there are no priorities, no thread groups, and threads
101cannot be destroyed, stopped, suspended, resumed, or interrupted. The
102static methods of Java's Thread class, when implemented, are mapped to
103module-level functions.
104
105All of the methods described below are executed atomically.
106
Fred Drakebf5a6d21999-03-12 19:57:38 +0000107
108\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000109
110A primitive lock is a synchronization primitive that is not owned
111by a particular thread when locked. In Python, it is currently
112the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000113directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000114
115A primitive lock is in one of two states, ``locked'' or ``unlocked''.
116It is created in the unlocked state. It has two basic methods,
117\method{acquire()} and \method{release()}. When the state is
118unlocked, \method{acquire()} changes the state to locked and returns
119immediately. When the state is locked, \method{acquire()} blocks
120until a call to \method{release()} in another thread changes it to
121unlocked, then the \method{acquire()} call resets it to locked and
122returns. The \method{release()} method should only be called in the
123locked state; it changes the state to unlocked and returns
124immediately. When more than one thread is blocked in
125\method{acquire()} waiting for the state to turn to unlocked, only one
126thread proceeds when a \method{release()} call resets the state to
127unlocked; which one of the waiting threads proceeds is not defined,
128and may vary across implementations.
129
130All methods are executed atomically.
131
Fred Drakebf5a6d21999-03-12 19:57:38 +0000132\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000133Acquire a lock, blocking or non-blocking.
134
135When invoked without arguments, block until the lock is
136unlocked, then set it to locked, and return. There is no
137return value in this case.
138
139When invoked with the \var{blocking} argument set to true, do the
140same thing as when called without arguments, and return true.
141
142When invoked with the \var{blocking} argument set to false, do not
143block. If a call without an argument would block, return false
144immediately; otherwise, do the same thing as when called
145without arguments, and return true.
146\end{methoddesc}
147
148\begin{methoddesc}{release}{}
149Release a lock.
150
151When the lock is locked, reset it to unlocked, and return. If
152any other threads are blocked waiting for the lock to become
153unlocked, allow exactly one of them to proceed.
154
155Do not call this method when the lock is unlocked.
156
157There is no return value.
158\end{methoddesc}
159
Fred Drakebf5a6d21999-03-12 19:57:38 +0000160
161\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000162
163A reentrant lock is a synchronization primitive that may be
164acquired multiple times by the same thread. Internally, it uses
165the concepts of ``owning thread'' and ``recursion level'' in
166addition to the locked/unlocked state used by primitive locks. In
167the locked state, some thread owns the lock; in the unlocked
168state, no thread owns it.
169
170To lock the lock, a thread calls its \method{acquire()} method; this
171returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000172thread calls its \method{release()} method.
173\method{acquire()}/\method{release()} call pairs may be nested; only
174the final \method{release()} (the \method{release()} of the outermost
175pair) resets the lock to unlocked and allows another thread blocked in
176\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000177
Fred Drakebf5a6d21999-03-12 19:57:38 +0000178\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000179Acquire a lock, blocking or non-blocking.
180
181When invoked without arguments: if this thread already owns
182the lock, increment the recursion level by one, and return
183immediately. Otherwise, if another thread owns the lock,
184block until the lock is unlocked. Once the lock is unlocked
185(not owned by any thread), then grab ownership, set the
186recursion level to one, and return. If more than one thread
187is blocked waiting until the lock is unlocked, only one at a
188time will be able to grab ownership of the lock. There is no
189return value in this case.
190
191When invoked with the \var{blocking} argument set to true, do the
192same thing as when called without arguments, and return true.
193
194When invoked with the \var{blocking} argument set to false, do not
195block. If a call without an argument would block, return false
196immediately; otherwise, do the same thing as when called
197without arguments, and return true.
198\end{methoddesc}
199
200\begin{methoddesc}{release}{}
201Release a lock, decrementing the recursion level. If after the
202decrement it is zero, reset the lock to unlocked (not owned by any
203thread), and if any other threads are blocked waiting for the lock to
204become unlocked, allow exactly one of them to proceed. If after the
205decrement the recursion level is still nonzero, the lock remains
206locked and owned by the calling thread.
207
208Only call this method when the calling thread owns the lock.
209Do not call this method when the lock is unlocked.
210
211There is no return value.
212\end{methoddesc}
213
Fred Drakebf5a6d21999-03-12 19:57:38 +0000214
215\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000216
217A condition variable is always associated with some kind of lock;
218this can be passed in or one will be created by default. (Passing
219one in is useful when several condition variables must share the
220same lock.)
221
222A condition variable has \method{acquire()} and \method{release()}
223methods that call the corresponding methods of the associated lock.
224It also has a \method{wait()} method, and \method{notify()} and
225\method{notifyAll()} methods. These three must only be called when
226the calling thread has acquired the lock.
227
228The \method{wait()} method releases the lock, and then blocks until it
229is awakened by a \method{notify()} or \method{notifyAll()} call for
230the same condition variable in another thread. Once awakened, it
231re-acquires the lock and returns. It is also possible to specify a
232timeout.
233
234The \method{notify()} method wakes up one of the threads waiting for
235the condition variable, if any are waiting. The \method{notifyAll()}
236method wakes up all threads waiting for the condition variable.
237
238Note: the \method{notify()} and \method{notifyAll()} methods don't
239release the lock; this means that the thread or threads awakened will
240not return from their \method{wait()} call immediately, but only when
241the thread that called \method{notify()} or \method{notifyAll()}
242finally relinquishes ownership of the lock.
243
244Tip: the typical programming style using condition variables uses the
245lock to synchronize access to some shared state; threads that are
246interested in a particular change of state call \method{wait()}
247repeatedly until they see the desired state, while threads that modify
248the state call \method{notify()} or \method{notifyAll()} when they
249change the state in such a way that it could possibly be a desired
250state for one of the waiters. For example, the following code is a
251generic producer-consumer situation with unlimited buffer capacity:
252
253\begin{verbatim}
254# Consume one item
255cv.acquire()
256while not an_item_is_available():
257 cv.wait()
258get_an_available_item()
259cv.release()
260
261# Produce one item
262cv.acquire()
263make_an_item_available()
264cv.notify()
265cv.release()
266\end{verbatim}
267
268To choose between \method{notify()} and \method{notifyAll()}, consider
269whether one state change can be interesting for only one or several
270waiting threads. E.g. in a typical producer-consumer situation,
271adding one item to the buffer only needs to wake up one consumer
272thread.
273
Fred Drakebf5a6d21999-03-12 19:57:38 +0000274\begin{classdesc}{Condition}{\optional{lock}}
275If the \var{lock} argument is given and not \code{None}, it must be a
276\class{Lock} or \class{RLock} object, and it is used as the underlying
277lock. Otherwise, a new \class{RLock} object is created and used as
278the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000279\end{classdesc}
280
281\begin{methoddesc}{acquire}{*args}
282Acquire the underlying lock.
283This method calls the corresponding method on the underlying
284lock; the return value is whatever that method returns.
285\end{methoddesc}
286
287\begin{methoddesc}{release}{}
288Release the underlying lock.
289This method calls the corresponding method on the underlying
290lock; there is no return value.
291\end{methoddesc}
292
Fred Drakebf5a6d21999-03-12 19:57:38 +0000293\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000294Wait until notified or until a timeout occurs.
295This must only be called when the calling thread has acquired the
296lock.
297
298This method releases the underlying lock, and then blocks until it is
299awakened by a \method{notify()} or \method{notifyAll()} call for the
300same condition variable in another thread, or until the optional
301timeout occurs. Once awakened or timed out, it re-acquires the lock
302and returns.
303
Fred Drakebf5a6d21999-03-12 19:57:38 +0000304When the \var{timeout} argument is present and not \code{None}, it
305should be a floating point number specifying a timeout for the
306operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000307
Fred Drakebf5a6d21999-03-12 19:57:38 +0000308When the underlying lock is an \class{RLock}, it is not released using
309its \method{release()} method, since this may not actually unlock the
310lock when it was acquired multiple times recursively. Instead, an
311internal interface of the \class{RLock} class is used, which really
312unlocks it even when it has been recursively acquired several times.
313Another internal interface is then used to restore the recursion level
314when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000315\end{methoddesc}
316
317\begin{methoddesc}{notify}{}
318Wake up a thread waiting on this condition, if any.
319This must only be called when the calling thread has acquired the
320lock.
321
322This method wakes up one of the threads waiting for the condition
323variable, if any are waiting; it is a no-op if no threads are waiting.
324
325The current implementation wakes up exactly one thread, if any are
326waiting. However, it's not safe to rely on this behavior. A future,
327optimized implementation may occasionally wake up more than one
328thread.
329
330Note: the awakened thread does not actually return from its
331\method{wait()} call until it can reacquire the lock. Since
332\method{notify()} does not release the lock, its caller should.
333\end{methoddesc}
334
335\begin{methoddesc}{notifyAll}{}
336Wake up all threads waiting on this condition. This method acts like
337\method{notify()}, but wakes up all waiting threads instead of one.
338\end{methoddesc}
339
Fred Drakebf5a6d21999-03-12 19:57:38 +0000340
341\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000342
343This is one of the oldest synchronization primitives in the history of
344computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000345Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
346\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000347
348A semaphore manages an internal counter which is decremented by each
349\method{acquire()} call and incremented by each \method{release()}
350call. The counter can never go below zero; when \method{acquire()}
351finds that it is zero, it blocks, waiting until some other thread
352calls \method{release()}.
353
Fred Drakebf5a6d21999-03-12 19:57:38 +0000354\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000355The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000356counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000357\end{classdesc}
358
Fred Drakebf5a6d21999-03-12 19:57:38 +0000359\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000360Acquire a semaphore.
361
362When invoked without arguments: if the internal counter is larger than
363zero on entry, decrement it by one and return immediately. If it is
364zero on entry, block, waiting until some other thread has called
365\method{release()} to make it larger than zero. This is done with
366proper interlocking so that if multiple \method{acquire()} calls are
367blocked, \method{release()} will wake exactly one of them up. The
368implementation may pick one at random, so the order in which blocked
369threads are awakened should not be relied on. There is no return
370value in this case.
371
Fred Drakebf5a6d21999-03-12 19:57:38 +0000372When invoked with \var{blocking} set to true, do the same thing as
373when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000374
Fred Drakebf5a6d21999-03-12 19:57:38 +0000375When invoked with \var{blocking} set to false, do not block. If a
376call without an argument would block, return false immediately;
377otherwise, do the same thing as when called without arguments, and
378return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000379\end{methoddesc}
380
381\begin{methoddesc}{release}{}
382Release a semaphore,
383incrementing the internal counter by one. When it was zero on
384entry and another thread is waiting for it to become larger
385than zero again, wake up that thread.
386\end{methoddesc}
387
Fred Drakebf5a6d21999-03-12 19:57:38 +0000388
Fred Drake31d833d2001-08-20 18:49:00 +0000389\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
390
391Semaphores are often used to guard resources with limited capacity, for
392example, a database server. In any situation where the size of the resource
393size is fixed, you should use a bounded semaphore. Before spawning any
394worker threads, your main thread would initialize the semaphore:
395
396\begin{verbatim}
397maxconnections = 5
398...
399pool_sema = BoundedSemaphore(value=maxconnections)
400\end{verbatim}
401
402Once spawned, worker threads call the semaphore's acquire and release
403methods when they need to connect to the server:
404
405\begin{verbatim}
406pool_sema.acquire()
407conn = connectdb()
408... use connection ...
409conn.close()
410pool_sema.release()
411\end{verbatim}
412
413The use of a bounded semaphore reduces the chance that a programming error
414which causes the semaphore to be released more than it's acquired will go
415undetected.
416
Fred Drake12686782002-03-19 14:37:44 +0000417
Fred Drakebf5a6d21999-03-12 19:57:38 +0000418\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000419
420This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000421threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000422
423An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000424the \method{set()} method and reset to false with the \method{clear()}
425method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000426
427
428\begin{classdesc}{Event}{}
429The internal flag is initially false.
430\end{classdesc}
431
432\begin{methoddesc}{isSet}{}
433Return true if and only if the internal flag is true.
434\end{methoddesc}
435
436\begin{methoddesc}{set}{}
437Set the internal flag to true.
438All threads waiting for it to become true are awakened.
439Threads that call \method{wait()} once the flag is true will not block
440at all.
441\end{methoddesc}
442
443\begin{methoddesc}{clear}{}
444Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000445Subsequently, threads calling \method{wait()} will block until
446\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000447\end{methoddesc}
448
Fred Drakebf5a6d21999-03-12 19:57:38 +0000449\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000450Block until the internal flag is true.
451If the internal flag is true on entry, return immediately. Otherwise,
452block until another thread calls \method{set()} to set the flag to
453true, or until the optional timeout occurs.
454
455When the timeout argument is present and not \code{None}, it should be a
456floating point number specifying a timeout for the operation in
457seconds (or fractions thereof).
458\end{methoddesc}
459
Fred Drakebf5a6d21999-03-12 19:57:38 +0000460
461\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000462
463This class represents an activity that is run in a separate thread
464of control. There are two ways to specify the activity: by
465passing a callable object to the constructor, or by overriding the
466\method{run()} method in a subclass. No other methods (except for the
467constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000468\emph{only} override the \method{__init__()} and \method{run()}
469methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000470
471Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000472calling the thread's \method{start()} method. This invokes the
473\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000474
475Once the thread's activity is started, the thread is considered
476'alive' and 'active' (these concepts are almost, but not quite
477exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000478vague). It stops being alive and active when its \method{run()}
479method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000480exception. The \method{isAlive()} method tests whether the thread is
481alive.
482
Fred Drakebf5a6d21999-03-12 19:57:38 +0000483Other threads can call a thread's \method{join()} method. This blocks
484the calling thread until the thread whose \method{join()} method is
485called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000486
487A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000488set with the \method{setName()} method, and retrieved with the
489\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000490
491A thread can be flagged as a ``daemon thread''. The significance
492of this flag is that the entire Python program exits when only
493daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000494creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000495method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000496
497There is a ``main thread'' object; this corresponds to the
498initial thread of control in the Python program. It is not a
499daemon thread.
500
501There is the possibility that ``dummy thread objects'' are
502created. These are thread objects corresponding to ``alien
503threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000504threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000505have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000506active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000507deleted, since it is impossible to detect the termination of alien
508threads.
509
510
511\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000512 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000513This constructor should always be called with keyword
514arguments. Arguments are:
515
Fred Drakec19f3922001-05-31 20:24:07 +0000516\var{group} should be \code{None}; reserved for future extension when
517a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000518
Fred Drakec19f3922001-05-31 20:24:07 +0000519\var{target} is the callable object to be invoked by the
520\method{run()} method. Defaults to \code{None}, meaning nothing is
521called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000522
Fred Drakec19f3922001-05-31 20:24:07 +0000523\var{name} is the thread name. By default, a unique name is
524constructed of the form ``Thread-\var{N}'' where \var{N} is a small
525decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000526
Fred Drakec19f3922001-05-31 20:24:07 +0000527\var{args} is the argument tuple for the target invocation. Defaults
528to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000529
Fred Drakec19f3922001-05-31 20:24:07 +0000530\var{kwargs} is a dictionary of keyword arguments for the target
531invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000532
533If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000534to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000535before doing anything else to the thread.
536\end{classdesc}
537
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000538\begin{methoddesc}{start}{}
539Start the thread's activity.
540
541This must be called at most once per thread object. It
542arranges for the object's \method{run()} method to be invoked in a
543separate thread of control.
544\end{methoddesc}
545
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000546\begin{methoddesc}{run}{}
547Method representing the thread's activity.
548
549You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000550\method{run()} method invokes the callable object passed to the
551object's constructor as the \var{target} argument, if any, with
552sequential and keyword arguments taken from the \var{args} and
553\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000554\end{methoddesc}
555
Fred Drakebf5a6d21999-03-12 19:57:38 +0000556\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000557Wait until the thread terminates.
558This blocks the calling thread until the thread whose \method{join()}
559method is called terminates -- either normally or through an
560unhandled exception -- or until the optional timeout occurs.
561
Fred Drake12686782002-03-19 14:37:44 +0000562When the \var{timeout} argument is present and not \code{None}, it
563should be a floating point number specifying a timeout for the
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000564operation in seconds (or fractions thereof).
565
566A thread can be \method{join()}ed many times.
567
568A thread cannot join itself because this would cause a
569deadlock.
570
571It is an error to attempt to \method{join()} a thread before it has
572been started.
573\end{methoddesc}
574
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000575\begin{methoddesc}{getName}{}
576Return the thread's name.
577\end{methoddesc}
578
579\begin{methoddesc}{setName}{name}
580Set the thread's name.
581
582The name is a string used for identification purposes only.
583It has no semantics. Multiple threads may be given the same
584name. The initial name is set by the constructor.
585\end{methoddesc}
586
587\begin{methoddesc}{isAlive}{}
588Return whether the thread is alive.
589
590Roughly, a thread is alive from the moment the \method{start()} method
591returns until its \method{run()} method terminates.
592\end{methoddesc}
593
594\begin{methoddesc}{isDaemon}{}
595Return the thread's daemon flag.
596\end{methoddesc}
597
598\begin{methoddesc}{setDaemon}{daemonic}
599Set the thread's daemon flag to the Boolean value \var{daemonic}.
600This must be called before \method{start()} is called.
601
602The initial value is inherited from the creating thread.
603
604The entire Python program exits when no active non-daemon
605threads are left.
606\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000607
608
609\subsection{Timer Objects \label{timer-objects}}
610
Fred Drake12686782002-03-19 14:37:44 +0000611This class represents an action that should be run only after a
612certain amount of time has passed --- a timer. \class{Timer} is a
613subclass of \class{Thread} and as such also functions as an example of
614creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000615
Fred Drake12686782002-03-19 14:37:44 +0000616Timers are started, as with threads, by calling their \method{start()}
617method. The timer can be stopped (before its action has begun) by
618calling the \method{cancel()} method. The interval the timer will
619wait before executing its action may not be exactly the same as the
620interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000621
622For example:
623\begin{verbatim}
624def hello():
625 print "hello, world"
626
627t = Timer(30.0, hello)
628t.start() # after 30 seconds, "hello, world" will be printed
629\end{verbatim}
630
631\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
632Create a timer that will run \var{function} with arguments \var{args} and
633keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
634\end{classdesc}
635
636\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000637Stop the timer, and cancel the execution of the timer's action. This
638will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000639\end{methoddesc}