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