blob: 19c496e499d3de85cb258fb044831abf2a706cd2 [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}{}
Guido van Rossumd8faa362007-04-27 19:54:29 +000018Return the number of \class{Thread} objects currently alive. The
19returned count is equal to the length of the list returned by
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000020\function{enumerate()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000021\end{funcdesc}
22
Guido van Rossumd8faa362007-04-27 19:54:29 +000023\begin{funcdescni}{Condition}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000024A factory function that returns a new condition variable object.
25A condition variable allows one or more threads to wait until they
26are notified by another thread.
Guido van Rossumd8faa362007-04-27 19:54:29 +000027\end{funcdescni}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000028
29\begin{funcdesc}{currentThread}{}
30Return the current \class{Thread} object, corresponding to the
31caller's thread of control. If the caller's thread of control was not
32created through the
33\module{threading} module, a dummy thread object with limited functionality
34is returned.
35\end{funcdesc}
36
37\begin{funcdesc}{enumerate}{}
Guido van Rossumd8faa362007-04-27 19:54:29 +000038Return a list of all \class{Thread} objects currently alive. The list
39includes daemonic threads, dummy thread objects created by
40\function{currentThread()}, and the main thread. It excludes
41terminated threads and threads that have not yet been started.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000042\end{funcdesc}
43
Guido van Rossumd8faa362007-04-27 19:54:29 +000044\begin{funcdescni}{Event}{}
Fred Drake12686782002-03-19 14:37:44 +000045A factory function that returns a new event object. An event manages
46a flag that can be set to true with the \method{set()} method and
47reset to false with the \method{clear()} method. The \method{wait()}
48method blocks until the flag is true.
Guido van Rossumd8faa362007-04-27 19:54:29 +000049\end{funcdescni}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000050
Jim Fultond15dc062004-07-14 19:11:50 +000051\begin{classdesc*}{local}{}
52A class that represents thread-local data. Thread-local data are data
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000053whose values are thread specific. To manage thread-local data, just
Jim Fultond15dc062004-07-14 19:11:50 +000054create an instance of \class{local} (or a subclass) and store
55attributes on it:
56
57\begin{verbatim}
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000058mydata = threading.local()
59mydata.x = 1
Jim Fultond15dc062004-07-14 19:11:50 +000060\end{verbatim}
61
62The instance's values will be different for separate threads.
63
64For more details and extensive examples, see the documentation string
Andrew M. Kuchling872dc5c2004-07-17 13:35:43 +000065of the \module{_threading_local} module.
Jim Fultond15dc062004-07-14 19:11:50 +000066
67\versionadded{2.4}
68\end{classdesc*}
69
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000070\begin{funcdesc}{Lock}{}
71A factory function that returns a new primitive lock object. Once
72a thread has acquired it, subsequent attempts to acquire it block,
73until it is released; any thread may release it.
74\end{funcdesc}
75
76\begin{funcdesc}{RLock}{}
77A factory function that returns a new reentrant lock object.
78A reentrant lock must be released by the thread that acquired it.
79Once a thread has acquired a reentrant lock, the same thread may
80acquire it again without blocking; the thread must release it once
81for each time it has acquired it.
82\end{funcdesc}
83
Guido van Rossumd8faa362007-04-27 19:54:29 +000084\begin{funcdescni}{Semaphore}{\optional{value}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +000085A factory function that returns a new semaphore object. A
86semaphore manages a counter representing the number of \method{release()}
87calls minus the number of \method{acquire()} calls, plus an initial value.
88The \method{acquire()} method blocks if necessary until it can return
Fred Drake31d833d2001-08-20 18:49:00 +000089without making the counter negative. If not given, \var{value} defaults to
901.
Guido van Rossumd8faa362007-04-27 19:54:29 +000091\end{funcdescni}
Fred Drake31d833d2001-08-20 18:49:00 +000092
93\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
94A factory function that returns a new bounded semaphore object. A bounded
95semaphore checks to make sure its current value doesn't exceed its initial
96value. If it does, \exception{ValueError} is raised. In most situations
97semaphores are used to guard resources with limited capacity. If the
98semaphore is released too many times it's a sign of a bug. If not given,
99\var{value} defaults to 1.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000100\end{funcdesc}
101
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102\begin{classdesc*}{Thread}
Fred Drake12686782002-03-19 14:37:44 +0000103A class that represents a thread of control. This class can be safely
104subclassed in a limited fashion.
Fred Drakec19f3922001-05-31 20:24:07 +0000105\end{classdesc*}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000106
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107\begin{classdesc*}{Timer}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000108A thread that executes a function after a specified interval has passed.
109\end{classdesc*}
110
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000111\begin{funcdesc}{settrace}{func}
Fred Drake57288152003-06-29 18:12:23 +0000112Set a trace function\index{trace function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000113from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000114\function{sys.settrace()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000115method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000116\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000117\end{funcdesc}
118
119\begin{funcdesc}{setprofile}{func}
Fred Drake57288152003-06-29 18:12:23 +0000120Set a profile function\index{profile function} for all threads started
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000121from the \module{threading} module. The \var{func} will be passed to
Fred Drake57288152003-06-29 18:12:23 +0000122\function{sys.setprofile()} for each thread, before its \method{run()}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000123method is called.
Neal Norwitzecc71712003-06-30 21:47:47 +0000124\versionadded{2.3}
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000125\end{funcdesc}
126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127\begin{funcdesc}{stack_size}{\optional{size}}
128Return the thread stack size used when creating new threads. The
129optional \var{size} argument specifies the stack size to be used for
130subsequently created threads, and must be 0 (use platform or
131configured default) or a positive integer value of at least 32,768 (32kB).
132If changing the thread stack size is unsupported, a \exception{ThreadError}
133is raised. If the specified stack size is invalid, a \exception{ValueError}
134is raised and the stack size is unmodified. 32kB is currently the minimum
135supported stack size value to guarantee sufficient stack space for the
136interpreter itself. Note that some platforms may have particular
137restrictions on values for the stack size, such as requiring a minimum
138stack size > 32kB or requiring allocation in multiples of the system
139memory page size - platform documentation should be referred to for
140more information (4kB pages are common; using multiples of 4096 for
141the stack size is the suggested approach in the absence of more
142specific information).
143Availability: Windows, systems with \POSIX{} threads.
144\versionadded{2.5}
145\end{funcdesc}
146
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000147Detailed interfaces for the objects are documented below.
148
149The design of this module is loosely based on Java's threading model.
150However, where Java makes locks and condition variables basic behavior
151of every object, they are separate objects in Python. Python's \class{Thread}
152class supports a subset of the behavior of Java's Thread class;
153currently, there are no priorities, no thread groups, and threads
154cannot be destroyed, stopped, suspended, resumed, or interrupted. The
155static methods of Java's Thread class, when implemented, are mapped to
156module-level functions.
157
158All of the methods described below are executed atomically.
159
Fred Drakebf5a6d21999-03-12 19:57:38 +0000160
161\subsection{Lock Objects \label{lock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000162
163A primitive lock is a synchronization primitive that is not owned
164by a particular thread when locked. In Python, it is currently
165the lowest level synchronization primitive available, implemented
Fred Drakeffbe6871999-04-22 21:23:22 +0000166directly by the \refmodule{thread} extension module.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000167
168A primitive lock is in one of two states, ``locked'' or ``unlocked''.
169It is created in the unlocked state. It has two basic methods,
170\method{acquire()} and \method{release()}. When the state is
171unlocked, \method{acquire()} changes the state to locked and returns
172immediately. When the state is locked, \method{acquire()} blocks
173until a call to \method{release()} in another thread changes it to
174unlocked, then the \method{acquire()} call resets it to locked and
175returns. The \method{release()} method should only be called in the
176locked state; it changes the state to unlocked and returns
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000177immediately. If an attempt is made to release an unlocked lock, a
178\exception{RuntimeError} will be raised.
179
180When more than one thread is blocked in \method{acquire()} waiting for
181the state to turn to unlocked, only one thread proceeds when a
182\method{release()} call resets the state to unlocked; which one of the
183waiting threads proceeds is not defined, and may vary across
184implementations.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000185
186All methods are executed atomically.
187
Guido van Rossumd8faa362007-04-27 19:54:29 +0000188\begin{methoddesc}[Lock]{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000189Acquire a lock, blocking or non-blocking.
190
191When invoked without arguments, block until the lock is
Andrew M. Kuchling921879a2005-06-02 16:59:18 +0000192unlocked, then set it to locked, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000193
194When invoked with the \var{blocking} argument set to true, do the
195same thing as when called without arguments, and return true.
196
197When invoked with the \var{blocking} argument set to false, do not
198block. If a call without an argument would block, return false
199immediately; otherwise, do the same thing as when called
200without arguments, and return true.
201\end{methoddesc}
202
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203\begin{methoddesc}[Lock]{release}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000204Release a lock.
205
206When the lock is locked, reset it to unlocked, and return. If
207any other threads are blocked waiting for the lock to become
208unlocked, allow exactly one of them to proceed.
209
210Do not call this method when the lock is unlocked.
211
212There is no return value.
213\end{methoddesc}
214
Fred Drakebf5a6d21999-03-12 19:57:38 +0000215
216\subsection{RLock Objects \label{rlock-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000217
218A reentrant lock is a synchronization primitive that may be
219acquired multiple times by the same thread. Internally, it uses
220the concepts of ``owning thread'' and ``recursion level'' in
221addition to the locked/unlocked state used by primitive locks. In
222the locked state, some thread owns the lock; in the unlocked
223state, no thread owns it.
224
225To lock the lock, a thread calls its \method{acquire()} method; this
226returns once the thread owns the lock. To unlock the lock, a
Fred Drake907e76b2001-07-06 20:30:11 +0000227thread calls its \method{release()} method.
228\method{acquire()}/\method{release()} call pairs may be nested; only
229the final \method{release()} (the \method{release()} of the outermost
230pair) resets the lock to unlocked and allows another thread blocked in
231\method{acquire()} to proceed.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000232
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233\begin{methoddesc}[RLock]{acquire}{\optional{blocking\code{ = 1}}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000234Acquire a lock, blocking or non-blocking.
235
236When invoked without arguments: if this thread already owns
237the lock, increment the recursion level by one, and return
238immediately. Otherwise, if another thread owns the lock,
239block until the lock is unlocked. Once the lock is unlocked
240(not owned by any thread), then grab ownership, set the
241recursion level to one, and return. If more than one thread
242is blocked waiting until the lock is unlocked, only one at a
243time will be able to grab ownership of the lock. There is no
244return value in this case.
245
246When invoked with the \var{blocking} argument set to true, do the
247same thing as when called without arguments, and return true.
248
249When invoked with the \var{blocking} argument set to false, do not
250block. If a call without an argument would block, return false
251immediately; otherwise, do the same thing as when called
252without arguments, and return true.
253\end{methoddesc}
254
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255\begin{methoddesc}[RLock]{release}{}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000256Release a lock, decrementing the recursion level. If after the
257decrement it is zero, reset the lock to unlocked (not owned by any
258thread), and if any other threads are blocked waiting for the lock to
259become unlocked, allow exactly one of them to proceed. If after the
260decrement the recursion level is still nonzero, the lock remains
261locked and owned by the calling thread.
262
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000263Only call this method when the calling thread owns the lock. A
264\exception{RuntimeError} is raised if this method is called when the
265lock is unlocked.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000266
267There is no return value.
268\end{methoddesc}
269
Fred Drakebf5a6d21999-03-12 19:57:38 +0000270
271\subsection{Condition Objects \label{condition-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000272
273A condition variable is always associated with some kind of lock;
274this can be passed in or one will be created by default. (Passing
275one in is useful when several condition variables must share the
276same lock.)
277
278A condition variable has \method{acquire()} and \method{release()}
279methods that call the corresponding methods of the associated lock.
280It also has a \method{wait()} method, and \method{notify()} and
281\method{notifyAll()} methods. These three must only be called when
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000282the calling thread has acquired the lock, otherwise a
283\exception{RuntimeError} is raised.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000284
285The \method{wait()} method releases the lock, and then blocks until it
286is awakened by a \method{notify()} or \method{notifyAll()} call for
287the same condition variable in another thread. Once awakened, it
288re-acquires the lock and returns. It is also possible to specify a
289timeout.
290
291The \method{notify()} method wakes up one of the threads waiting for
292the condition variable, if any are waiting. The \method{notifyAll()}
293method wakes up all threads waiting for the condition variable.
294
295Note: the \method{notify()} and \method{notifyAll()} methods don't
296release the lock; this means that the thread or threads awakened will
297not return from their \method{wait()} call immediately, but only when
298the thread that called \method{notify()} or \method{notifyAll()}
299finally relinquishes ownership of the lock.
300
301Tip: the typical programming style using condition variables uses the
302lock to synchronize access to some shared state; threads that are
303interested in a particular change of state call \method{wait()}
304repeatedly until they see the desired state, while threads that modify
305the state call \method{notify()} or \method{notifyAll()} when they
306change the state in such a way that it could possibly be a desired
307state for one of the waiters. For example, the following code is a
308generic producer-consumer situation with unlimited buffer capacity:
309
310\begin{verbatim}
311# Consume one item
312cv.acquire()
313while not an_item_is_available():
314 cv.wait()
315get_an_available_item()
316cv.release()
317
318# Produce one item
319cv.acquire()
320make_an_item_available()
321cv.notify()
322cv.release()
323\end{verbatim}
324
325To choose between \method{notify()} and \method{notifyAll()}, consider
326whether one state change can be interesting for only one or several
327waiting threads. E.g. in a typical producer-consumer situation,
328adding one item to the buffer only needs to wake up one consumer
329thread.
330
Fred Drakebf5a6d21999-03-12 19:57:38 +0000331\begin{classdesc}{Condition}{\optional{lock}}
332If the \var{lock} argument is given and not \code{None}, it must be a
333\class{Lock} or \class{RLock} object, and it is used as the underlying
334lock. Otherwise, a new \class{RLock} object is created and used as
335the underlying lock.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000336\end{classdesc}
337
338\begin{methoddesc}{acquire}{*args}
339Acquire the underlying lock.
340This method calls the corresponding method on the underlying
341lock; the return value is whatever that method returns.
342\end{methoddesc}
343
344\begin{methoddesc}{release}{}
345Release the underlying lock.
346This method calls the corresponding method on the underlying
347lock; there is no return value.
348\end{methoddesc}
349
Fred Drakebf5a6d21999-03-12 19:57:38 +0000350\begin{methoddesc}{wait}{\optional{timeout}}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000351Wait until notified or until a timeout occurs. If the calling thread
352has not acquired the lock when this method is called, a
353\exception{RuntimeError} is raised.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000354
355This method releases the underlying lock, and then blocks until it is
356awakened by a \method{notify()} or \method{notifyAll()} call for the
357same condition variable in another thread, or until the optional
358timeout occurs. Once awakened or timed out, it re-acquires the lock
359and returns.
360
Fred Drakebf5a6d21999-03-12 19:57:38 +0000361When the \var{timeout} argument is present and not \code{None}, it
362should be a floating point number specifying a timeout for the
363operation in seconds (or fractions thereof).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000364
Fred Drakebf5a6d21999-03-12 19:57:38 +0000365When the underlying lock is an \class{RLock}, it is not released using
366its \method{release()} method, since this may not actually unlock the
367lock when it was acquired multiple times recursively. Instead, an
368internal interface of the \class{RLock} class is used, which really
369unlocks it even when it has been recursively acquired several times.
370Another internal interface is then used to restore the recursion level
371when the lock is reacquired.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000372\end{methoddesc}
373
374\begin{methoddesc}{notify}{}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000375Wake up a thread waiting on this condition, if any. Wait until
376notified or until a timeout occurs. If the calling thread has not
377acquired the lock when this method is called, a
378\exception{RuntimeError} is raised.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000379
380This method wakes up one of the threads waiting for the condition
381variable, if any are waiting; it is a no-op if no threads are waiting.
382
383The current implementation wakes up exactly one thread, if any are
384waiting. However, it's not safe to rely on this behavior. A future,
385optimized implementation may occasionally wake up more than one
386thread.
387
388Note: the awakened thread does not actually return from its
389\method{wait()} call until it can reacquire the lock. Since
390\method{notify()} does not release the lock, its caller should.
391\end{methoddesc}
392
393\begin{methoddesc}{notifyAll}{}
394Wake up all threads waiting on this condition. This method acts like
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000395\method{notify()}, but wakes up all waiting threads instead of one. If
396the calling thread has not acquired the lock when this method is
397called, a \exception{RuntimeError} is raised.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000398\end{methoddesc}
399
Fred Drakebf5a6d21999-03-12 19:57:38 +0000400
401\subsection{Semaphore Objects \label{semaphore-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000402
403This is one of the oldest synchronization primitives in the history of
404computer science, invented by the early Dutch computer scientist
Fred Drakebf5a6d21999-03-12 19:57:38 +0000405Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
406\method{acquire()} and \method{release()}).
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000407
408A semaphore manages an internal counter which is decremented by each
409\method{acquire()} call and incremented by each \method{release()}
410call. The counter can never go below zero; when \method{acquire()}
411finds that it is zero, it blocks, waiting until some other thread
412calls \method{release()}.
413
Fred Drakebf5a6d21999-03-12 19:57:38 +0000414\begin{classdesc}{Semaphore}{\optional{value}}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000415The optional argument gives the initial \var{value} for the internal
416counter; it defaults to \code{1}. If the \var{value} given is less
417than 0, \exception{ValueError} is raised.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000418\end{classdesc}
419
Fred Drakebf5a6d21999-03-12 19:57:38 +0000420\begin{methoddesc}{acquire}{\optional{blocking}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000421Acquire a semaphore.
422
423When invoked without arguments: if the internal counter is larger than
424zero on entry, decrement it by one and return immediately. If it is
425zero on entry, block, waiting until some other thread has called
426\method{release()} to make it larger than zero. This is done with
427proper interlocking so that if multiple \method{acquire()} calls are
428blocked, \method{release()} will wake exactly one of them up. The
429implementation may pick one at random, so the order in which blocked
430threads are awakened should not be relied on. There is no return
431value in this case.
432
Fred Drakebf5a6d21999-03-12 19:57:38 +0000433When invoked with \var{blocking} set to true, do the same thing as
434when called without arguments, and return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000435
Fred Drakebf5a6d21999-03-12 19:57:38 +0000436When invoked with \var{blocking} set to false, do not block. If a
437call without an argument would block, return false immediately;
438otherwise, do the same thing as when called without arguments, and
439return true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000440\end{methoddesc}
441
442\begin{methoddesc}{release}{}
443Release a semaphore,
444incrementing the internal counter by one. When it was zero on
445entry and another thread is waiting for it to become larger
446than zero again, wake up that thread.
447\end{methoddesc}
448
Fred Drakebf5a6d21999-03-12 19:57:38 +0000449
Fred Drake31d833d2001-08-20 18:49:00 +0000450\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}
451
452Semaphores are often used to guard resources with limited capacity, for
453example, a database server. In any situation where the size of the resource
454size is fixed, you should use a bounded semaphore. Before spawning any
455worker threads, your main thread would initialize the semaphore:
456
457\begin{verbatim}
458maxconnections = 5
459...
460pool_sema = BoundedSemaphore(value=maxconnections)
461\end{verbatim}
462
463Once spawned, worker threads call the semaphore's acquire and release
464methods when they need to connect to the server:
465
466\begin{verbatim}
467pool_sema.acquire()
468conn = connectdb()
469... use connection ...
470conn.close()
471pool_sema.release()
472\end{verbatim}
473
474The use of a bounded semaphore reduces the chance that a programming error
475which causes the semaphore to be released more than it's acquired will go
476undetected.
477
Fred Drake12686782002-03-19 14:37:44 +0000478
Fred Drakebf5a6d21999-03-12 19:57:38 +0000479\subsection{Event Objects \label{event-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000480
481This is one of the simplest mechanisms for communication between
Fred Drake12686782002-03-19 14:37:44 +0000482threads: one thread signals an event and other threads wait for it.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000483
484An event object manages an internal flag that can be set to true with
Fred Drake12686782002-03-19 14:37:44 +0000485the \method{set()} method and reset to false with the \method{clear()}
486method. The \method{wait()} method blocks until the flag is true.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000487
488
489\begin{classdesc}{Event}{}
490The internal flag is initially false.
491\end{classdesc}
492
493\begin{methoddesc}{isSet}{}
494Return true if and only if the internal flag is true.
495\end{methoddesc}
496
497\begin{methoddesc}{set}{}
498Set the internal flag to true.
499All threads waiting for it to become true are awakened.
500Threads that call \method{wait()} once the flag is true will not block
501at all.
502\end{methoddesc}
503
504\begin{methoddesc}{clear}{}
505Reset the internal flag to false.
Fred Drake12686782002-03-19 14:37:44 +0000506Subsequently, threads calling \method{wait()} will block until
507\method{set()} is called to set the internal flag to true again.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000508\end{methoddesc}
509
Fred Drakebf5a6d21999-03-12 19:57:38 +0000510\begin{methoddesc}{wait}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000511Block until the internal flag is true.
512If the internal flag is true on entry, return immediately. Otherwise,
513block until another thread calls \method{set()} to set the flag to
514true, or until the optional timeout occurs.
515
516When the timeout argument is present and not \code{None}, it should be a
517floating point number specifying a timeout for the operation in
518seconds (or fractions thereof).
519\end{methoddesc}
520
Fred Drakebf5a6d21999-03-12 19:57:38 +0000521
522\subsection{Thread Objects \label{thread-objects}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000523
524This class represents an activity that is run in a separate thread
525of control. There are two ways to specify the activity: by
526passing a callable object to the constructor, or by overriding the
527\method{run()} method in a subclass. No other methods (except for the
528constructor) should be overridden in a subclass. In other words,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000529\emph{only} override the \method{__init__()} and \method{run()}
530methods of this class.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000531
532Once a thread object is created, its activity must be started by
Fred Drakebf5a6d21999-03-12 19:57:38 +0000533calling the thread's \method{start()} method. This invokes the
534\method{run()} method in a separate thread of control.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000535
536Once the thread's activity is started, the thread is considered
Guido van Rossumd8faa362007-04-27 19:54:29 +0000537'alive'. It stops being alive when its \method{run()} method terminates
538-- either normally, or by raising an unhandled exception. The
539\method{isAlive()} method tests whether the thread is alive.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000540
Fred Drakebf5a6d21999-03-12 19:57:38 +0000541Other threads can call a thread's \method{join()} method. This blocks
542the calling thread until the thread whose \method{join()} method is
543called is terminated.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000544
545A thread has a name. The name can be passed to the constructor,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000546set with the \method{setName()} method, and retrieved with the
547\method{getName()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000548
549A thread can be flagged as a ``daemon thread''. The significance
550of this flag is that the entire Python program exits when only
551daemon threads are left. The initial value is inherited from the
Fred Drakebf5a6d21999-03-12 19:57:38 +0000552creating thread. The flag can be set with the \method{setDaemon()}
Fred Drakec19f3922001-05-31 20:24:07 +0000553method and retrieved with the \method{isDaemon()} method.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000554
555There is a ``main thread'' object; this corresponds to the
556initial thread of control in the Python program. It is not a
557daemon thread.
558
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559There is the possibility that ``dummy thread objects'' are created.
560These are thread objects corresponding to ``alien threads'', which
561are threads of control started outside the threading module, such as
562directly from C code. Dummy thread objects have limited
563functionality; they are always considered alive and daemonic, and
564cannot be \method{join()}ed. They are never deleted, since it is
565impossible to detect the termination of alien threads.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000566
567
568\begin{classdesc}{Thread}{group=None, target=None, name=None,
Fred Drakebf5a6d21999-03-12 19:57:38 +0000569 args=(), kwargs=\{\}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000570This constructor should always be called with keyword
571arguments. Arguments are:
572
Fred Drakec19f3922001-05-31 20:24:07 +0000573\var{group} should be \code{None}; reserved for future extension when
574a \class{ThreadGroup} class is implemented.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000575
Fred Drakec19f3922001-05-31 20:24:07 +0000576\var{target} is the callable object to be invoked by the
577\method{run()} method. Defaults to \code{None}, meaning nothing is
578called.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000579
Fred Drakec19f3922001-05-31 20:24:07 +0000580\var{name} is the thread name. By default, a unique name is
581constructed of the form ``Thread-\var{N}'' where \var{N} is a small
582decimal number.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000583
Fred Drakec19f3922001-05-31 20:24:07 +0000584\var{args} is the argument tuple for the target invocation. Defaults
585to \code{()}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000586
Fred Drakec19f3922001-05-31 20:24:07 +0000587\var{kwargs} is a dictionary of keyword arguments for the target
588invocation. Defaults to \code{\{\}}.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000589
590If the subclass overrides the constructor, it must make sure
Fred Drakebf5a6d21999-03-12 19:57:38 +0000591to invoke the base class constructor (\code{Thread.__init__()})
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000592before doing anything else to the thread.
593\end{classdesc}
594
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000595\begin{methoddesc}{start}{}
596Start the thread's activity.
597
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000598It must be called at most once per thread object. It arranges for the
599object's \method{run()} method to be invoked in a separate thread of
600control.
601
602This method will raise a \exception{RuntimeException} if called more
603than once on the same thread object.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000604\end{methoddesc}
605
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000606\begin{methoddesc}{run}{}
607Method representing the thread's activity.
608
609You may override this method in a subclass. The standard
Fred Drake12686782002-03-19 14:37:44 +0000610\method{run()} method invokes the callable object passed to the
611object's constructor as the \var{target} argument, if any, with
612sequential and keyword arguments taken from the \var{args} and
613\var{kwargs} arguments, respectively.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000614\end{methoddesc}
615
Fred Drakebf5a6d21999-03-12 19:57:38 +0000616\begin{methoddesc}{join}{\optional{timeout}}
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000617Wait until the thread terminates.
618This blocks the calling thread until the thread whose \method{join()}
619method is called terminates -- either normally or through an
620unhandled exception -- or until the optional timeout occurs.
621
Fred Drake12686782002-03-19 14:37:44 +0000622When the \var{timeout} argument is present and not \code{None}, it
623should be a floating point number specifying a timeout for the
Georg Brandl75d51062005-07-17 21:00:26 +0000624operation in seconds (or fractions thereof). As \method{join()} always
625returns \code{None}, you must call \method{isAlive()} to decide whether
626a timeout happened.
627
628When the \var{timeout} argument is not present or \code{None}, the
629operation will block until the thread terminates.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000630
631A thread can be \method{join()}ed many times.
632
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000633\method{join()} may throw a \exception{RuntimeError}, if an attempt is
634made to join the current thread as that would cause a deadlock. It is
635also an error to \method{join()} a thread before it has been started
636and attempts to do so raises same exception.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000637\end{methoddesc}
638
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000639\begin{methoddesc}{getName}{}
640Return the thread's name.
641\end{methoddesc}
642
643\begin{methoddesc}{setName}{name}
644Set the thread's name.
645
646The name is a string used for identification purposes only.
647It has no semantics. Multiple threads may be given the same
648name. The initial name is set by the constructor.
649\end{methoddesc}
650
651\begin{methoddesc}{isAlive}{}
652Return whether the thread is alive.
653
654Roughly, a thread is alive from the moment the \method{start()} method
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655returns until its \method{run()} method terminates. The module
656function \function{enumerate()} returns a list of all alive threads.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000657\end{methoddesc}
658
659\begin{methoddesc}{isDaemon}{}
660Return the thread's daemon flag.
661\end{methoddesc}
662
663\begin{methoddesc}{setDaemon}{daemonic}
664Set the thread's daemon flag to the Boolean value \var{daemonic}.
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000665This must be called before \method{start()} is called, otherwise
666\exception{RuntimeError} is raised.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000667
668The initial value is inherited from the creating thread.
669
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670The entire Python program exits when no alive non-daemon threads are
671left.
Andrew M. Kuchling16440e61998-07-20 13:46:10 +0000672\end{methoddesc}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000673
674
675\subsection{Timer Objects \label{timer-objects}}
676
Fred Drake12686782002-03-19 14:37:44 +0000677This class represents an action that should be run only after a
678certain amount of time has passed --- a timer. \class{Timer} is a
679subclass of \class{Thread} and as such also functions as an example of
680creating custom threads.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000681
Fred Drake12686782002-03-19 14:37:44 +0000682Timers are started, as with threads, by calling their \method{start()}
683method. The timer can be stopped (before its action has begun) by
684calling the \method{cancel()} method. The interval the timer will
685wait before executing its action may not be exactly the same as the
686interval specified by the user.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000687
688For example:
689\begin{verbatim}
690def hello():
691 print "hello, world"
692
693t = Timer(30.0, hello)
694t.start() # after 30 seconds, "hello, world" will be printed
695\end{verbatim}
696
697\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
698Create a timer that will run \var{function} with arguments \var{args} and
699keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
700\end{classdesc}
701
702\begin{methoddesc}{cancel}{}
Fred Drake12686782002-03-19 14:37:44 +0000703Stop the timer, and cancel the execution of the timer's action. This
704will only work if the timer is still in its waiting stage.
Martin v. Löwis44f86962001-09-05 13:44:54 +0000705\end{methoddesc}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000706
707\subsection{Using locks, conditions, and semaphores in the \keyword{with}
708statement \label{with-locks}}
709
710All of the objects provided by this module that have \method{acquire()} and
711\method{release()} methods can be used as context managers for a \keyword{with}
712statement. The \method{acquire()} method will be called when the block is
713entered, and \method{release()} will be called when the block is exited.
714
715Currently, \class{Lock}, \class{RLock}, \class{Condition}, \class{Semaphore},
716and \class{BoundedSemaphore} objects may be used as \keyword{with}
717statement context managers. For example:
718
719\begin{verbatim}
720from __future__ import with_statement
721import threading
722
723some_rlock = threading.RLock()
724
725with some_rlock:
726 print "some_rlock is locked while this executes"
727\end{verbatim}
728