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