blob: a152a4d7e5efab3149d8ffc13aaa70c6a196120d [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}{}
Fred Drake12686782002-03-19 14:37:44 +000043A factory function that returns a new event object. An event manages
44a flag that can be set to true with the \method{set()} method and
45reset to false with the \method{clear()} method. The \method{wait()}
46method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000047\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}{}
Fred Drake12686782002-03-19 14:37:44 +000082A class that represents a thread of control. This class can be safely
83subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +000084\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000085
Martin v. Löwis44f86962001-09-05 13:44:54 +000086\begin{classdesc*}{Timer}{}
87A thread that executes a function after a specified interval has passed.
88\end{classdesc*}
89
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000090Detailed interfaces for the objects are documented below.
91
92The design of this module is loosely based on Java's threading model.
93However, where Java makes locks and condition variables basic behavior
94of every object, they are separate objects in Python. Python's \class{Thread}
95class supports a subset of the behavior of Java's Thread class;
96currently, there are no priorities, no thread groups, and threads
97cannot be destroyed, stopped, suspended, resumed, or interrupted. The
98static methods of Java's Thread class, when implemented, are mapped to
99module-level functions.
100
101All of the methods described below are executed atomically.
102
Fred Drakebf5a6d21999-03-12 19:57:38 +0000103
104\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000105
106A primitive lock is a synchronization primitive that is not owned
107by a particular thread when locked. In Python, it is currently
108the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000109directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000110
111A primitive lock is in one of two states, ``locked'' or ``unlocked''.
112It is created in the unlocked state. It has two basic methods,
113\method{acquire()} and \method{release()}. When the state is
114unlocked, \method{acquire()} changes the state to locked and returns
115immediately. When the state is locked, \method{acquire()} blocks
116until a call to \method{release()} in another thread changes it to
117unlocked, then the \method{acquire()} call resets it to locked and
118returns. The \method{release()} method should only be called in the
119locked state; it changes the state to unlocked and returns
120immediately. When more than one thread is blocked in
121\method{acquire()} waiting for the state to turn to unlocked, only one
122thread proceeds when a \method{release()} call resets the state to
123unlocked; which one of the waiting threads proceeds is not defined,
124and may vary across implementations.
125
126All methods are executed atomically.
127
Fred Drakebf5a6d21999-03-12 19:57:38 +0000128\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000129Acquire a lock, blocking or non-blocking.
130
131When invoked without arguments, block until the lock is
132unlocked, then set it to locked, and return. There is no
133return value in this case.
134
135When invoked with the \var{blocking} argument set to true, do the
136same thing as when called without arguments, and return true.
137
138When invoked with the \var{blocking} argument set to false, do not
139block. If a call without an argument would block, return false
140immediately; otherwise, do the same thing as when called
141without arguments, and return true.
142\end{methoddesc}
143
144\begin{methoddesc}{release}{}
145Release a lock.
146
147When the lock is locked, reset it to unlocked, and return. If
148any other threads are blocked waiting for the lock to become
149unlocked, allow exactly one of them to proceed.
150
151Do not call this method when the lock is unlocked.
152
153There is no return value.
154\end{methoddesc}
155
Fred Drakebf5a6d21999-03-12 19:57:38 +0000156
157\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000158
159A reentrant lock is a synchronization primitive that may be
160acquired multiple times by the same thread. Internally, it uses
161the concepts of ``owning thread'' and ``recursion level'' in
162addition to the locked/unlocked state used by primitive locks. In
163the locked state, some thread owns the lock; in the unlocked
164state, no thread owns it.
165
166To lock the lock, a thread calls its \method{acquire()} method; this
167returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000168thread calls its \method{release()} method.
169\method{acquire()}/\method{release()} call pairs may be nested; only
170the final \method{release()} (the \method{release()} of the outermost
171pair) resets the lock to unlocked and allows another thread blocked in
172\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000173
Fred Drakebf5a6d21999-03-12 19:57:38 +0000174\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000175Acquire a lock, blocking or non-blocking.
176
177When invoked without arguments: if this thread already owns
178the lock, increment the recursion level by one, and return
179immediately. Otherwise, if another thread owns the lock,
180block until the lock is unlocked. Once the lock is unlocked
181(not owned by any thread), then grab ownership, set the
182recursion level to one, and return. If more than one thread
183is blocked waiting until the lock is unlocked, only one at a
184time will be able to grab ownership of the lock. There is no
185return value in this case.
186
187When invoked with the \var{blocking} argument set to true, do the
188same thing as when called without arguments, and return true.
189
190When invoked with the \var{blocking} argument set to false, do not
191block. If a call without an argument would block, return false
192immediately; otherwise, do the same thing as when called
193without arguments, and return true.
194\end{methoddesc}
195
196\begin{methoddesc}{release}{}
197Release a lock, decrementing the recursion level. If after the
198decrement it is zero, reset the lock to unlocked (not owned by any
199thread), and if any other threads are blocked waiting for the lock to
200become unlocked, allow exactly one of them to proceed. If after the
201decrement the recursion level is still nonzero, the lock remains
202locked and owned by the calling thread.
203
204Only call this method when the calling thread owns the lock.
205Do not call this method when the lock is unlocked.
206
207There is no return value.
208\end{methoddesc}
209
Fred Drakebf5a6d21999-03-12 19:57:38 +0000210
211\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000212
213A condition variable is always associated with some kind of lock;
214this can be passed in or one will be created by default. (Passing
215one in is useful when several condition variables must share the
216same lock.)
217
218A condition variable has \method{acquire()} and \method{release()}
219methods that call the corresponding methods of the associated lock.
220It also has a \method{wait()} method, and \method{notify()} and
221\method{notifyAll()} methods. These three must only be called when
222the calling thread has acquired the lock.
223
224The \method{wait()} method releases the lock, and then blocks until it
225is awakened by a \method{notify()} or \method{notifyAll()} call for
226the same condition variable in another thread. Once awakened, it
227re-acquires the lock and returns. It is also possible to specify a
228timeout.
229
230The \method{notify()} method wakes up one of the threads waiting for
231the condition variable, if any are waiting. The \method{notifyAll()}
232method wakes up all threads waiting for the condition variable.
233
234Note: the \method{notify()} and \method{notifyAll()} methods don't
235release the lock; this means that the thread or threads awakened will
236not return from their \method{wait()} call immediately, but only when
237the thread that called \method{notify()} or \method{notifyAll()}
238finally relinquishes ownership of the lock.
239
240Tip: the typical programming style using condition variables uses the
241lock to synchronize access to some shared state; threads that are
242interested in a particular change of state call \method{wait()}
243repeatedly until they see the desired state, while threads that modify
244the state call \method{notify()} or \method{notifyAll()} when they
245change the state in such a way that it could possibly be a desired
246state for one of the waiters. For example, the following code is a
247generic producer-consumer situation with unlimited buffer capacity:
248
249\begin{verbatim}
250# Consume one item
251cv.acquire()
252while not an_item_is_available():
253 cv.wait()
254get_an_available_item()
255cv.release()
256
257# Produce one item
258cv.acquire()
259make_an_item_available()
260cv.notify()
261cv.release()
262\end{verbatim}
263
264To choose between \method{notify()} and \method{notifyAll()}, consider
265whether one state change can be interesting for only one or several
266waiting threads. E.g. in a typical producer-consumer situation,
267adding one item to the buffer only needs to wake up one consumer
268thread.
269
Fred Drakebf5a6d21999-03-12 19:57:38 +0000270\begin{classdesc}{Condition}{\optional{lock}}
271If the \var{lock} argument is given and not \code{None}, it must be a
272\class{Lock} or \class{RLock} object, and it is used as the underlying
273lock. Otherwise, a new \class{RLock} object is created and used as
274the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000275\end{classdesc}
276
277\begin{methoddesc}{acquire}{*args}
278Acquire the underlying lock.
279This method calls the corresponding method on the underlying
280lock; the return value is whatever that method returns.
281\end{methoddesc}
282
283\begin{methoddesc}{release}{}
284Release the underlying lock.
285This method calls the corresponding method on the underlying
286lock; there is no return value.
287\end{methoddesc}
288
Fred Drakebf5a6d21999-03-12 19:57:38 +0000289\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000290Wait until notified or until a timeout occurs.
291This must only be called when the calling thread has acquired the
292lock.
293
294This method releases the underlying lock, and then blocks until it is
295awakened by a \method{notify()} or \method{notifyAll()} call for the
296same condition variable in another thread, or until the optional
297timeout occurs. Once awakened or timed out, it re-acquires the lock
298and returns.
299
Fred Drakebf5a6d21999-03-12 19:57:38 +0000300When the \var{timeout} argument is present and not \code{None}, it
301should be a floating point number specifying a timeout for the
302operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000303
Fred Drakebf5a6d21999-03-12 19:57:38 +0000304When the underlying lock is an \class{RLock}, it is not released using
305its \method{release()} method, since this may not actually unlock the
306lock when it was acquired multiple times recursively. Instead, an
307internal interface of the \class{RLock} class is used, which really
308unlocks it even when it has been recursively acquired several times.
309Another internal interface is then used to restore the recursion level
310when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000311\end{methoddesc}
312
313\begin{methoddesc}{notify}{}
314Wake up a thread waiting on this condition, if any.
315This must only be called when the calling thread has acquired the
316lock.
317
318This method wakes up one of the threads waiting for the condition
319variable, if any are waiting; it is a no-op if no threads are waiting.
320
321The current implementation wakes up exactly one thread, if any are
322waiting. However, it's not safe to rely on this behavior. A future,
323optimized implementation may occasionally wake up more than one
324thread.
325
326Note: the awakened thread does not actually return from its
327\method{wait()} call until it can reacquire the lock. Since
328\method{notify()} does not release the lock, its caller should.
329\end{methoddesc}
330
331\begin{methoddesc}{notifyAll}{}
332Wake up all threads waiting on this condition. This method acts like
333\method{notify()}, but wakes up all waiting threads instead of one.
334\end{methoddesc}
335
Fred Drakebf5a6d21999-03-12 19:57:38 +0000336
337\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000338
339This is one of the oldest synchronization primitives in the history of
340computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000341Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
342\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000343
344A semaphore manages an internal counter which is decremented by each
345\method{acquire()} call and incremented by each \method{release()}
346call. The counter can never go below zero; when \method{acquire()}
347finds that it is zero, it blocks, waiting until some other thread
348calls \method{release()}.
349
Fred Drakebf5a6d21999-03-12 19:57:38 +0000350\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000351The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000352counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000353\end{classdesc}
354
Fred Drakebf5a6d21999-03-12 19:57:38 +0000355\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000356Acquire a semaphore.
357
358When invoked without arguments: if the internal counter is larger than
359zero on entry, decrement it by one and return immediately. If it is
360zero on entry, block, waiting until some other thread has called
361\method{release()} to make it larger than zero. This is done with
362proper interlocking so that if multiple \method{acquire()} calls are
363blocked, \method{release()} will wake exactly one of them up. The
364implementation may pick one at random, so the order in which blocked
365threads are awakened should not be relied on. There is no return
366value in this case.
367
Fred Drakebf5a6d21999-03-12 19:57:38 +0000368When invoked with \var{blocking} set to true, do the same thing as
369when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000370
Fred Drakebf5a6d21999-03-12 19:57:38 +0000371When invoked with \var{blocking} set to false, do not block. If a
372call without an argument would block, return false immediately;
373otherwise, do the same thing as when called without arguments, and
374return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000375\end{methoddesc}
376
377\begin{methoddesc}{release}{}
378Release a semaphore,
379incrementing the internal counter by one. When it was zero on
380entry and another thread is waiting for it to become larger
381than zero again, wake up that thread.
382\end{methoddesc}
383
Fred Drakebf5a6d21999-03-12 19:57:38 +0000384
Fred Drake31d833d2001-08-20 18:49:00 +0000385\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
386
387Semaphores are often used to guard resources with limited capacity, for
388example, a database server. In any situation where the size of the resource
389size is fixed, you should use a bounded semaphore. Before spawning any
390worker threads, your main thread would initialize the semaphore:
391
392\begin{verbatim}
393maxconnections = 5
394...
395pool_sema = BoundedSemaphore(value=maxconnections)
396\end{verbatim}
397
398Once spawned, worker threads call the semaphore's acquire and release
399methods when they need to connect to the server:
400
401\begin{verbatim}
402pool_sema.acquire()
403conn = connectdb()
404... use connection ...
405conn.close()
406pool_sema.release()
407\end{verbatim}
408
409The use of a bounded semaphore reduces the chance that a programming error
410which causes the semaphore to be released more than it's acquired will go
411undetected.
412
Fred Drake12686782002-03-19 14:37:44 +0000413
Fred Drakebf5a6d21999-03-12 19:57:38 +0000414\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000415
416This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000417threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000418
419An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000420the \method{set()} method and reset to false with the \method{clear()}
421method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000422
423
424\begin{classdesc}{Event}{}
425The internal flag is initially false.
426\end{classdesc}
427
428\begin{methoddesc}{isSet}{}
429Return true if and only if the internal flag is true.
430\end{methoddesc}
431
432\begin{methoddesc}{set}{}
433Set the internal flag to true.
434All threads waiting for it to become true are awakened.
435Threads that call \method{wait()} once the flag is true will not block
436at all.
437\end{methoddesc}
438
439\begin{methoddesc}{clear}{}
440Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000441Subsequently, threads calling \method{wait()} will block until
442\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000443\end{methoddesc}
444
Fred Drakebf5a6d21999-03-12 19:57:38 +0000445\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000446Block until the internal flag is true.
447If the internal flag is true on entry, return immediately. Otherwise,
448block until another thread calls \method{set()} to set the flag to
449true, or until the optional timeout occurs.
450
451When the timeout argument is present and not \code{None}, it should be a
452floating point number specifying a timeout for the operation in
453seconds (or fractions thereof).
454\end{methoddesc}
455
Fred Drakebf5a6d21999-03-12 19:57:38 +0000456
457\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000458
459This class represents an activity that is run in a separate thread
460of control. There are two ways to specify the activity: by
461passing a callable object to the constructor, or by overriding the
462\method{run()} method in a subclass. No other methods (except for the
463constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000464\emph{only} override the \method{__init__()} and \method{run()}
465methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000466
467Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000468calling the thread's \method{start()} method. This invokes the
469\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000470
471Once the thread's activity is started, the thread is considered
472'alive' and 'active' (these concepts are almost, but not quite
473exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000474vague). It stops being alive and active when its \method{run()}
475method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000476exception. The \method{isAlive()} method tests whether the thread is
477alive.
478
Fred Drakebf5a6d21999-03-12 19:57:38 +0000479Other threads can call a thread's \method{join()} method. This blocks
480the calling thread until the thread whose \method{join()} method is
481called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000482
483A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000484set with the \method{setName()} method, and retrieved with the
485\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000486
487A thread can be flagged as a ``daemon thread''. The significance
488of this flag is that the entire Python program exits when only
489daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000490creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000491method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000492
493There is a ``main thread'' object; this corresponds to the
494initial thread of control in the Python program. It is not a
495daemon thread.
496
497There is the possibility that ``dummy thread objects'' are
498created. These are thread objects corresponding to ``alien
499threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000500threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000501have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000502active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000503deleted, since it is impossible to detect the termination of alien
504threads.
505
506
507\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000508 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000509This constructor should always be called with keyword
510arguments. Arguments are:
511
Fred Drakec19f3922001-05-31 20:24:07 +0000512\var{group} should be \code{None}; reserved for future extension when
513a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000514
Fred Drakec19f3922001-05-31 20:24:07 +0000515\var{target} is the callable object to be invoked by the
516\method{run()} method. Defaults to \code{None}, meaning nothing is
517called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000518
Fred Drakec19f3922001-05-31 20:24:07 +0000519\var{name} is the thread name. By default, a unique name is
520constructed of the form ``Thread-\var{N}'' where \var{N} is a small
521decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000522
Fred Drakec19f3922001-05-31 20:24:07 +0000523\var{args} is the argument tuple for the target invocation. Defaults
524to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000525
Fred Drakec19f3922001-05-31 20:24:07 +0000526\var{kwargs} is a dictionary of keyword arguments for the target
527invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000528
529If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000530to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000531before doing anything else to the thread.
532\end{classdesc}
533
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000534\begin{methoddesc}{start}{}
535Start the thread's activity.
536
537This must be called at most once per thread object. It
538arranges for the object's \method{run()} method to be invoked in a
539separate thread of control.
540\end{methoddesc}
541
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000542\begin{methoddesc}{run}{}
543Method representing the thread's activity.
544
545You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000546\method{run()} method invokes the callable object passed to the
547object's constructor as the \var{target} argument, if any, with
548sequential and keyword arguments taken from the \var{args} and
549\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000550\end{methoddesc}
551
Fred Drakebf5a6d21999-03-12 19:57:38 +0000552\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000553Wait until the thread terminates.
554This blocks the calling thread until the thread whose \method{join()}
555method is called terminates -- either normally or through an
556unhandled exception -- or until the optional timeout occurs.
557
Fred Drake12686782002-03-19 14:37:44 +0000558When the \var{timeout} argument is present and not \code{None}, it
559should be a floating point number specifying a timeout for the
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000560operation in seconds (or fractions thereof).
561
562A thread can be \method{join()}ed many times.
563
564A thread cannot join itself because this would cause a
565deadlock.
566
567It is an error to attempt to \method{join()} a thread before it has
568been started.
569\end{methoddesc}
570
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000571\begin{methoddesc}{getName}{}
572Return the thread's name.
573\end{methoddesc}
574
575\begin{methoddesc}{setName}{name}
576Set the thread's name.
577
578The name is a string used for identification purposes only.
579It has no semantics. Multiple threads may be given the same
580name. The initial name is set by the constructor.
581\end{methoddesc}
582
583\begin{methoddesc}{isAlive}{}
584Return whether the thread is alive.
585
586Roughly, a thread is alive from the moment the \method{start()} method
587returns until its \method{run()} method terminates.
588\end{methoddesc}
589
590\begin{methoddesc}{isDaemon}{}
591Return the thread's daemon flag.
592\end{methoddesc}
593
594\begin{methoddesc}{setDaemon}{daemonic}
595Set the thread's daemon flag to the Boolean value \var{daemonic}.
596This must be called before \method{start()} is called.
597
598The initial value is inherited from the creating thread.
599
600The entire Python program exits when no active non-daemon
601threads are left.
602\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000603
604
605\subsection{Timer Objects \label{timer-objects}}
606
Fred Drake12686782002-03-19 14:37:44 +0000607This class represents an action that should be run only after a
608certain amount of time has passed --- a timer. \class{Timer} is a
609subclass of \class{Thread} and as such also functions as an example of
610creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000611
Fred Drake12686782002-03-19 14:37:44 +0000612Timers are started, as with threads, by calling their \method{start()}
613method. The timer can be stopped (before its action has begun) by
614calling the \method{cancel()} method. The interval the timer will
615wait before executing its action may not be exactly the same as the
616interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000617
618For example:
619\begin{verbatim}
620def hello():
621 print "hello, world"
622
623t = Timer(30.0, hello)
624t.start() # after 30 seconds, "hello, world" will be printed
625\end{verbatim}
626
627\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
628Create a timer that will run \var{function} with arguments \var{args} and
629keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
630\end{classdesc}
631
632\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000633Stop the timer, and cancel the execution of the timer's action. This
634will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000635\end{methoddesc}