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