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