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