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