blob: ad48feb5ec07f8c13ccaec83c74e02530ad330d3 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{threading} ---
Fred Drakebf5a6d21999-03-12 19:57:38 +00002 Higher-level threading interface}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drakebf5a6d21999-03-12 19:57:38 +00004\declaremodule{standard}{threading}
5\modulesynopsis{Higher-level threading interface.}
Fred Drakeb91e9341998-07-23 17:59:49 +00006
Andrew M. Kuchling16440e61998-07-20 13:46:10 +00007
Fred Drake9643c671998-07-27 22:06:12 +00008This module constructs higher-level threading interfaces on top of the
Fred Drakeffbe6871999-04-22 21:23:22 +00009lower level \refmodule{thread} module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000010
Fred Drake740f8002002-12-30 23:00:36 +000011The \refmodule[dummythreading]{dummy_threading} module is provided for
12situations where \module{threading} cannot be used because
13\refmodule{thread} is missing.
Guido van Rossum29692332002-12-30 22:34:10 +000014
Fred Drake11f89b72003-01-06 16:38:10 +000015This module defines the following functions and objects:
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000016
17\begin{funcdesc}{activeCount}{}
18Return the number of currently active \class{Thread} objects.
19The returned count is equal to the length of the list returned by
20\function{enumerate()}.
21A function that returns the number of currently active threads.
22\end{funcdesc}
23
24\begin{funcdesc}{Condition}{}
25A factory function that returns a new condition variable object.
26A condition variable allows one or more threads to wait until they
27are notified by another thread.
28\end{funcdesc}
29
30\begin{funcdesc}{currentThread}{}
31Return the current \class{Thread} object, corresponding to the
32caller's thread of control. If the caller's thread of control was not
33created through the
34\module{threading} module, a dummy thread object with limited functionality
35is returned.
36\end{funcdesc}
37
38\begin{funcdesc}{enumerate}{}
39Return a list of all currently active \class{Thread} objects.
40The list includes daemonic threads, dummy thread objects created
41by \function{currentThread()}, and the main thread. It excludes terminated
42threads and threads that have not yet been started.
43\end{funcdesc}
44
45\begin{funcdesc}{Event}{}
Fred Drake12686782002-03-19 14:37:44 +000046A factory function that returns a new event object. An event manages
47a flag that can be set to true with the \method{set()} method and
48reset to false with the \method{clear()} method. The \method{wait()}
49method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000050\end{funcdesc}
51
52\begin{funcdesc}{Lock}{}
53A factory function that returns a new primitive lock object. Once
54a thread has acquired it, subsequent attempts to acquire it block,
55until it is released; any thread may release it.
56\end{funcdesc}
57
58\begin{funcdesc}{RLock}{}
59A factory function that returns a new reentrant lock object.
60A reentrant lock must be released by the thread that acquired it.
61Once a thread has acquired a reentrant lock, the same thread may
62acquire it again without blocking; the thread must release it once
63for each time it has acquired it.
64\end{funcdesc}
65
Fred Drake31d833d2001-08-20 18:49:00 +000066\begin{funcdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000067A factory function that returns a new semaphore object. A
68semaphore manages a counter representing the number of \method{release()}
69calls minus the number of \method{acquire()} calls, plus an initial value.
70The \method{acquire()} method blocks if necessary until it can return
Fred Drake31d833d2001-08-20 18:49:00 +000071without making the counter negative. If not given, \var{value} defaults to
721.
73\end{funcdesc}
74
75\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
76A factory function that returns a new bounded semaphore object. A bounded
77semaphore checks to make sure its current value doesn't exceed its initial
78value. If it does, \exception{ValueError} is raised. In most situations
79semaphores are used to guard resources with limited capacity. If the
80semaphore is released too many times it's a sign of a bug. If not given,
81\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000082\end{funcdesc}
83
Fred Drakec19f3922001-05-31 20:24:07 +000084\begin{classdesc*}{Thread}{}
Fred Drake12686782002-03-19 14:37:44 +000085A class that represents a thread of control. This class can be safely
86subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +000087\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000088
Martin v. Löwis44f86962001-09-05 13:44:54 +000089\begin{classdesc*}{Timer}{}
90A thread that executes a function after a specified interval has passed.
91\end{classdesc*}
92
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000093\begin{funcdesc}{settrace}{func}
94Set a trace function \index{trace function} for all threads started
95from the \module{threading} module. The \var{func} will be passed to
96\cfuntion{sys.settrace} for each thread, before its \method{run}
97method is called.
98\end{funcdesc}
99
100\begin{funcdesc}{setprofile}{func}
101Set a profile function \index{profile function} for all threads started
102from the \module{threading} module. The \var{func} will be passed to
103\cfuntion{sys.setprofile} for each thread, before its \method{run}
104method is called.
105\end{funcdesc}
106
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000107Detailed interfaces for the objects are documented below.
108
109The design of this module is loosely based on Java's threading model.
110However, where Java makes locks and condition variables basic behavior
111of every object, they are separate objects in Python. Python's \class{Thread}
112class supports a subset of the behavior of Java's Thread class;
113currently, there are no priorities, no thread groups, and threads
114cannot be destroyed, stopped, suspended, resumed, or interrupted. The
115static methods of Java's Thread class, when implemented, are mapped to
116module-level functions.
117
118All of the methods described below are executed atomically.
119
Fred Drakebf5a6d21999-03-12 19:57:38 +0000120
121\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000122
123A primitive lock is a synchronization primitive that is not owned
124by a particular thread when locked. In Python, it is currently
125the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000126directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000127
128A primitive lock is in one of two states, ``locked'' or ``unlocked''.
129It is created in the unlocked state. It has two basic methods,
130\method{acquire()} and \method{release()}. When the state is
131unlocked, \method{acquire()} changes the state to locked and returns
132immediately. When the state is locked, \method{acquire()} blocks
133until a call to \method{release()} in another thread changes it to
134unlocked, then the \method{acquire()} call resets it to locked and
135returns. The \method{release()} method should only be called in the
136locked state; it changes the state to unlocked and returns
137immediately. When more than one thread is blocked in
138\method{acquire()} waiting for the state to turn to unlocked, only one
139thread proceeds when a \method{release()} call resets the state to
140unlocked; which one of the waiting threads proceeds is not defined,
141and may vary across implementations.
142
143All methods are executed atomically.
144
Fred Drakebf5a6d21999-03-12 19:57:38 +0000145\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000146Acquire a lock, blocking or non-blocking.
147
148When invoked without arguments, block until the lock is
149unlocked, then set it to locked, and return. There is no
150return value in this case.
151
152When invoked with the \var{blocking} argument set to true, do the
153same thing as when called without arguments, and return true.
154
155When invoked with the \var{blocking} argument set to false, do not
156block. If a call without an argument would block, return false
157immediately; otherwise, do the same thing as when called
158without arguments, and return true.
159\end{methoddesc}
160
161\begin{methoddesc}{release}{}
162Release a lock.
163
164When the lock is locked, reset it to unlocked, and return. If
165any other threads are blocked waiting for the lock to become
166unlocked, allow exactly one of them to proceed.
167
168Do not call this method when the lock is unlocked.
169
170There is no return value.
171\end{methoddesc}
172
Fred Drakebf5a6d21999-03-12 19:57:38 +0000173
174\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000175
176A reentrant lock is a synchronization primitive that may be
177acquired multiple times by the same thread. Internally, it uses
178the concepts of ``owning thread'' and ``recursion level'' in
179addition to the locked/unlocked state used by primitive locks. In
180the locked state, some thread owns the lock; in the unlocked
181state, no thread owns it.
182
183To lock the lock, a thread calls its \method{acquire()} method; this
184returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000185thread calls its \method{release()} method.
186\method{acquire()}/\method{release()} call pairs may be nested; only
187the final \method{release()} (the \method{release()} of the outermost
188pair) resets the lock to unlocked and allows another thread blocked in
189\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000190
Fred Drakebf5a6d21999-03-12 19:57:38 +0000191\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000192Acquire a lock, blocking or non-blocking.
193
194When invoked without arguments: if this thread already owns
195the lock, increment the recursion level by one, and return
196immediately. Otherwise, if another thread owns the lock,
197block until the lock is unlocked. Once the lock is unlocked
198(not owned by any thread), then grab ownership, set the
199recursion level to one, and return. If more than one thread
200is blocked waiting until the lock is unlocked, only one at a
201time will be able to grab ownership of the lock. There is no
202return value in this case.
203
204When invoked with the \var{blocking} argument set to true, do the
205same thing as when called without arguments, and return true.
206
207When invoked with the \var{blocking} argument set to false, do not
208block. If a call without an argument would block, return false
209immediately; otherwise, do the same thing as when called
210without arguments, and return true.
211\end{methoddesc}
212
213\begin{methoddesc}{release}{}
214Release a lock, decrementing the recursion level. If after the
215decrement it is zero, reset the lock to unlocked (not owned by any
216thread), and if any other threads are blocked waiting for the lock to
217become unlocked, allow exactly one of them to proceed. If after the
218decrement the recursion level is still nonzero, the lock remains
219locked and owned by the calling thread.
220
221Only call this method when the calling thread owns the lock.
222Do not call this method when the lock is unlocked.
223
224There is no return value.
225\end{methoddesc}
226
Fred Drakebf5a6d21999-03-12 19:57:38 +0000227
228\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000229
230A condition variable is always associated with some kind of lock;
231this can be passed in or one will be created by default. (Passing
232one in is useful when several condition variables must share the
233same lock.)
234
235A condition variable has \method{acquire()} and \method{release()}
236methods that call the corresponding methods of the associated lock.
237It also has a \method{wait()} method, and \method{notify()} and
238\method{notifyAll()} methods. These three must only be called when
239the calling thread has acquired the lock.
240
241The \method{wait()} method releases the lock, and then blocks until it
242is awakened by a \method{notify()} or \method{notifyAll()} call for
243the same condition variable in another thread. Once awakened, it
244re-acquires the lock and returns. It is also possible to specify a
245timeout.
246
247The \method{notify()} method wakes up one of the threads waiting for
248the condition variable, if any are waiting. The \method{notifyAll()}
249method wakes up all threads waiting for the condition variable.
250
251Note: the \method{notify()} and \method{notifyAll()} methods don't
252release the lock; this means that the thread or threads awakened will
253not return from their \method{wait()} call immediately, but only when
254the thread that called \method{notify()} or \method{notifyAll()}
255finally relinquishes ownership of the lock.
256
257Tip: the typical programming style using condition variables uses the
258lock to synchronize access to some shared state; threads that are
259interested in a particular change of state call \method{wait()}
260repeatedly until they see the desired state, while threads that modify
261the state call \method{notify()} or \method{notifyAll()} when they
262change the state in such a way that it could possibly be a desired
263state for one of the waiters. For example, the following code is a
264generic producer-consumer situation with unlimited buffer capacity:
265
266\begin{verbatim}
267# Consume one item
268cv.acquire()
269while not an_item_is_available():
270 cv.wait()
271get_an_available_item()
272cv.release()
273
274# Produce one item
275cv.acquire()
276make_an_item_available()
277cv.notify()
278cv.release()
279\end{verbatim}
280
281To choose between \method{notify()} and \method{notifyAll()}, consider
282whether one state change can be interesting for only one or several
283waiting threads. E.g. in a typical producer-consumer situation,
284adding one item to the buffer only needs to wake up one consumer
285thread.
286
Fred Drakebf5a6d21999-03-12 19:57:38 +0000287\begin{classdesc}{Condition}{\optional{lock}}
288If the \var{lock} argument is given and not \code{None}, it must be a
289\class{Lock} or \class{RLock} object, and it is used as the underlying
290lock. Otherwise, a new \class{RLock} object is created and used as
291the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000292\end{classdesc}
293
294\begin{methoddesc}{acquire}{*args}
295Acquire the underlying lock.
296This method calls the corresponding method on the underlying
297lock; the return value is whatever that method returns.
298\end{methoddesc}
299
300\begin{methoddesc}{release}{}
301Release the underlying lock.
302This method calls the corresponding method on the underlying
303lock; there is no return value.
304\end{methoddesc}
305
Fred Drakebf5a6d21999-03-12 19:57:38 +0000306\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000307Wait until notified or until a timeout occurs.
308This must only be called when the calling thread has acquired the
309lock.
310
311This method releases the underlying lock, and then blocks until it is
312awakened by a \method{notify()} or \method{notifyAll()} call for the
313same condition variable in another thread, or until the optional
314timeout occurs. Once awakened or timed out, it re-acquires the lock
315and returns.
316
Fred Drakebf5a6d21999-03-12 19:57:38 +0000317When the \var{timeout} argument is present and not \code{None}, it
318should be a floating point number specifying a timeout for the
319operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000320
Fred Drakebf5a6d21999-03-12 19:57:38 +0000321When the underlying lock is an \class{RLock}, it is not released using
322its \method{release()} method, since this may not actually unlock the
323lock when it was acquired multiple times recursively. Instead, an
324internal interface of the \class{RLock} class is used, which really
325unlocks it even when it has been recursively acquired several times.
326Another internal interface is then used to restore the recursion level
327when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000328\end{methoddesc}
329
330\begin{methoddesc}{notify}{}
331Wake up a thread waiting on this condition, if any.
332This must only be called when the calling thread has acquired the
333lock.
334
335This method wakes up one of the threads waiting for the condition
336variable, if any are waiting; it is a no-op if no threads are waiting.
337
338The current implementation wakes up exactly one thread, if any are
339waiting. However, it's not safe to rely on this behavior. A future,
340optimized implementation may occasionally wake up more than one
341thread.
342
343Note: the awakened thread does not actually return from its
344\method{wait()} call until it can reacquire the lock. Since
345\method{notify()} does not release the lock, its caller should.
346\end{methoddesc}
347
348\begin{methoddesc}{notifyAll}{}
349Wake up all threads waiting on this condition. This method acts like
350\method{notify()}, but wakes up all waiting threads instead of one.
351\end{methoddesc}
352
Fred Drakebf5a6d21999-03-12 19:57:38 +0000353
354\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000355
356This is one of the oldest synchronization primitives in the history of
357computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000358Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
359\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000360
361A semaphore manages an internal counter which is decremented by each
362\method{acquire()} call and incremented by each \method{release()}
363call. The counter can never go below zero; when \method{acquire()}
364finds that it is zero, it blocks, waiting until some other thread
365calls \method{release()}.
366
Fred Drakebf5a6d21999-03-12 19:57:38 +0000367\begin{classdesc}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000368The optional argument gives the initial value for the internal
Fred Drakebf5a6d21999-03-12 19:57:38 +0000369counter; it defaults to \code{1}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000370\end{classdesc}
371
Fred Drakebf5a6d21999-03-12 19:57:38 +0000372\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000373Acquire a semaphore.
374
375When invoked without arguments: if the internal counter is larger than
376zero on entry, decrement it by one and return immediately. If it is
377zero on entry, block, waiting until some other thread has called
378\method{release()} to make it larger than zero. This is done with
379proper interlocking so that if multiple \method{acquire()} calls are
380blocked, \method{release()} will wake exactly one of them up. The
381implementation may pick one at random, so the order in which blocked
382threads are awakened should not be relied on. There is no return
383value in this case.
384
Fred Drakebf5a6d21999-03-12 19:57:38 +0000385When invoked with \var{blocking} set to true, do the same thing as
386when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000387
Fred Drakebf5a6d21999-03-12 19:57:38 +0000388When invoked with \var{blocking} set to false, do not block. If a
389call without an argument would block, return false immediately;
390otherwise, do the same thing as when called without arguments, and
391return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000392\end{methoddesc}
393
394\begin{methoddesc}{release}{}
395Release a semaphore,
396incrementing the internal counter by one. When it was zero on
397entry and another thread is waiting for it to become larger
398than zero again, wake up that thread.
399\end{methoddesc}
400
Fred Drakebf5a6d21999-03-12 19:57:38 +0000401
Fred Drake31d833d2001-08-20 18:49:00 +0000402\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
403
404Semaphores are often used to guard resources with limited capacity, for
405example, a database server. In any situation where the size of the resource
406size is fixed, you should use a bounded semaphore. Before spawning any
407worker threads, your main thread would initialize the semaphore:
408
409\begin{verbatim}
410maxconnections = 5
411...
412pool_sema = BoundedSemaphore(value=maxconnections)
413\end{verbatim}
414
415Once spawned, worker threads call the semaphore's acquire and release
416methods when they need to connect to the server:
417
418\begin{verbatim}
419pool_sema.acquire()
420conn = connectdb()
421... use connection ...
422conn.close()
423pool_sema.release()
424\end{verbatim}
425
426The use of a bounded semaphore reduces the chance that a programming error
427which causes the semaphore to be released more than it's acquired will go
428undetected.
429
Fred Drake12686782002-03-19 14:37:44 +0000430
Fred Drakebf5a6d21999-03-12 19:57:38 +0000431\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000432
433This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000434threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000435
436An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000437the \method{set()} method and reset to false with the \method{clear()}
438method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000439
440
441\begin{classdesc}{Event}{}
442The internal flag is initially false.
443\end{classdesc}
444
445\begin{methoddesc}{isSet}{}
446Return true if and only if the internal flag is true.
447\end{methoddesc}
448
449\begin{methoddesc}{set}{}
450Set the internal flag to true.
451All threads waiting for it to become true are awakened.
452Threads that call \method{wait()} once the flag is true will not block
453at all.
454\end{methoddesc}
455
456\begin{methoddesc}{clear}{}
457Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000458Subsequently, threads calling \method{wait()} will block until
459\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000460\end{methoddesc}
461
Fred Drakebf5a6d21999-03-12 19:57:38 +0000462\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000463Block until the internal flag is true.
464If the internal flag is true on entry, return immediately. Otherwise,
465block until another thread calls \method{set()} to set the flag to
466true, or until the optional timeout occurs.
467
468When the timeout argument is present and not \code{None}, it should be a
469floating point number specifying a timeout for the operation in
470seconds (or fractions thereof).
471\end{methoddesc}
472
Fred Drakebf5a6d21999-03-12 19:57:38 +0000473
474\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000475
476This class represents an activity that is run in a separate thread
477of control. There are two ways to specify the activity: by
478passing a callable object to the constructor, or by overriding the
479\method{run()} method in a subclass. No other methods (except for the
480constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000481\emph{only} override the \method{__init__()} and \method{run()}
482methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000483
484Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000485calling the thread's \method{start()} method. This invokes the
486\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000487
488Once the thread's activity is started, the thread is considered
489'alive' and 'active' (these concepts are almost, but not quite
490exactly, the same; their definition is intentionally somewhat
Fred Drakebf5a6d21999-03-12 19:57:38 +0000491vague). It stops being alive and active when its \method{run()}
492method terminates -- either normally, or by raising an unhandled
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000493exception. The \method{isAlive()} method tests whether the thread is
494alive.
495
Fred Drakebf5a6d21999-03-12 19:57:38 +0000496Other threads can call a thread's \method{join()} method. This blocks
497the calling thread until the thread whose \method{join()} method is
498called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000499
500A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000501set with the \method{setName()} method, and retrieved with the
502\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000503
504A thread can be flagged as a ``daemon thread''. The significance
505of this flag is that the entire Python program exits when only
506daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000507creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000508method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000509
510There is a ``main thread'' object; this corresponds to the
511initial thread of control in the Python program. It is not a
512daemon thread.
513
514There is the possibility that ``dummy thread objects'' are
515created. These are thread objects corresponding to ``alien
516threads''. These are threads of control started outside the
Fred Drake907e76b2001-07-06 20:30:11 +0000517threading module, such as directly from C code. Dummy thread objects
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000518have limited functionality; they are always considered alive,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000519active, and daemonic, and cannot be \method{join()}ed. They are never
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000520deleted, since it is impossible to detect the termination of alien
521threads.
522
523
524\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000525 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000526This constructor should always be called with keyword
527arguments. Arguments are:
528
Fred Drakec19f3922001-05-31 20:24:07 +0000529\var{group} should be \code{None}; reserved for future extension when
530a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000531
Fred Drakec19f3922001-05-31 20:24:07 +0000532\var{target} is the callable object to be invoked by the
533\method{run()} method. Defaults to \code{None}, meaning nothing is
534called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000535
Fred Drakec19f3922001-05-31 20:24:07 +0000536\var{name} is the thread name. By default, a unique name is
537constructed of the form ``Thread-\var{N}'' where \var{N} is a small
538decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000539
Fred Drakec19f3922001-05-31 20:24:07 +0000540\var{args} is the argument tuple for the target invocation. Defaults
541to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000542
Fred Drakec19f3922001-05-31 20:24:07 +0000543\var{kwargs} is a dictionary of keyword arguments for the target
544invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000545
546If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000547to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000548before doing anything else to the thread.
549\end{classdesc}
550
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000551\begin{methoddesc}{start}{}
552Start the thread's activity.
553
554This must be called at most once per thread object. It
555arranges for the object's \method{run()} method to be invoked in a
556separate thread of control.
557\end{methoddesc}
558
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000559\begin{methoddesc}{run}{}
560Method representing the thread's activity.
561
562You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000563\method{run()} method invokes the callable object passed to the
564object's constructor as the \var{target} argument, if any, with
565sequential and keyword arguments taken from the \var{args} and
566\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000567\end{methoddesc}
568
Fred Drakebf5a6d21999-03-12 19:57:38 +0000569\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000570Wait until the thread terminates.
571This blocks the calling thread until the thread whose \method{join()}
572method is called terminates -- either normally or through an
573unhandled exception -- or until the optional timeout occurs.
574
Fred Drake12686782002-03-19 14:37:44 +0000575When the \var{timeout} argument is present and not \code{None}, it
576should be a floating point number specifying a timeout for the
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000577operation in seconds (or fractions thereof).
578
579A thread can be \method{join()}ed many times.
580
581A thread cannot join itself because this would cause a
582deadlock.
583
584It is an error to attempt to \method{join()} a thread before it has
585been started.
586\end{methoddesc}
587
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000588\begin{methoddesc}{getName}{}
589Return the thread's name.
590\end{methoddesc}
591
592\begin{methoddesc}{setName}{name}
593Set the thread's name.
594
595The name is a string used for identification purposes only.
596It has no semantics. Multiple threads may be given the same
597name. The initial name is set by the constructor.
598\end{methoddesc}
599
600\begin{methoddesc}{isAlive}{}
601Return whether the thread is alive.
602
603Roughly, a thread is alive from the moment the \method{start()} method
604returns until its \method{run()} method terminates.
605\end{methoddesc}
606
607\begin{methoddesc}{isDaemon}{}
608Return the thread's daemon flag.
609\end{methoddesc}
610
611\begin{methoddesc}{setDaemon}{daemonic}
612Set the thread's daemon flag to the Boolean value \var{daemonic}.
613This must be called before \method{start()} is called.
614
615The initial value is inherited from the creating thread.
616
617The entire Python program exits when no active non-daemon
618threads are left.
619\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000620
621
622\subsection{Timer Objects \label{timer-objects}}
623
Fred Drake12686782002-03-19 14:37:44 +0000624This class represents an action that should be run only after a
625certain amount of time has passed --- a timer. \class{Timer} is a
626subclass of \class{Thread} and as such also functions as an example of
627creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000628
Fred Drake12686782002-03-19 14:37:44 +0000629Timers are started, as with threads, by calling their \method{start()}
630method. The timer can be stopped (before its action has begun) by
631calling the \method{cancel()} method. The interval the timer will
632wait before executing its action may not be exactly the same as the
633interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000634
635For example:
636\begin{verbatim}
637def hello():
638 print "hello, world"
639
640t = Timer(30.0, hello)
641t.start() # after 30 seconds, "hello, world" will be printed
642\end{verbatim}
643
644\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
645Create a timer that will run \var{function} with arguments \var{args} and
646keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
647\end{classdesc}
648
649\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000650Stop the timer, and cancel the execution of the timer's action. This
651will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000652\end{methoddesc}