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