1 \section{\module{threading
} ---
2 Higher-level threading interface
}
4 \declaremodule{standard
}{threading
}
5 \modulesynopsis{Higher-level threading interface.
}
8 This module constructs higher-level threading interfaces on top of the
9 lower level
\refmodule{thread
} module.
11 The
\refmodule[dummythreading
]{dummy_threading
} module is provided for
12 situations where
\module{threading
} cannot be used because
13 \refmodule{thread
} is missing.
15 This module is safe for use with
\samp{from threading import *
}. It
16 defines the following functions and objects:
18 \begin{funcdesc
}{activeCount
}{}
19 Return the number of currently active
\class{Thread
} objects.
20 The returned count is equal to the length of the list returned by
21 \function{enumerate()
}.
22 A function that returns the number of currently active threads.
25 \begin{funcdesc
}{Condition
}{}
26 A factory function that returns a new condition variable object.
27 A condition variable allows one or more threads to wait until they
28 are notified by another thread.
31 \begin{funcdesc
}{currentThread
}{}
32 Return the current
\class{Thread
} object, corresponding to the
33 caller's thread of control. If the caller's thread of control was not
35 \module{threading
} module, a dummy thread object with limited functionality
39 \begin{funcdesc
}{enumerate
}{}
40 Return a list of all currently active
\class{Thread
} objects.
41 The list includes daemonic threads, dummy thread objects created
42 by
\function{currentThread()
}, and the main thread. It excludes terminated
43 threads and threads that have not yet been started.
46 \begin{funcdesc
}{Event
}{}
47 A factory function that returns a new event object. An event manages
48 a flag that can be set to true with the
\method{set()
} method and
49 reset to false with the
\method{clear()
} method. The
\method{wait()
}
50 method blocks until the flag is true.
53 \begin{funcdesc
}{Lock
}{}
54 A factory function that returns a new primitive lock object. Once
55 a thread has acquired it, subsequent attempts to acquire it block,
56 until it is released; any thread may release it.
59 \begin{funcdesc
}{RLock
}{}
60 A factory function that returns a new reentrant lock object.
61 A reentrant lock must be released by the thread that acquired it.
62 Once a thread has acquired a reentrant lock, the same thread may
63 acquire it again without blocking; the thread must release it once
64 for each time it has acquired it.
67 \begin{funcdesc
}{Semaphore
}{\optional{value
}}
68 A factory function that returns a new semaphore object. A
69 semaphore manages a counter representing the number of
\method{release()
}
70 calls minus the number of
\method{acquire()
} calls, plus an initial value.
71 The
\method{acquire()
} method blocks if necessary until it can return
72 without making the counter negative. If not given,
\var{value
} defaults to
76 \begin{funcdesc
}{BoundedSemaphore
}{\optional{value
}}
77 A factory function that returns a new bounded semaphore object. A bounded
78 semaphore checks to make sure its current value doesn't exceed its initial
79 value. If it does,
\exception{ValueError
} is raised. In most situations
80 semaphores are used to guard resources with limited capacity. If the
81 semaphore is released too many times it's a sign of a bug. If not given,
82 \var{value
} defaults to
1.
85 \begin{classdesc*
}{Thread
}{}
86 A class that represents a thread of control. This class can be safely
87 subclassed in a limited fashion.
90 \begin{classdesc*
}{Timer
}{}
91 A thread that executes a function after a specified interval has passed.
94 Detailed interfaces for the objects are documented below.
96 The design of this module is loosely based on Java's threading model.
97 However, where Java makes locks and condition variables basic behavior
98 of every object, they are separate objects in Python. Python's
\class{Thread
}
99 class supports a subset of the behavior of Java's Thread class;
100 currently, there are no priorities, no thread groups, and threads
101 cannot be destroyed, stopped, suspended, resumed, or interrupted. The
102 static methods of Java's Thread class, when implemented, are mapped to
103 module-level functions.
105 All of the methods described below are executed atomically.
108 \subsection{Lock Objects
\label{lock-objects
}}
110 A primitive lock is a synchronization primitive that is not owned
111 by a particular thread when locked. In Python, it is currently
112 the lowest level synchronization primitive available, implemented
113 directly by the
\refmodule{thread
} extension module.
115 A primitive lock is in one of two states, ``locked'' or ``unlocked''.
116 It is created in the unlocked state. It has two basic methods,
117 \method{acquire()
} and
\method{release()
}. When the state is
118 unlocked,
\method{acquire()
} changes the state to locked and returns
119 immediately. When the state is locked,
\method{acquire()
} blocks
120 until a call to
\method{release()
} in another thread changes it to
121 unlocked, then the
\method{acquire()
} call resets it to locked and
122 returns. The
\method{release()
} method should only be called in the
123 locked state; it changes the state to unlocked and returns
124 immediately. When more than one thread is blocked in
125 \method{acquire()
} waiting for the state to turn to unlocked, only one
126 thread proceeds when a
\method{release()
} call resets the state to
127 unlocked; which one of the waiting threads proceeds is not defined,
128 and may vary across implementations.
130 All methods are executed atomically.
132 \begin{methoddesc
}{acquire
}{\optional{blocking
\code{ =
1}}}
133 Acquire a lock, blocking or non-blocking.
135 When invoked without arguments, block until the lock is
136 unlocked, then set it to locked, and return. There is no
137 return value in this case.
139 When invoked with the
\var{blocking
} argument set to true, do the
140 same thing as when called without arguments, and return true.
142 When invoked with the
\var{blocking
} argument set to false, do not
143 block. If a call without an argument would block, return false
144 immediately; otherwise, do the same thing as when called
145 without arguments, and return true.
148 \begin{methoddesc
}{release
}{}
151 When the lock is locked, reset it to unlocked, and return. If
152 any other threads are blocked waiting for the lock to become
153 unlocked, allow exactly one of them to proceed.
155 Do not call this method when the lock is unlocked.
157 There is no return value.
161 \subsection{RLock Objects
\label{rlock-objects
}}
163 A reentrant lock is a synchronization primitive that may be
164 acquired multiple times by the same thread. Internally, it uses
165 the concepts of ``owning thread'' and ``recursion level'' in
166 addition to the locked/unlocked state used by primitive locks. In
167 the locked state, some thread owns the lock; in the unlocked
168 state, no thread owns it.
170 To lock the lock, a thread calls its
\method{acquire()
} method; this
171 returns once the thread owns the lock. To unlock the lock, a
172 thread calls its
\method{release()
} method.
173 \method{acquire()
}/
\method{release()
} call pairs may be nested; only
174 the final
\method{release()
} (the
\method{release()
} of the outermost
175 pair) resets the lock to unlocked and allows another thread blocked in
176 \method{acquire()
} to proceed.
178 \begin{methoddesc
}{acquire
}{\optional{blocking
\code{ =
1}}}
179 Acquire a lock, blocking or non-blocking.
181 When invoked without arguments: if this thread already owns
182 the lock, increment the recursion level by one, and return
183 immediately. Otherwise, if another thread owns the lock,
184 block until the lock is unlocked. Once the lock is unlocked
185 (not owned by any thread), then grab ownership, set the
186 recursion level to one, and return. If more than one thread
187 is blocked waiting until the lock is unlocked, only one at a
188 time will be able to grab ownership of the lock. There is no
189 return value in this case.
191 When invoked with the
\var{blocking
} argument set to true, do the
192 same thing as when called without arguments, and return true.
194 When invoked with the
\var{blocking
} argument set to false, do not
195 block. If a call without an argument would block, return false
196 immediately; otherwise, do the same thing as when called
197 without arguments, and return true.
200 \begin{methoddesc
}{release
}{}
201 Release a lock, decrementing the recursion level. If after the
202 decrement it is zero, reset the lock to unlocked (not owned by any
203 thread), and if any other threads are blocked waiting for the lock to
204 become unlocked, allow exactly one of them to proceed. If after the
205 decrement the recursion level is still nonzero, the lock remains
206 locked and owned by the calling thread.
208 Only call this method when the calling thread owns the lock.
209 Do not call this method when the lock is unlocked.
211 There is no return value.
215 \subsection{Condition Objects
\label{condition-objects
}}
217 A condition variable is always associated with some kind of lock;
218 this can be passed in or one will be created by default. (Passing
219 one in is useful when several condition variables must share the
222 A condition variable has
\method{acquire()
} and
\method{release()
}
223 methods that call the corresponding methods of the associated lock.
224 It also has a
\method{wait()
} method, and
\method{notify()
} and
225 \method{notifyAll()
} methods. These three must only be called when
226 the calling thread has acquired the lock.
228 The
\method{wait()
} method releases the lock, and then blocks until it
229 is awakened by a
\method{notify()
} or
\method{notifyAll()
} call for
230 the same condition variable in another thread. Once awakened, it
231 re-acquires the lock and returns. It is also possible to specify a
234 The
\method{notify()
} method wakes up one of the threads waiting for
235 the condition variable, if any are waiting. The
\method{notifyAll()
}
236 method wakes up all threads waiting for the condition variable.
238 Note: the
\method{notify()
} and
\method{notifyAll()
} methods don't
239 release the lock; this means that the thread or threads awakened will
240 not return from their
\method{wait()
} call immediately, but only when
241 the thread that called
\method{notify()
} or
\method{notifyAll()
}
242 finally relinquishes ownership of the lock.
244 Tip: the typical programming style using condition variables uses the
245 lock to synchronize access to some shared state; threads that are
246 interested in a particular change of state call
\method{wait()
}
247 repeatedly until they see the desired state, while threads that modify
248 the state call
\method{notify()
} or
\method{notifyAll()
} when they
249 change the state in such a way that it could possibly be a desired
250 state for one of the waiters. For example, the following code is a
251 generic producer-consumer situation with unlimited buffer capacity:
256 while not an_item_is_available():
258 get_an_available_item()
263 make_an_item_available()
268 To choose between
\method{notify()
} and
\method{notifyAll()
}, consider
269 whether one state change can be interesting for only one or several
270 waiting threads. E.g. in a typical producer-consumer situation,
271 adding one item to the buffer only needs to wake up one consumer
274 \begin{classdesc
}{Condition
}{\optional{lock
}}
275 If the
\var{lock
} argument is given and not
\code{None
}, it must be a
276 \class{Lock
} or
\class{RLock
} object, and it is used as the underlying
277 lock. Otherwise, a new
\class{RLock
} object is created and used as
281 \begin{methoddesc
}{acquire
}{*args
}
282 Acquire the underlying lock.
283 This method calls the corresponding method on the underlying
284 lock; the return value is whatever that method returns.
287 \begin{methoddesc
}{release
}{}
288 Release the underlying lock.
289 This method calls the corresponding method on the underlying
290 lock; there is no return value.
293 \begin{methoddesc
}{wait
}{\optional{timeout
}}
294 Wait until notified or until a timeout occurs.
295 This must only be called when the calling thread has acquired the
298 This method releases the underlying lock, and then blocks until it is
299 awakened by a
\method{notify()
} or
\method{notifyAll()
} call for the
300 same condition variable in another thread, or until the optional
301 timeout occurs. Once awakened or timed out, it re-acquires the lock
304 When the
\var{timeout
} argument is present and not
\code{None
}, it
305 should be a floating point number specifying a timeout for the
306 operation in seconds (or fractions thereof).
308 When the underlying lock is an
\class{RLock
}, it is not released using
309 its
\method{release()
} method, since this may not actually unlock the
310 lock when it was acquired multiple times recursively. Instead, an
311 internal interface of the
\class{RLock
} class is used, which really
312 unlocks it even when it has been recursively acquired several times.
313 Another internal interface is then used to restore the recursion level
314 when the lock is reacquired.
317 \begin{methoddesc
}{notify
}{}
318 Wake up a thread waiting on this condition, if any.
319 This must only be called when the calling thread has acquired the
322 This method wakes up one of the threads waiting for the condition
323 variable, if any are waiting; it is a no-op if no threads are waiting.
325 The current implementation wakes up exactly one thread, if any are
326 waiting. However, it's not safe to rely on this behavior. A future,
327 optimized implementation may occasionally wake up more than one
330 Note: the awakened thread does not actually return from its
331 \method{wait()
} call until it can reacquire the lock. Since
332 \method{notify()
} does not release the lock, its caller should.
335 \begin{methoddesc
}{notifyAll
}{}
336 Wake up all threads waiting on this condition. This method acts like
337 \method{notify()
}, but wakes up all waiting threads instead of one.
341 \subsection{Semaphore Objects
\label{semaphore-objects
}}
343 This is one of the oldest synchronization primitives in the history of
344 computer science, invented by the early Dutch computer scientist
345 Edsger W. Dijkstra (he used
\method{P()
} and
\method{V()
} instead of
346 \method{acquire()
} and
\method{release()
}).
348 A semaphore manages an internal counter which is decremented by each
349 \method{acquire()
} call and incremented by each
\method{release()
}
350 call. The counter can never go below zero; when
\method{acquire()
}
351 finds that it is zero, it blocks, waiting until some other thread
352 calls
\method{release()
}.
354 \begin{classdesc
}{Semaphore
}{\optional{value
}}
355 The optional argument gives the initial value for the internal
356 counter; it defaults to
\code{1}.
359 \begin{methoddesc
}{acquire
}{\optional{blocking
}}
362 When invoked without arguments: if the internal counter is larger than
363 zero on entry, decrement it by one and return immediately. If it is
364 zero on entry, block, waiting until some other thread has called
365 \method{release()
} to make it larger than zero. This is done with
366 proper interlocking so that if multiple
\method{acquire()
} calls are
367 blocked,
\method{release()
} will wake exactly one of them up. The
368 implementation may pick one at random, so the order in which blocked
369 threads are awakened should not be relied on. There is no return
372 When invoked with
\var{blocking
} set to true, do the same thing as
373 when called without arguments, and return true.
375 When invoked with
\var{blocking
} set to false, do not block. If a
376 call without an argument would block, return false immediately;
377 otherwise, do the same thing as when called without arguments, and
381 \begin{methoddesc
}{release
}{}
383 incrementing the internal counter by one. When it was zero on
384 entry and another thread is waiting for it to become larger
385 than zero again, wake up that thread.
389 \subsubsection{\class{Semaphore
} Example
\label{semaphore-examples
}}
391 Semaphores are often used to guard resources with limited capacity, for
392 example, a database server. In any situation where the size of the resource
393 size is fixed, you should use a bounded semaphore. Before spawning any
394 worker threads, your main thread would initialize the semaphore:
399 pool_sema = BoundedSemaphore(value=maxconnections)
402 Once spawned, worker threads call the semaphore's acquire and release
403 methods when they need to connect to the server:
408 ... use connection ...
413 The use of a bounded semaphore reduces the chance that a programming error
414 which causes the semaphore to be released more than it's acquired will go
418 \subsection{Event Objects
\label{event-objects
}}
420 This is one of the simplest mechanisms for communication between
421 threads: one thread signals an event and other threads wait for it.
423 An event object manages an internal flag that can be set to true with
424 the
\method{set()
} method and reset to false with the
\method{clear()
}
425 method. The
\method{wait()
} method blocks until the flag is true.
428 \begin{classdesc
}{Event
}{}
429 The internal flag is initially false.
432 \begin{methoddesc
}{isSet
}{}
433 Return true if and only if the internal flag is true.
436 \begin{methoddesc
}{set
}{}
437 Set the internal flag to true.
438 All threads waiting for it to become true are awakened.
439 Threads that call
\method{wait()
} once the flag is true will not block
443 \begin{methoddesc
}{clear
}{}
444 Reset the internal flag to false.
445 Subsequently, threads calling
\method{wait()
} will block until
446 \method{set()
} is called to set the internal flag to true again.
449 \begin{methoddesc
}{wait
}{\optional{timeout
}}
450 Block until the internal flag is true.
451 If the internal flag is true on entry, return immediately. Otherwise,
452 block until another thread calls
\method{set()
} to set the flag to
453 true, or until the optional timeout occurs.
455 When the timeout argument is present and not
\code{None
}, it should be a
456 floating point number specifying a timeout for the operation in
457 seconds (or fractions thereof).
461 \subsection{Thread Objects
\label{thread-objects
}}
463 This class represents an activity that is run in a separate thread
464 of control. There are two ways to specify the activity: by
465 passing a callable object to the constructor, or by overriding the
466 \method{run()
} method in a subclass. No other methods (except for the
467 constructor) should be overridden in a subclass. In other words,
468 \emph{only
} override the
\method{__init__()
} and
\method{run()
}
469 methods of this class.
471 Once a thread object is created, its activity must be started by
472 calling the thread's
\method{start()
} method. This invokes the
473 \method{run()
} method in a separate thread of control.
475 Once the thread's activity is started, the thread is considered
476 'alive' and 'active' (these concepts are almost, but not quite
477 exactly, the same; their definition is intentionally somewhat
478 vague). It stops being alive and active when its
\method{run()
}
479 method terminates -- either normally, or by raising an unhandled
480 exception. The
\method{isAlive()
} method tests whether the thread is
483 Other threads can call a thread's
\method{join()
} method. This blocks
484 the calling thread until the thread whose
\method{join()
} method is
485 called is terminated.
487 A thread has a name. The name can be passed to the constructor,
488 set with the
\method{setName()
} method, and retrieved with the
489 \method{getName()
} method.
491 A thread can be flagged as a ``daemon thread''. The significance
492 of this flag is that the entire Python program exits when only
493 daemon threads are left. The initial value is inherited from the
494 creating thread. The flag can be set with the
\method{setDaemon()
}
495 method and retrieved with the
\method{isDaemon()
} method.
497 There is a ``main thread'' object; this corresponds to the
498 initial thread of control in the Python program. It is not a
501 There is the possibility that ``dummy thread objects'' are
502 created. These are thread objects corresponding to ``alien
503 threads''. These are threads of control started outside the
504 threading module, such as directly from C code. Dummy thread objects
505 have limited functionality; they are always considered alive,
506 active, and daemonic, and cannot be
\method{join()
}ed. They are never
507 deleted, since it is impossible to detect the termination of alien
511 \begin{classdesc
}{Thread
}{group=None, target=None, name=None,
512 args=(), kwargs=\
{\
}}
513 This constructor should always be called with keyword
514 arguments. Arguments are:
516 \var{group
} should be
\code{None
}; reserved for future extension when
517 a
\class{ThreadGroup
} class is implemented.
519 \var{target
} is the callable object to be invoked by the
520 \method{run()
} method. Defaults to
\code{None
}, meaning nothing is
523 \var{name
} is the thread name. By default, a unique name is
524 constructed of the form ``Thread-
\var{N
}'' where
\var{N
} is a small
527 \var{args
} is the argument tuple for the target invocation. Defaults
530 \var{kwargs
} is a dictionary of keyword arguments for the target
531 invocation. Defaults to
\code{\
{\
}}.
533 If the subclass overrides the constructor, it must make sure
534 to invoke the base class constructor (
\code{Thread.__init__()
})
535 before doing anything else to the thread.
538 \begin{methoddesc
}{start
}{}
539 Start the thread's activity.
541 This must be called at most once per thread object. It
542 arranges for the object's
\method{run()
} method to be invoked in a
543 separate thread of control.
546 \begin{methoddesc
}{run
}{}
547 Method representing the thread's activity.
549 You may override this method in a subclass. The standard
550 \method{run()
} method invokes the callable object passed to the
551 object's constructor as the
\var{target
} argument, if any, with
552 sequential and keyword arguments taken from the
\var{args
} and
553 \var{kwargs
} arguments, respectively.
556 \begin{methoddesc
}{join
}{\optional{timeout
}}
557 Wait until the thread terminates.
558 This blocks the calling thread until the thread whose
\method{join()
}
559 method is called terminates -- either normally or through an
560 unhandled exception -- or until the optional timeout occurs.
562 When the
\var{timeout
} argument is present and not
\code{None
}, it
563 should be a floating point number specifying a timeout for the
564 operation in seconds (or fractions thereof).
566 A thread can be
\method{join()
}ed many times.
568 A thread cannot join itself because this would cause a
571 It is an error to attempt to
\method{join()
} a thread before it has
575 \begin{methoddesc
}{getName
}{}
576 Return the thread's name.
579 \begin{methoddesc
}{setName
}{name
}
580 Set the thread's name.
582 The name is a string used for identification purposes only.
583 It has no semantics. Multiple threads may be given the same
584 name. The initial name is set by the constructor.
587 \begin{methoddesc
}{isAlive
}{}
588 Return whether the thread is alive.
590 Roughly, a thread is alive from the moment the
\method{start()
} method
591 returns until its
\method{run()
} method terminates.
594 \begin{methoddesc
}{isDaemon
}{}
595 Return the thread's daemon flag.
598 \begin{methoddesc
}{setDaemon
}{daemonic
}
599 Set the thread's daemon flag to the Boolean value
\var{daemonic
}.
600 This must be called before
\method{start()
} is called.
602 The initial value is inherited from the creating thread.
604 The entire Python program exits when no active non-daemon
609 \subsection{Timer Objects
\label{timer-objects
}}
611 This class represents an action that should be run only after a
612 certain amount of time has passed --- a timer.
\class{Timer
} is a
613 subclass of
\class{Thread
} and as such also functions as an example of
614 creating custom threads.
616 Timers are started, as with threads, by calling their
\method{start()
}
617 method. The timer can be stopped (before its action has begun) by
618 calling the
\method{cancel()
} method. The interval the timer will
619 wait before executing its action may not be exactly the same as the
620 interval specified by the user.
627 t = Timer(
30.0, hello)
628 t.start() # after
30 seconds, "hello, world" will be printed
631 \begin{classdesc
}{Timer
}{interval, function, args=
[], kwargs=\
{\
}}
632 Create a timer that will run
\var{function
} with arguments
\var{args
} and
633 keyword arguments
\var{kwargs
}, after
\var{interval
} seconds have passed.
636 \begin{methoddesc
}{cancel
}{}
637 Stop the timer, and cancel the execution of the timer's action. This
638 will only work if the timer is still in its waiting stage.