| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 |  | 
|  | 2 | :mod:`threading` --- Higher-level threading interface | 
|  | 3 | ===================================================== | 
|  | 4 |  | 
|  | 5 | .. module:: threading | 
|  | 6 | :synopsis: Higher-level threading interface. | 
|  | 7 |  | 
|  | 8 |  | 
|  | 9 | This module constructs higher-level threading interfaces on top of the  lower | 
|  | 10 | level :mod:`thread` module. | 
| Georg Brandl | a6168f9 | 2008-05-25 07:20:14 +0000 | [diff] [blame] | 11 | See also the :mod:`mutex` and :mod:`Queue` modules. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 12 |  | 
|  | 13 | The :mod:`dummy_threading` module is provided for situations where | 
|  | 14 | :mod:`threading` cannot be used because :mod:`thread` is missing. | 
|  | 15 |  | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 16 | .. note:: | 
|  | 17 |  | 
|  | 18 | In 3.x, names in camelCase have been renamed to their underscored | 
|  | 19 | equivelents.  Both names are availble in 2.6. | 
|  | 20 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 21 | This module defines the following functions and objects: | 
|  | 22 |  | 
|  | 23 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 24 | .. function:: active_count() | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 25 | activeCount() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 26 |  | 
|  | 27 | Return the number of :class:`Thread` objects currently alive.  The returned | 
|  | 28 | count is equal to the length of the list returned by :func:`enumerate`. | 
|  | 29 |  | 
|  | 30 |  | 
|  | 31 | .. function:: Condition() | 
|  | 32 | :noindex: | 
|  | 33 |  | 
|  | 34 | A factory function that returns a new condition variable object. A condition | 
|  | 35 | variable allows one or more threads to wait until they are notified by another | 
|  | 36 | thread. | 
|  | 37 |  | 
|  | 38 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 39 | .. function:: current_thread() | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 40 | currentThread() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 41 |  | 
|  | 42 | Return the current :class:`Thread` object, corresponding to the caller's thread | 
|  | 43 | of control.  If the caller's thread of control was not created through the | 
|  | 44 | :mod:`threading` module, a dummy thread object with limited functionality is | 
|  | 45 | returned. | 
|  | 46 |  | 
|  | 47 |  | 
|  | 48 | .. function:: enumerate() | 
|  | 49 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 50 | Return a list of all :class:`Thread` objects currently alive.  The list | 
|  | 51 | includes daemonic threads, dummy thread objects created by | 
|  | 52 | :func:`current_thread`, and the main thread.  It excludes terminated threads | 
|  | 53 | and threads that have not yet been started. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 54 |  | 
|  | 55 |  | 
|  | 56 | .. function:: Event() | 
|  | 57 | :noindex: | 
|  | 58 |  | 
|  | 59 | A factory function that returns a new event object.  An event manages a flag | 
|  | 60 | that can be set to true with the :meth:`set` method and reset to false with the | 
|  | 61 | :meth:`clear` method.  The :meth:`wait` method blocks until the flag is true. | 
|  | 62 |  | 
|  | 63 |  | 
|  | 64 | .. class:: local | 
|  | 65 |  | 
|  | 66 | A class that represents thread-local data.  Thread-local data are data whose | 
|  | 67 | values are thread specific.  To manage thread-local data, just create an | 
|  | 68 | instance of :class:`local` (or a subclass) and store attributes on it:: | 
|  | 69 |  | 
|  | 70 | mydata = threading.local() | 
|  | 71 | mydata.x = 1 | 
|  | 72 |  | 
|  | 73 | The instance's values will be different for separate threads. | 
|  | 74 |  | 
|  | 75 | For more details and extensive examples, see the documentation string of the | 
|  | 76 | :mod:`_threading_local` module. | 
|  | 77 |  | 
|  | 78 | .. versionadded:: 2.4 | 
|  | 79 |  | 
|  | 80 |  | 
|  | 81 | .. function:: Lock() | 
|  | 82 |  | 
|  | 83 | A factory function that returns a new primitive lock object.  Once a thread has | 
|  | 84 | acquired it, subsequent attempts to acquire it block, until it is released; any | 
|  | 85 | thread may release it. | 
|  | 86 |  | 
|  | 87 |  | 
|  | 88 | .. function:: RLock() | 
|  | 89 |  | 
|  | 90 | A factory function that returns a new reentrant lock object. A reentrant lock | 
|  | 91 | must be released by the thread that acquired it. Once a thread has acquired a | 
|  | 92 | reentrant lock, the same thread may acquire it again without blocking; the | 
|  | 93 | thread must release it once for each time it has acquired it. | 
|  | 94 |  | 
|  | 95 |  | 
|  | 96 | .. function:: Semaphore([value]) | 
|  | 97 | :noindex: | 
|  | 98 |  | 
|  | 99 | A factory function that returns a new semaphore object.  A semaphore manages a | 
|  | 100 | counter representing the number of :meth:`release` calls minus the number of | 
|  | 101 | :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks | 
|  | 102 | if necessary until it can return without making the counter negative.  If not | 
|  | 103 | given, *value* defaults to 1. | 
|  | 104 |  | 
|  | 105 |  | 
|  | 106 | .. function:: BoundedSemaphore([value]) | 
|  | 107 |  | 
|  | 108 | A factory function that returns a new bounded semaphore object.  A bounded | 
|  | 109 | semaphore checks to make sure its current value doesn't exceed its initial | 
|  | 110 | value.  If it does, :exc:`ValueError` is raised. In most situations semaphores | 
|  | 111 | are used to guard resources with limited capacity.  If the semaphore is released | 
|  | 112 | too many times it's a sign of a bug.  If not given, *value* defaults to 1. | 
|  | 113 |  | 
|  | 114 |  | 
|  | 115 | .. class:: Thread | 
|  | 116 |  | 
|  | 117 | A class that represents a thread of control.  This class can be safely | 
|  | 118 | subclassed in a limited fashion. | 
|  | 119 |  | 
|  | 120 |  | 
|  | 121 | .. class:: Timer | 
|  | 122 |  | 
|  | 123 | A thread that executes a function after a specified interval has passed. | 
|  | 124 |  | 
|  | 125 |  | 
|  | 126 | .. function:: settrace(func) | 
|  | 127 |  | 
|  | 128 | .. index:: single: trace function | 
|  | 129 |  | 
|  | 130 | Set a trace function for all threads started from the :mod:`threading` module. | 
|  | 131 | The *func* will be passed to  :func:`sys.settrace` for each thread, before its | 
|  | 132 | :meth:`run` method is called. | 
|  | 133 |  | 
|  | 134 | .. versionadded:: 2.3 | 
|  | 135 |  | 
|  | 136 |  | 
|  | 137 | .. function:: setprofile(func) | 
|  | 138 |  | 
|  | 139 | .. index:: single: profile function | 
|  | 140 |  | 
|  | 141 | Set a profile function for all threads started from the :mod:`threading` module. | 
|  | 142 | The *func* will be passed to  :func:`sys.setprofile` for each thread, before its | 
|  | 143 | :meth:`run` method is called. | 
|  | 144 |  | 
|  | 145 | .. versionadded:: 2.3 | 
|  | 146 |  | 
|  | 147 |  | 
|  | 148 | .. function:: stack_size([size]) | 
|  | 149 |  | 
|  | 150 | Return the thread stack size used when creating new threads.  The optional | 
|  | 151 | *size* argument specifies the stack size to be used for subsequently created | 
|  | 152 | threads, and must be 0 (use platform or configured default) or a positive | 
|  | 153 | integer value of at least 32,768 (32kB). If changing the thread stack size is | 
|  | 154 | unsupported, a :exc:`ThreadError` is raised.  If the specified stack size is | 
|  | 155 | invalid, a :exc:`ValueError` is raised and the stack size is unmodified.  32kB | 
|  | 156 | is currently the minimum supported stack size value to guarantee sufficient | 
|  | 157 | stack space for the interpreter itself.  Note that some platforms may have | 
|  | 158 | particular restrictions on values for the stack size, such as requiring a | 
|  | 159 | minimum stack size > 32kB or requiring allocation in multiples of the system | 
|  | 160 | memory page size - platform documentation should be referred to for more | 
|  | 161 | information (4kB pages are common; using multiples of 4096 for the stack size is | 
|  | 162 | the suggested approach in the absence of more specific information). | 
|  | 163 | Availability: Windows, systems with POSIX threads. | 
|  | 164 |  | 
|  | 165 | .. versionadded:: 2.5 | 
|  | 166 |  | 
|  | 167 | Detailed interfaces for the objects are documented below. | 
|  | 168 |  | 
|  | 169 | The design of this module is loosely based on Java's threading model. However, | 
|  | 170 | where Java makes locks and condition variables basic behavior of every object, | 
|  | 171 | they are separate objects in Python.  Python's :class:`Thread` class supports a | 
|  | 172 | subset of the behavior of Java's Thread class; currently, there are no | 
|  | 173 | priorities, no thread groups, and threads cannot be destroyed, stopped, | 
|  | 174 | suspended, resumed, or interrupted.  The static methods of Java's Thread class, | 
|  | 175 | when implemented, are mapped to module-level functions. | 
|  | 176 |  | 
|  | 177 | All of the methods described below are executed atomically. | 
|  | 178 |  | 
|  | 179 |  | 
|  | 180 | .. _lock-objects: | 
|  | 181 |  | 
|  | 182 | Lock Objects | 
|  | 183 | ------------ | 
|  | 184 |  | 
|  | 185 | A primitive lock is a synchronization primitive that is not owned by a | 
|  | 186 | particular thread when locked.  In Python, it is currently the lowest level | 
|  | 187 | synchronization primitive available, implemented directly by the :mod:`thread` | 
|  | 188 | extension module. | 
|  | 189 |  | 
|  | 190 | A primitive lock is in one of two states, "locked" or "unlocked". It is created | 
|  | 191 | in the unlocked state.  It has two basic methods, :meth:`acquire` and | 
|  | 192 | :meth:`release`.  When the state is unlocked, :meth:`acquire` changes the state | 
|  | 193 | to locked and returns immediately.  When the state is locked, :meth:`acquire` | 
|  | 194 | blocks until a call to :meth:`release` in another thread changes it to unlocked, | 
|  | 195 | then the :meth:`acquire` call resets it to locked and returns.  The | 
|  | 196 | :meth:`release` method should only be called in the locked state; it changes the | 
|  | 197 | state to unlocked and returns immediately. If an attempt is made to release an | 
|  | 198 | unlocked lock, a :exc:`RuntimeError` will be raised. | 
|  | 199 |  | 
|  | 200 | When more than one thread is blocked in :meth:`acquire` waiting for the state to | 
|  | 201 | turn to unlocked, only one thread proceeds when a :meth:`release` call resets | 
|  | 202 | the state to unlocked; which one of the waiting threads proceeds is not defined, | 
|  | 203 | and may vary across implementations. | 
|  | 204 |  | 
|  | 205 | All methods are executed atomically. | 
|  | 206 |  | 
|  | 207 |  | 
|  | 208 | .. method:: Lock.acquire([blocking=1]) | 
|  | 209 |  | 
|  | 210 | Acquire a lock, blocking or non-blocking. | 
|  | 211 |  | 
|  | 212 | When invoked without arguments, block until the lock is unlocked, then set it to | 
|  | 213 | locked, and return true. | 
|  | 214 |  | 
|  | 215 | When invoked with the *blocking* argument set to true, do the same thing as when | 
|  | 216 | called without arguments, and return true. | 
|  | 217 |  | 
|  | 218 | When invoked with the *blocking* argument set to false, do not block.  If a call | 
|  | 219 | without an argument would block, return false immediately; otherwise, do the | 
|  | 220 | same thing as when called without arguments, and return true. | 
|  | 221 |  | 
|  | 222 |  | 
|  | 223 | .. method:: Lock.release() | 
|  | 224 |  | 
|  | 225 | Release a lock. | 
|  | 226 |  | 
|  | 227 | When the lock is locked, reset it to unlocked, and return.  If any other threads | 
|  | 228 | are blocked waiting for the lock to become unlocked, allow exactly one of them | 
|  | 229 | to proceed. | 
|  | 230 |  | 
|  | 231 | Do not call this method when the lock is unlocked. | 
|  | 232 |  | 
|  | 233 | There is no return value. | 
|  | 234 |  | 
|  | 235 |  | 
|  | 236 | .. _rlock-objects: | 
|  | 237 |  | 
|  | 238 | RLock Objects | 
|  | 239 | ------------- | 
|  | 240 |  | 
|  | 241 | A reentrant lock is a synchronization primitive that may be acquired multiple | 
|  | 242 | times by the same thread.  Internally, it uses the concepts of "owning thread" | 
|  | 243 | and "recursion level" in addition to the locked/unlocked state used by primitive | 
|  | 244 | locks.  In the locked state, some thread owns the lock; in the unlocked state, | 
|  | 245 | no thread owns it. | 
|  | 246 |  | 
|  | 247 | To lock the lock, a thread calls its :meth:`acquire` method; this returns once | 
|  | 248 | the thread owns the lock.  To unlock the lock, a thread calls its | 
|  | 249 | :meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be | 
|  | 250 | nested; only the final :meth:`release` (the :meth:`release` of the outermost | 
|  | 251 | pair) resets the lock to unlocked and allows another thread blocked in | 
|  | 252 | :meth:`acquire` to proceed. | 
|  | 253 |  | 
|  | 254 |  | 
|  | 255 | .. method:: RLock.acquire([blocking=1]) | 
|  | 256 |  | 
|  | 257 | Acquire a lock, blocking or non-blocking. | 
|  | 258 |  | 
|  | 259 | When invoked without arguments: if this thread already owns the lock, increment | 
|  | 260 | the recursion level by one, and return immediately.  Otherwise, if another | 
|  | 261 | thread owns the lock, block until the lock is unlocked.  Once the lock is | 
|  | 262 | unlocked (not owned by any thread), then grab ownership, set the recursion level | 
|  | 263 | to one, and return.  If more than one thread is blocked waiting until the lock | 
|  | 264 | is unlocked, only one at a time will be able to grab ownership of the lock. | 
|  | 265 | There is no return value in this case. | 
|  | 266 |  | 
|  | 267 | When invoked with the *blocking* argument set to true, do the same thing as when | 
|  | 268 | called without arguments, and return true. | 
|  | 269 |  | 
|  | 270 | When invoked with the *blocking* argument set to false, do not block.  If a call | 
|  | 271 | without an argument would block, return false immediately; otherwise, do the | 
|  | 272 | same thing as when called without arguments, and return true. | 
|  | 273 |  | 
|  | 274 |  | 
|  | 275 | .. method:: RLock.release() | 
|  | 276 |  | 
|  | 277 | Release a lock, decrementing the recursion level.  If after the decrement it is | 
|  | 278 | zero, reset the lock to unlocked (not owned by any thread), and if any other | 
|  | 279 | threads are blocked waiting for the lock to become unlocked, allow exactly one | 
|  | 280 | of them to proceed.  If after the decrement the recursion level is still | 
|  | 281 | nonzero, the lock remains locked and owned by the calling thread. | 
|  | 282 |  | 
|  | 283 | Only call this method when the calling thread owns the lock. A | 
|  | 284 | :exc:`RuntimeError` is raised if this method is called when the lock is | 
|  | 285 | unlocked. | 
|  | 286 |  | 
|  | 287 | There is no return value. | 
|  | 288 |  | 
|  | 289 |  | 
|  | 290 | .. _condition-objects: | 
|  | 291 |  | 
|  | 292 | Condition Objects | 
|  | 293 | ----------------- | 
|  | 294 |  | 
|  | 295 | A condition variable is always associated with some kind of lock; this can be | 
|  | 296 | passed in or one will be created by default.  (Passing one in is useful when | 
|  | 297 | several condition variables must share the same lock.) | 
|  | 298 |  | 
|  | 299 | A condition variable has :meth:`acquire` and :meth:`release` methods that call | 
|  | 300 | the corresponding methods of the associated lock. It also has a :meth:`wait` | 
|  | 301 | method, and :meth:`notify` and :meth:`notifyAll` methods.  These three must only | 
|  | 302 | be called when the calling thread has acquired the lock, otherwise a | 
|  | 303 | :exc:`RuntimeError` is raised. | 
|  | 304 |  | 
|  | 305 | The :meth:`wait` method releases the lock, and then blocks until it is awakened | 
|  | 306 | by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in | 
|  | 307 | another thread.  Once awakened, it re-acquires the lock and returns.  It is also | 
|  | 308 | possible to specify a timeout. | 
|  | 309 |  | 
|  | 310 | The :meth:`notify` method wakes up one of the threads waiting for the condition | 
|  | 311 | variable, if any are waiting.  The :meth:`notifyAll` method wakes up all threads | 
|  | 312 | waiting for the condition variable. | 
|  | 313 |  | 
|  | 314 | Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock; | 
|  | 315 | this means that the thread or threads awakened will not return from their | 
|  | 316 | :meth:`wait` call immediately, but only when the thread that called | 
|  | 317 | :meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock. | 
|  | 318 |  | 
|  | 319 | Tip: the typical programming style using condition variables uses the lock to | 
|  | 320 | synchronize access to some shared state; threads that are interested in a | 
|  | 321 | particular change of state call :meth:`wait` repeatedly until they see the | 
|  | 322 | desired state, while threads that modify the state call :meth:`notify` or | 
|  | 323 | :meth:`notifyAll` when they change the state in such a way that it could | 
|  | 324 | possibly be a desired state for one of the waiters.  For example, the following | 
|  | 325 | code is a generic producer-consumer situation with unlimited buffer capacity:: | 
|  | 326 |  | 
|  | 327 | # Consume one item | 
|  | 328 | cv.acquire() | 
|  | 329 | while not an_item_is_available(): | 
|  | 330 | cv.wait() | 
|  | 331 | get_an_available_item() | 
|  | 332 | cv.release() | 
|  | 333 |  | 
|  | 334 | # Produce one item | 
|  | 335 | cv.acquire() | 
|  | 336 | make_an_item_available() | 
|  | 337 | cv.notify() | 
|  | 338 | cv.release() | 
|  | 339 |  | 
|  | 340 | To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one | 
|  | 341 | state change can be interesting for only one or several waiting threads.  E.g. | 
|  | 342 | in a typical producer-consumer situation, adding one item to the buffer only | 
|  | 343 | needs to wake up one consumer thread. | 
|  | 344 |  | 
|  | 345 |  | 
|  | 346 | .. class:: Condition([lock]) | 
|  | 347 |  | 
|  | 348 | If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or | 
|  | 349 | :class:`RLock` object, and it is used as the underlying lock.  Otherwise, a new | 
|  | 350 | :class:`RLock` object is created and used as the underlying lock. | 
|  | 351 |  | 
|  | 352 |  | 
|  | 353 | .. method:: Condition.acquire(*args) | 
|  | 354 |  | 
|  | 355 | Acquire the underlying lock. This method calls the corresponding method on the | 
|  | 356 | underlying lock; the return value is whatever that method returns. | 
|  | 357 |  | 
|  | 358 |  | 
|  | 359 | .. method:: Condition.release() | 
|  | 360 |  | 
|  | 361 | Release the underlying lock. This method calls the corresponding method on the | 
|  | 362 | underlying lock; there is no return value. | 
|  | 363 |  | 
|  | 364 |  | 
|  | 365 | .. method:: Condition.wait([timeout]) | 
|  | 366 |  | 
|  | 367 | Wait until notified or until a timeout occurs. If the calling thread has not | 
|  | 368 | acquired the lock when this method is called, a :exc:`RuntimeError` is raised. | 
|  | 369 |  | 
|  | 370 | This method releases the underlying lock, and then blocks until it is awakened | 
|  | 371 | by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in | 
|  | 372 | another thread, or until the optional timeout occurs.  Once awakened or timed | 
|  | 373 | out, it re-acquires the lock and returns. | 
|  | 374 |  | 
|  | 375 | When the *timeout* argument is present and not ``None``, it should be a floating | 
|  | 376 | point number specifying a timeout for the operation in seconds (or fractions | 
|  | 377 | thereof). | 
|  | 378 |  | 
|  | 379 | When the underlying lock is an :class:`RLock`, it is not released using its | 
|  | 380 | :meth:`release` method, since this may not actually unlock the lock when it was | 
|  | 381 | acquired multiple times recursively.  Instead, an internal interface of the | 
|  | 382 | :class:`RLock` class is used, which really unlocks it even when it has been | 
|  | 383 | recursively acquired several times. Another internal interface is then used to | 
|  | 384 | restore the recursion level when the lock is reacquired. | 
|  | 385 |  | 
|  | 386 |  | 
|  | 387 | .. method:: Condition.notify() | 
|  | 388 |  | 
|  | 389 | Wake up a thread waiting on this condition, if any. Wait until notified or until | 
|  | 390 | a timeout occurs. If the calling thread has not acquired the lock when this | 
|  | 391 | method is called, a :exc:`RuntimeError` is raised. | 
|  | 392 |  | 
|  | 393 | This method wakes up one of the threads waiting for the condition variable, if | 
|  | 394 | any are waiting; it is a no-op if no threads are waiting. | 
|  | 395 |  | 
|  | 396 | The current implementation wakes up exactly one thread, if any are waiting. | 
|  | 397 | However, it's not safe to rely on this behavior.  A future, optimized | 
|  | 398 | implementation may occasionally wake up more than one thread. | 
|  | 399 |  | 
|  | 400 | Note: the awakened thread does not actually return from its :meth:`wait` call | 
|  | 401 | until it can reacquire the lock.  Since :meth:`notify` does not release the | 
|  | 402 | lock, its caller should. | 
|  | 403 |  | 
|  | 404 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 405 | .. method:: Condition.notify_all() | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 406 | Condition.notifyAll() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 407 |  | 
|  | 408 | Wake up all threads waiting on this condition.  This method acts like | 
|  | 409 | :meth:`notify`, but wakes up all waiting threads instead of one. If the calling | 
|  | 410 | thread has not acquired the lock when this method is called, a | 
|  | 411 | :exc:`RuntimeError` is raised. | 
|  | 412 |  | 
|  | 413 |  | 
|  | 414 | .. _semaphore-objects: | 
|  | 415 |  | 
|  | 416 | Semaphore Objects | 
|  | 417 | ----------------- | 
|  | 418 |  | 
|  | 419 | This is one of the oldest synchronization primitives in the history of computer | 
|  | 420 | science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he | 
|  | 421 | used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`). | 
|  | 422 |  | 
|  | 423 | A semaphore manages an internal counter which is decremented by each | 
|  | 424 | :meth:`acquire` call and incremented by each :meth:`release` call.  The counter | 
|  | 425 | can never go below zero; when :meth:`acquire` finds that it is zero, it blocks, | 
|  | 426 | waiting until some other thread calls :meth:`release`. | 
|  | 427 |  | 
|  | 428 |  | 
|  | 429 | .. class:: Semaphore([value]) | 
|  | 430 |  | 
|  | 431 | The optional argument gives the initial *value* for the internal counter; it | 
|  | 432 | defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is | 
|  | 433 | raised. | 
|  | 434 |  | 
|  | 435 |  | 
|  | 436 | .. method:: Semaphore.acquire([blocking]) | 
|  | 437 |  | 
|  | 438 | Acquire a semaphore. | 
|  | 439 |  | 
|  | 440 | When invoked without arguments: if the internal counter is larger than zero on | 
|  | 441 | entry, decrement it by one and return immediately.  If it is zero on entry, | 
|  | 442 | block, waiting until some other thread has called :meth:`release` to make it | 
|  | 443 | larger than zero.  This is done with proper interlocking so that if multiple | 
|  | 444 | :meth:`acquire` calls are blocked, :meth:`release` will wake exactly one of them | 
|  | 445 | up.  The implementation may pick one at random, so the order in which blocked | 
|  | 446 | threads are awakened should not be relied on.  There is no return value in this | 
|  | 447 | case. | 
|  | 448 |  | 
|  | 449 | When invoked with *blocking* set to true, do the same thing as when called | 
|  | 450 | without arguments, and return true. | 
|  | 451 |  | 
|  | 452 | When invoked with *blocking* set to false, do not block.  If a call without an | 
|  | 453 | argument would block, return false immediately; otherwise, do the same thing as | 
|  | 454 | when called without arguments, and return true. | 
|  | 455 |  | 
|  | 456 |  | 
|  | 457 | .. method:: Semaphore.release() | 
|  | 458 |  | 
|  | 459 | Release a semaphore, incrementing the internal counter by one.  When it was zero | 
|  | 460 | on entry and another thread is waiting for it to become larger than zero again, | 
|  | 461 | wake up that thread. | 
|  | 462 |  | 
|  | 463 |  | 
|  | 464 | .. _semaphore-examples: | 
|  | 465 |  | 
|  | 466 | :class:`Semaphore` Example | 
|  | 467 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 468 |  | 
|  | 469 | Semaphores are often used to guard resources with limited capacity, for example, | 
|  | 470 | a database server.  In any situation where the size of the resource size is | 
|  | 471 | fixed, you should use a bounded semaphore.  Before spawning any worker threads, | 
|  | 472 | your main thread would initialize the semaphore:: | 
|  | 473 |  | 
|  | 474 | maxconnections = 5 | 
|  | 475 | ... | 
|  | 476 | pool_sema = BoundedSemaphore(value=maxconnections) | 
|  | 477 |  | 
|  | 478 | Once spawned, worker threads call the semaphore's acquire and release methods | 
|  | 479 | when they need to connect to the server:: | 
|  | 480 |  | 
|  | 481 | pool_sema.acquire() | 
|  | 482 | conn = connectdb() | 
|  | 483 | ... use connection ... | 
|  | 484 | conn.close() | 
|  | 485 | pool_sema.release() | 
|  | 486 |  | 
|  | 487 | The use of a bounded semaphore reduces the chance that a programming error which | 
|  | 488 | causes the semaphore to be released more than it's acquired will go undetected. | 
|  | 489 |  | 
|  | 490 |  | 
|  | 491 | .. _event-objects: | 
|  | 492 |  | 
|  | 493 | Event Objects | 
|  | 494 | ------------- | 
|  | 495 |  | 
|  | 496 | This is one of the simplest mechanisms for communication between threads: one | 
|  | 497 | thread signals an event and other threads wait for it. | 
|  | 498 |  | 
|  | 499 | An event object manages an internal flag that can be set to true with the | 
|  | 500 | :meth:`set` method and reset to false with the :meth:`clear` method.  The | 
|  | 501 | :meth:`wait` method blocks until the flag is true. | 
|  | 502 |  | 
|  | 503 |  | 
|  | 504 | .. class:: Event() | 
|  | 505 |  | 
|  | 506 | The internal flag is initially false. | 
|  | 507 |  | 
|  | 508 |  | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 509 | .. method:: Event.is_set() | 
|  | 510 | Event.isSet() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 511 |  | 
|  | 512 | Return true if and only if the internal flag is true. | 
|  | 513 |  | 
|  | 514 |  | 
|  | 515 | .. method:: Event.set() | 
|  | 516 |  | 
|  | 517 | Set the internal flag to true. All threads waiting for it to become true are | 
|  | 518 | awakened. Threads that call :meth:`wait` once the flag is true will not block at | 
|  | 519 | all. | 
|  | 520 |  | 
|  | 521 |  | 
|  | 522 | .. method:: Event.clear() | 
|  | 523 |  | 
|  | 524 | Reset the internal flag to false. Subsequently, threads calling :meth:`wait` | 
|  | 525 | will block until :meth:`set` is called to set the internal flag to true again. | 
|  | 526 |  | 
|  | 527 |  | 
|  | 528 | .. method:: Event.wait([timeout]) | 
|  | 529 |  | 
|  | 530 | Block until the internal flag is true. If the internal flag is true on entry, | 
|  | 531 | return immediately.  Otherwise, block until another thread calls :meth:`set` to | 
|  | 532 | set the flag to true, or until the optional timeout occurs. | 
|  | 533 |  | 
|  | 534 | When the timeout argument is present and not ``None``, it should be a floating | 
|  | 535 | point number specifying a timeout for the operation in seconds (or fractions | 
|  | 536 | thereof). | 
|  | 537 |  | 
|  | 538 |  | 
|  | 539 | .. _thread-objects: | 
|  | 540 |  | 
|  | 541 | Thread Objects | 
|  | 542 | -------------- | 
|  | 543 |  | 
|  | 544 | This class represents an activity that is run in a separate thread of control. | 
|  | 545 | There are two ways to specify the activity: by passing a callable object to the | 
|  | 546 | constructor, or by overriding the :meth:`run` method in a subclass.  No other | 
|  | 547 | methods (except for the constructor) should be overridden in a subclass.  In | 
|  | 548 | other words,  *only*  override the :meth:`__init__` and :meth:`run` methods of | 
|  | 549 | this class. | 
|  | 550 |  | 
|  | 551 | Once a thread object is created, its activity must be started by calling the | 
|  | 552 | thread's :meth:`start` method.  This invokes the :meth:`run` method in a | 
|  | 553 | separate thread of control. | 
|  | 554 |  | 
|  | 555 | Once the thread's activity is started, the thread is considered 'alive'. It | 
|  | 556 | stops being alive when its :meth:`run` method terminates -- either normally, or | 
|  | 557 | by raising an unhandled exception.  The :meth:`isAlive` method tests whether the | 
|  | 558 | thread is alive. | 
|  | 559 |  | 
|  | 560 | Other threads can call a thread's :meth:`join` method.  This blocks the calling | 
|  | 561 | thread until the thread whose :meth:`join` method is called is terminated. | 
|  | 562 |  | 
|  | 563 | A thread has a name.  The name can be passed to the constructor, set with the | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 564 | :meth:`set_name` method, and retrieved with the :meth:`get_name` method. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 565 |  | 
|  | 566 | A thread can be flagged as a "daemon thread".  The significance of this flag is | 
|  | 567 | that the entire Python program exits when only daemon threads are left.  The | 
|  | 568 | initial value is inherited from the creating thread.  The flag can be set with | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 569 | the :meth:`set_daemon` method and retrieved with the :meth:`is_daemon` method. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 570 |  | 
|  | 571 | There is a "main thread" object; this corresponds to the initial thread of | 
|  | 572 | control in the Python program.  It is not a daemon thread. | 
|  | 573 |  | 
|  | 574 | There is the possibility that "dummy thread objects" are created. These are | 
|  | 575 | thread objects corresponding to "alien threads", which are threads of control | 
|  | 576 | started outside the threading module, such as directly from C code.  Dummy | 
|  | 577 | thread objects have limited functionality; they are always considered alive and | 
|  | 578 | daemonic, and cannot be :meth:`join`\ ed.  They are never deleted, since it is | 
|  | 579 | impossible to detect the termination of alien threads. | 
|  | 580 |  | 
|  | 581 |  | 
|  | 582 | .. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}) | 
|  | 583 |  | 
|  | 584 | This constructor should always be called with keyword arguments.  Arguments are: | 
|  | 585 |  | 
|  | 586 | *group* should be ``None``; reserved for future extension when a | 
|  | 587 | :class:`ThreadGroup` class is implemented. | 
|  | 588 |  | 
|  | 589 | *target* is the callable object to be invoked by the :meth:`run` method. | 
|  | 590 | Defaults to ``None``, meaning nothing is called. | 
|  | 591 |  | 
|  | 592 | *name* is the thread name.  By default, a unique name is constructed of the form | 
|  | 593 | "Thread-*N*" where *N* is a small decimal number. | 
|  | 594 |  | 
|  | 595 | *args* is the argument tuple for the target invocation.  Defaults to ``()``. | 
|  | 596 |  | 
|  | 597 | *kwargs* is a dictionary of keyword arguments for the target invocation. | 
|  | 598 | Defaults to ``{}``. | 
|  | 599 |  | 
|  | 600 | If the subclass overrides the constructor, it must make sure to invoke the base | 
|  | 601 | class constructor (``Thread.__init__()``) before doing anything else to the | 
|  | 602 | thread. | 
|  | 603 |  | 
|  | 604 |  | 
|  | 605 | .. method:: Thread.start() | 
|  | 606 |  | 
|  | 607 | Start the thread's activity. | 
|  | 608 |  | 
|  | 609 | It must be called at most once per thread object.  It arranges for the object's | 
|  | 610 | :meth:`run` method to be invoked in a separate thread of control. | 
|  | 611 |  | 
|  | 612 | This method will raise a :exc:`RuntimeException` if called more than once on the | 
|  | 613 | same thread object. | 
|  | 614 |  | 
|  | 615 |  | 
|  | 616 | .. method:: Thread.run() | 
|  | 617 |  | 
|  | 618 | Method representing the thread's activity. | 
|  | 619 |  | 
|  | 620 | You may override this method in a subclass.  The standard :meth:`run` method | 
|  | 621 | invokes the callable object passed to the object's constructor as the *target* | 
|  | 622 | argument, if any, with sequential and keyword arguments taken from the *args* | 
|  | 623 | and *kwargs* arguments, respectively. | 
|  | 624 |  | 
|  | 625 |  | 
|  | 626 | .. method:: Thread.join([timeout]) | 
|  | 627 |  | 
|  | 628 | Wait until the thread terminates. This blocks the calling thread until the | 
|  | 629 | thread whose :meth:`join` method is called terminates -- either normally or | 
|  | 630 | through an unhandled exception -- or until the optional timeout occurs. | 
|  | 631 |  | 
|  | 632 | When the *timeout* argument is present and not ``None``, it should be a floating | 
|  | 633 | point number specifying a timeout for the operation in seconds (or fractions | 
| Georg Brandl | 6ebc527 | 2008-01-19 17:38:53 +0000 | [diff] [blame] | 634 | thereof). As :meth:`join` always returns ``None``, you must call :meth:`isAlive` | 
|  | 635 | after :meth:`join` to decide whether a timeout happened -- if the thread is | 
|  | 636 | still alive, the :meth:`join` call timed out. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 637 |  | 
|  | 638 | When the *timeout* argument is not present or ``None``, the operation will block | 
|  | 639 | until the thread terminates. | 
|  | 640 |  | 
|  | 641 | A thread can be :meth:`join`\ ed many times. | 
|  | 642 |  | 
| Georg Brandl | 6ebc527 | 2008-01-19 17:38:53 +0000 | [diff] [blame] | 643 | :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join | 
|  | 644 | the current thread as that would cause a deadlock. It is also an error to | 
|  | 645 | :meth:`join` a thread before it has been started and attempts to do so | 
|  | 646 | raises the same exception. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 647 |  | 
|  | 648 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 649 | .. method:: Thread.get_name() | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 650 | Thread.getName() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 651 |  | 
|  | 652 | Return the thread's name. | 
|  | 653 |  | 
|  | 654 |  | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 655 | .. method:: Thread.set_name(name) | 
|  | 656 | Thread.setName(name) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 657 |  | 
|  | 658 | Set the thread's name. | 
|  | 659 |  | 
|  | 660 | The name is a string used for identification purposes only. It has no semantics. | 
|  | 661 | Multiple threads may be given the same name.  The initial name is set by the | 
|  | 662 | constructor. | 
|  | 663 |  | 
|  | 664 |  | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 665 | .. method:: Thread.get_ident() | 
| Gregory P. Smith | 8856dda | 2008-06-01 23:48:47 +0000 | [diff] [blame] | 666 |  | 
|  | 667 | Return the 'thread identifier' of this thread or None if the thread has not | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 668 | been started.  This is a nonzero integer.  See the :func:`thread.get_ident()` | 
|  | 669 | function.  Thread identifiers may be recycled when a thread exits and another | 
|  | 670 | thread is created.  The identifier is returned even after the thread has | 
|  | 671 | exited. | 
| Gregory P. Smith | 8856dda | 2008-06-01 23:48:47 +0000 | [diff] [blame] | 672 |  | 
|  | 673 | .. versionadded:: 2.6 | 
|  | 674 |  | 
|  | 675 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 676 | .. method:: Thread.is_alive() | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 677 | Thread.isAlive() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 678 |  | 
|  | 679 | Return whether the thread is alive. | 
|  | 680 |  | 
|  | 681 | Roughly, a thread is alive from the moment the :meth:`start` method returns | 
|  | 682 | until its :meth:`run` method terminates. The module function :func:`enumerate` | 
|  | 683 | returns a list of all alive threads. | 
|  | 684 |  | 
|  | 685 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 686 | .. method:: Thread.is_daemon() | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 687 | Thread.isDaemon() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 688 |  | 
|  | 689 | Return the thread's daemon flag. | 
|  | 690 |  | 
|  | 691 |  | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 692 | .. method:: Thread.set_daemon(daemonic) | 
| Benjamin Peterson | f439560 | 2008-06-11 17:50:00 +0000 | [diff] [blame^] | 693 | Thread.setDaemon(daemonic) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 694 |  | 
|  | 695 | Set the thread's daemon flag to the Boolean value *daemonic*. This must be | 
|  | 696 | called before :meth:`start` is called, otherwise :exc:`RuntimeError` is raised. | 
|  | 697 |  | 
|  | 698 | The initial value is inherited from the creating thread. | 
|  | 699 |  | 
|  | 700 | The entire Python program exits when no alive non-daemon threads are left. | 
|  | 701 |  | 
|  | 702 |  | 
|  | 703 | .. _timer-objects: | 
|  | 704 |  | 
|  | 705 | Timer Objects | 
|  | 706 | ------------- | 
|  | 707 |  | 
|  | 708 | This class represents an action that should be run only after a certain amount | 
|  | 709 | of time has passed --- a timer.  :class:`Timer` is a subclass of :class:`Thread` | 
|  | 710 | and as such also functions as an example of creating custom threads. | 
|  | 711 |  | 
|  | 712 | Timers are started, as with threads, by calling their :meth:`start` method.  The | 
|  | 713 | timer can be stopped (before its action has begun) by calling the :meth:`cancel` | 
|  | 714 | method.  The interval the timer will wait before executing its action may not be | 
|  | 715 | exactly the same as the interval specified by the user. | 
|  | 716 |  | 
|  | 717 | For example:: | 
|  | 718 |  | 
|  | 719 | def hello(): | 
|  | 720 | print "hello, world" | 
|  | 721 |  | 
|  | 722 | t = Timer(30.0, hello) | 
|  | 723 | t.start() # after 30 seconds, "hello, world" will be printed | 
|  | 724 |  | 
|  | 725 |  | 
|  | 726 | .. class:: Timer(interval, function, args=[], kwargs={}) | 
|  | 727 |  | 
|  | 728 | Create a timer that will run *function* with arguments *args* and  keyword | 
|  | 729 | arguments *kwargs*, after *interval* seconds have passed. | 
|  | 730 |  | 
|  | 731 |  | 
|  | 732 | .. method:: Timer.cancel() | 
|  | 733 |  | 
|  | 734 | Stop the timer, and cancel the execution of the timer's action.  This will only | 
|  | 735 | work if the timer is still in its waiting stage. | 
|  | 736 |  | 
|  | 737 |  | 
|  | 738 | .. _with-locks: | 
|  | 739 |  | 
|  | 740 | Using locks, conditions, and semaphores in the :keyword:`with` statement | 
|  | 741 | ------------------------------------------------------------------------ | 
|  | 742 |  | 
|  | 743 | All of the objects provided by this module that have :meth:`acquire` and | 
|  | 744 | :meth:`release` methods can be used as context managers for a :keyword:`with` | 
|  | 745 | statement.  The :meth:`acquire` method will be called when the block is entered, | 
|  | 746 | and :meth:`release` will be called when the block is exited. | 
|  | 747 |  | 
|  | 748 | Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`, | 
|  | 749 | :class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as | 
|  | 750 | :keyword:`with` statement context managers.  For example:: | 
|  | 751 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 752 | import threading | 
|  | 753 |  | 
|  | 754 | some_rlock = threading.RLock() | 
|  | 755 |  | 
|  | 756 | with some_rlock: | 
|  | 757 | print "some_rlock is locked while this executes" | 
|  | 758 |  | 
| Georg Brandl | 2e25551 | 2008-03-13 07:21:41 +0000 | [diff] [blame] | 759 |  | 
|  | 760 | .. _threaded-imports: | 
|  | 761 |  | 
|  | 762 | Importing in threaded code | 
|  | 763 | -------------------------- | 
|  | 764 |  | 
|  | 765 | While the import machinery is thread safe, there are two key | 
|  | 766 | restrictions on threaded imports due to inherent limitations in the way | 
|  | 767 | that thread safety is provided: | 
|  | 768 |  | 
|  | 769 | * Firstly, other than in the main module, an import should not have the | 
|  | 770 | side effect of spawning a new thread and then waiting for that thread in | 
|  | 771 | any way. Failing to abide by this restriction can lead to a deadlock if | 
|  | 772 | the spawned thread directly or indirectly attempts to import a module. | 
|  | 773 | * Secondly, all import attempts must be completed before the interpreter | 
|  | 774 | starts shutting itself down. This can be most easily achieved by only | 
|  | 775 | performing imports from non-daemon threads created through the threading | 
|  | 776 | module. Daemon threads and threads created directly with the thread | 
|  | 777 | module will require some other form of synchronization to ensure they do | 
|  | 778 | not attempt imports after system shutdown has commenced. Failure to | 
|  | 779 | abide by this restriction will lead to intermittent exceptions and | 
|  | 780 | crashes during interpreter shutdown (as the late imports attempt to | 
|  | 781 | access machinery which is no longer in a valid state). |