Jeremy Hylton | 92bb6e7 | 2002-08-14 19:25:42 +0000 | [diff] [blame] | 1 | """Thread module emulating a subset of Java's threading model.""" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 2 | |
Antoine Pitrou | 4a8bcdf | 2017-05-28 14:02:26 +0200 | [diff] [blame] | 3 | import os as _os |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 4 | import sys as _sys |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 5 | import _thread |
Kyle Stanley | b61b818 | 2020-03-27 15:31:22 -0400 | [diff] [blame] | 6 | import functools |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 7 | |
Victor Stinner | ae58649 | 2014-09-02 23:18:25 +0200 | [diff] [blame] | 8 | from time import monotonic as _time |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 9 | from _weakrefset import WeakSet |
R David Murray | b186f1df | 2014-10-04 17:43:54 -0400 | [diff] [blame] | 10 | from itertools import islice as _islice, count as _count |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 11 | try: |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 12 | from _collections import deque as _deque |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 13 | except ImportError: |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 14 | from collections import deque as _deque |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 15 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 16 | # Note regarding PEP 8 compliant names |
| 17 | # This threading model was originally inspired by Java, and inherited |
| 18 | # the convention of camelCase function and method names from that |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 19 | # language. Those original names are not in any imminent danger of |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 20 | # being deprecated (even for Py3k),so this module provides them as an |
| 21 | # alias for the PEP 8 compliant names |
| 22 | # Note that using the new PEP 8 compliant names facilitates substitution |
| 23 | # with the multiprocessing module, which doesn't provide the old |
| 24 | # Java inspired names. |
| 25 | |
Victor Stinner | d12e757 | 2019-05-21 12:44:57 +0200 | [diff] [blame] | 26 | __all__ = ['get_ident', 'active_count', 'Condition', 'current_thread', |
| 27 | 'enumerate', 'main_thread', 'TIMEOUT_MAX', |
Martin Panter | 19e69c5 | 2015-11-14 12:46:42 +0000 | [diff] [blame] | 28 | 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', |
| 29 | 'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError', |
Victor Stinner | cd590a7 | 2019-05-28 00:39:52 +0200 | [diff] [blame] | 30 | 'setprofile', 'settrace', 'local', 'stack_size', |
| 31 | 'excepthook', 'ExceptHookArgs'] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 32 | |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 33 | # Rename some stuff so "from threading import *" is safe |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 34 | _start_new_thread = _thread.start_new_thread |
| 35 | _allocate_lock = _thread.allocate_lock |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 36 | _set_sentinel = _thread._set_sentinel |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 37 | get_ident = _thread.get_ident |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 38 | try: |
| 39 | get_native_id = _thread.get_native_id |
| 40 | _HAVE_THREAD_NATIVE_ID = True |
| 41 | __all__.append('get_native_id') |
| 42 | except AttributeError: |
| 43 | _HAVE_THREAD_NATIVE_ID = False |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 44 | ThreadError = _thread.error |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 45 | try: |
| 46 | _CRLock = _thread.RLock |
| 47 | except AttributeError: |
| 48 | _CRLock = None |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 49 | TIMEOUT_MAX = _thread.TIMEOUT_MAX |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 50 | del _thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 51 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 52 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 53 | # Support for profile and trace hooks |
| 54 | |
| 55 | _profile_hook = None |
| 56 | _trace_hook = None |
| 57 | |
| 58 | def setprofile(func): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 59 | """Set a profile function for all threads started from the threading module. |
| 60 | |
| 61 | The func will be passed to sys.setprofile() for each thread, before its |
| 62 | run() method is called. |
| 63 | |
| 64 | """ |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 65 | global _profile_hook |
| 66 | _profile_hook = func |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 67 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 68 | def settrace(func): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 69 | """Set a trace function for all threads started from the threading module. |
| 70 | |
| 71 | The func will be passed to sys.settrace() for each thread, before its run() |
| 72 | method is called. |
| 73 | |
| 74 | """ |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 75 | global _trace_hook |
| 76 | _trace_hook = func |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 77 | |
| 78 | # Synchronization classes |
| 79 | |
| 80 | Lock = _allocate_lock |
| 81 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 82 | def RLock(*args, **kwargs): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 83 | """Factory function that returns a new reentrant lock. |
| 84 | |
| 85 | A reentrant lock must be released by the thread that acquired it. Once a |
| 86 | thread has acquired a reentrant lock, the same thread may acquire it again |
| 87 | without blocking; the thread must release it once for each time it has |
| 88 | acquired it. |
| 89 | |
| 90 | """ |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 91 | if _CRLock is None: |
| 92 | return _PyRLock(*args, **kwargs) |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 93 | return _CRLock(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 94 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 95 | class _RLock: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 96 | """This class implements reentrant lock objects. |
| 97 | |
| 98 | A reentrant lock must be released by the thread that acquired it. Once a |
| 99 | thread has acquired a reentrant lock, the same thread may acquire it |
| 100 | again without blocking; the thread must release it once for each time it |
| 101 | has acquired it. |
| 102 | |
| 103 | """ |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 104 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 105 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 106 | self._block = _allocate_lock() |
| 107 | self._owner = None |
| 108 | self._count = 0 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 109 | |
| 110 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 111 | owner = self._owner |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 112 | try: |
| 113 | owner = _active[owner].name |
| 114 | except KeyError: |
| 115 | pass |
Raymond Hettinger | 62f4dad | 2014-05-25 18:22:35 -0700 | [diff] [blame] | 116 | return "<%s %s.%s object owner=%r count=%d at %s>" % ( |
| 117 | "locked" if self._block.locked() else "unlocked", |
| 118 | self.__class__.__module__, |
| 119 | self.__class__.__qualname__, |
| 120 | owner, |
| 121 | self._count, |
| 122 | hex(id(self)) |
| 123 | ) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 124 | |
Victor Stinner | 87255be | 2020-04-07 23:11:49 +0200 | [diff] [blame] | 125 | def _at_fork_reinit(self): |
| 126 | self._block._at_fork_reinit() |
| 127 | self._owner = None |
| 128 | self._count = 0 |
| 129 | |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 130 | def acquire(self, blocking=True, timeout=-1): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 131 | """Acquire a lock, blocking or non-blocking. |
| 132 | |
| 133 | When invoked without arguments: if this thread already owns the lock, |
| 134 | increment the recursion level by one, and return immediately. Otherwise, |
| 135 | if another thread owns the lock, block until the lock is unlocked. Once |
| 136 | the lock is unlocked (not owned by any thread), then grab ownership, set |
| 137 | the recursion level to one, and return. If more than one thread is |
| 138 | blocked waiting until the lock is unlocked, only one at a time will be |
| 139 | able to grab ownership of the lock. There is no return value in this |
| 140 | case. |
| 141 | |
| 142 | When invoked with the blocking argument set to true, do the same thing |
| 143 | as when called without arguments, and return true. |
| 144 | |
| 145 | When invoked with the blocking argument set to false, do not block. If a |
| 146 | call without an argument would block, return false immediately; |
| 147 | otherwise, do the same thing as when called without arguments, and |
| 148 | return true. |
| 149 | |
| 150 | When invoked with the floating-point timeout argument set to a positive |
| 151 | value, block for at most the number of seconds specified by timeout |
| 152 | and as long as the lock cannot be acquired. Return true if the lock has |
| 153 | been acquired, false if the timeout has elapsed. |
| 154 | |
| 155 | """ |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 156 | me = get_ident() |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 157 | if self._owner == me: |
Raymond Hettinger | 720da57 | 2013-03-10 15:13:35 -0700 | [diff] [blame] | 158 | self._count += 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 159 | return 1 |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 160 | rc = self._block.acquire(blocking, timeout) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 161 | if rc: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 162 | self._owner = me |
| 163 | self._count = 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 164 | return rc |
| 165 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 166 | __enter__ = acquire |
| 167 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 168 | def release(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 169 | """Release a lock, decrementing the recursion level. |
| 170 | |
| 171 | If after the decrement it is zero, reset the lock to unlocked (not owned |
| 172 | by any thread), and if any other threads are blocked waiting for the |
| 173 | lock to become unlocked, allow exactly one of them to proceed. If after |
| 174 | the decrement the recursion level is still nonzero, the lock remains |
| 175 | locked and owned by the calling thread. |
| 176 | |
| 177 | Only call this method when the calling thread owns the lock. A |
| 178 | RuntimeError is raised if this method is called when the lock is |
| 179 | unlocked. |
| 180 | |
| 181 | There is no return value. |
| 182 | |
| 183 | """ |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 184 | if self._owner != get_ident(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 185 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 186 | self._count = count = self._count - 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 187 | if not count: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 188 | self._owner = None |
| 189 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 190 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 191 | def __exit__(self, t, v, tb): |
| 192 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 193 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 194 | # Internal methods used by condition variables |
| 195 | |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 196 | def _acquire_restore(self, state): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 197 | self._block.acquire() |
| 198 | self._count, self._owner = state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 199 | |
| 200 | def _release_save(self): |
Victor Stinner | c2824d4 | 2011-04-24 23:41:33 +0200 | [diff] [blame] | 201 | if self._count == 0: |
| 202 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 203 | count = self._count |
| 204 | self._count = 0 |
| 205 | owner = self._owner |
| 206 | self._owner = None |
| 207 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 208 | return (count, owner) |
| 209 | |
| 210 | def _is_owned(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 211 | return self._owner == get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 212 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 213 | _PyRLock = _RLock |
| 214 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 215 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 216 | class Condition: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 217 | """Class that implements a condition variable. |
| 218 | |
| 219 | A condition variable allows one or more threads to wait until they are |
| 220 | notified by another thread. |
| 221 | |
| 222 | If the lock argument is given and not None, it must be a Lock or RLock |
| 223 | object, and it is used as the underlying lock. Otherwise, a new RLock object |
| 224 | is created and used as the underlying lock. |
| 225 | |
| 226 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 227 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 228 | def __init__(self, lock=None): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 229 | if lock is None: |
| 230 | lock = RLock() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 231 | self._lock = lock |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 232 | # Export the lock's acquire() and release() methods |
| 233 | self.acquire = lock.acquire |
| 234 | self.release = lock.release |
| 235 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 236 | # these override the default implementations (which just call |
| 237 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 238 | try: |
| 239 | self._release_save = lock._release_save |
| 240 | except AttributeError: |
| 241 | pass |
| 242 | try: |
| 243 | self._acquire_restore = lock._acquire_restore |
| 244 | except AttributeError: |
| 245 | pass |
| 246 | try: |
| 247 | self._is_owned = lock._is_owned |
| 248 | except AttributeError: |
| 249 | pass |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 250 | self._waiters = _deque() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 251 | |
Victor Stinner | 87255be | 2020-04-07 23:11:49 +0200 | [diff] [blame] | 252 | def _at_fork_reinit(self): |
| 253 | self._lock._at_fork_reinit() |
| 254 | self._waiters.clear() |
| 255 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 256 | def __enter__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 257 | return self._lock.__enter__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 258 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 259 | def __exit__(self, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 260 | return self._lock.__exit__(*args) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 261 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 262 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 263 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 264 | |
| 265 | def _release_save(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 266 | self._lock.release() # No state to save |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 267 | |
| 268 | def _acquire_restore(self, x): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 269 | self._lock.acquire() # Ignore saved state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 270 | |
| 271 | def _is_owned(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 272 | # Return True if lock is owned by current_thread. |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 273 | # This method is called only if _lock doesn't have _is_owned(). |
Serhiy Storchaka | 1f21eaa | 2019-09-01 12:16:51 +0300 | [diff] [blame] | 274 | if self._lock.acquire(False): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 275 | self._lock.release() |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 276 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 277 | else: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 278 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 279 | |
| 280 | def wait(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 281 | """Wait until notified or until a timeout occurs. |
| 282 | |
| 283 | If the calling thread has not acquired the lock when this method is |
| 284 | called, a RuntimeError is raised. |
| 285 | |
| 286 | This method releases the underlying lock, and then blocks until it is |
| 287 | awakened by a notify() or notify_all() call for the same condition |
| 288 | variable in another thread, or until the optional timeout occurs. Once |
| 289 | awakened or timed out, it re-acquires the lock and returns. |
| 290 | |
| 291 | When the timeout argument is present and not None, it should be a |
| 292 | floating point number specifying a timeout for the operation in seconds |
| 293 | (or fractions thereof). |
| 294 | |
| 295 | When the underlying lock is an RLock, it is not released using its |
| 296 | release() method, since this may not actually unlock the lock when it |
| 297 | was acquired multiple times recursively. Instead, an internal interface |
| 298 | of the RLock class is used, which really unlocks it even when it has |
| 299 | been recursively acquired several times. Another internal interface is |
| 300 | then used to restore the recursion level when the lock is reacquired. |
| 301 | |
| 302 | """ |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 303 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 304 | raise RuntimeError("cannot wait on un-acquired lock") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 305 | waiter = _allocate_lock() |
| 306 | waiter.acquire() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 307 | self._waiters.append(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 308 | saved_state = self._release_save() |
Antoine Pitrou | a64b92e | 2014-08-29 23:26:36 +0200 | [diff] [blame] | 309 | gotit = False |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 310 | try: # restore state no matter what (e.g., KeyboardInterrupt) |
| 311 | if timeout is None: |
| 312 | waiter.acquire() |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 313 | gotit = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 314 | else: |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 315 | if timeout > 0: |
| 316 | gotit = waiter.acquire(True, timeout) |
| 317 | else: |
| 318 | gotit = waiter.acquire(False) |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 319 | return gotit |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 320 | finally: |
| 321 | self._acquire_restore(saved_state) |
Antoine Pitrou | a64b92e | 2014-08-29 23:26:36 +0200 | [diff] [blame] | 322 | if not gotit: |
| 323 | try: |
| 324 | self._waiters.remove(waiter) |
| 325 | except ValueError: |
| 326 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 327 | |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 328 | def wait_for(self, predicate, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 329 | """Wait until a condition evaluates to True. |
| 330 | |
| 331 | predicate should be a callable which result will be interpreted as a |
| 332 | boolean value. A timeout may be provided giving the maximum time to |
| 333 | wait. |
| 334 | |
| 335 | """ |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 336 | endtime = None |
| 337 | waittime = timeout |
| 338 | result = predicate() |
| 339 | while not result: |
| 340 | if waittime is not None: |
| 341 | if endtime is None: |
| 342 | endtime = _time() + waittime |
| 343 | else: |
| 344 | waittime = endtime - _time() |
| 345 | if waittime <= 0: |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 346 | break |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 347 | self.wait(waittime) |
| 348 | result = predicate() |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 349 | return result |
| 350 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 351 | def notify(self, n=1): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 352 | """Wake up one or more threads waiting on this condition, if any. |
| 353 | |
| 354 | If the calling thread has not acquired the lock when this method is |
| 355 | called, a RuntimeError is raised. |
| 356 | |
| 357 | This method wakes up at most n of the threads waiting for the condition |
| 358 | variable; it is a no-op if no threads are waiting. |
| 359 | |
| 360 | """ |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 361 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 362 | raise RuntimeError("cannot notify on un-acquired lock") |
Raymond Hettinger | b65e579 | 2013-03-10 20:34:16 -0700 | [diff] [blame] | 363 | all_waiters = self._waiters |
| 364 | waiters_to_notify = _deque(_islice(all_waiters, n)) |
| 365 | if not waiters_to_notify: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 366 | return |
Raymond Hettinger | b65e579 | 2013-03-10 20:34:16 -0700 | [diff] [blame] | 367 | for waiter in waiters_to_notify: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 368 | waiter.release() |
| 369 | try: |
Raymond Hettinger | b65e579 | 2013-03-10 20:34:16 -0700 | [diff] [blame] | 370 | all_waiters.remove(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 371 | except ValueError: |
| 372 | pass |
| 373 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 374 | def notify_all(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 375 | """Wake up all threads waiting on this condition. |
| 376 | |
| 377 | If the calling thread has not acquired the lock when this method |
| 378 | is called, a RuntimeError is raised. |
| 379 | |
| 380 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 381 | self.notify(len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 382 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 383 | notifyAll = notify_all |
| 384 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 385 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 386 | class Semaphore: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 387 | """This class implements semaphore objects. |
| 388 | |
| 389 | Semaphores manage a counter representing the number of release() calls minus |
| 390 | the number of acquire() calls, plus an initial value. The acquire() method |
| 391 | blocks if necessary until it can return without making the counter |
| 392 | negative. If not given, value defaults to 1. |
| 393 | |
| 394 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 395 | |
Andrew M. Kuchling | 39d3bfc | 2000-02-29 00:10:24 +0000 | [diff] [blame] | 396 | # After Tim Peters' semaphore class, but not quite the same (no maximum) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 397 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 398 | def __init__(self, value=1): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 399 | if value < 0: |
| 400 | raise ValueError("semaphore initial value must be >= 0") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 401 | self._cond = Condition(Lock()) |
| 402 | self._value = value |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 403 | |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 404 | def acquire(self, blocking=True, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 405 | """Acquire a semaphore, decrementing the internal counter by one. |
| 406 | |
| 407 | When invoked without arguments: if the internal counter is larger than |
| 408 | zero on entry, decrement it by one and return immediately. If it is zero |
| 409 | on entry, block, waiting until some other thread has called release() to |
| 410 | make it larger than zero. This is done with proper interlocking so that |
| 411 | if multiple acquire() calls are blocked, release() will wake exactly one |
| 412 | of them up. The implementation may pick one at random, so the order in |
| 413 | which blocked threads are awakened should not be relied on. There is no |
| 414 | return value in this case. |
| 415 | |
| 416 | When invoked with blocking set to true, do the same thing as when called |
| 417 | without arguments, and return true. |
| 418 | |
| 419 | When invoked with blocking set to false, do not block. If a call without |
| 420 | an argument would block, return false immediately; otherwise, do the |
| 421 | same thing as when called without arguments, and return true. |
| 422 | |
| 423 | When invoked with a timeout other than None, it will block for at |
| 424 | most timeout seconds. If acquire does not complete successfully in |
| 425 | that interval, return false. Return true otherwise. |
| 426 | |
| 427 | """ |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 428 | if not blocking and timeout is not None: |
| 429 | raise ValueError("can't specify timeout for non-blocking acquire") |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 430 | rc = False |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 431 | endtime = None |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 432 | with self._cond: |
| 433 | while self._value == 0: |
| 434 | if not blocking: |
| 435 | break |
| 436 | if timeout is not None: |
| 437 | if endtime is None: |
| 438 | endtime = _time() + timeout |
| 439 | else: |
| 440 | timeout = endtime - _time() |
| 441 | if timeout <= 0: |
| 442 | break |
| 443 | self._cond.wait(timeout) |
| 444 | else: |
Serhiy Storchaka | b00b596 | 2013-04-22 22:54:16 +0300 | [diff] [blame] | 445 | self._value -= 1 |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 446 | rc = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 447 | return rc |
| 448 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 449 | __enter__ = acquire |
| 450 | |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 451 | def release(self, n=1): |
| 452 | """Release a semaphore, incrementing the internal counter by one or more. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 453 | |
| 454 | When the counter is zero on entry and another thread is waiting for it |
| 455 | to become larger than zero again, wake up that thread. |
| 456 | |
| 457 | """ |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 458 | if n < 1: |
| 459 | raise ValueError('n must be one or more') |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 460 | with self._cond: |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 461 | self._value += n |
| 462 | for i in range(n): |
| 463 | self._cond.notify() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 464 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 465 | def __exit__(self, t, v, tb): |
| 466 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 467 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 468 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 469 | class BoundedSemaphore(Semaphore): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 470 | """Implements a bounded semaphore. |
| 471 | |
| 472 | A bounded semaphore checks to make sure its current value doesn't exceed its |
| 473 | initial value. If it does, ValueError is raised. In most situations |
| 474 | semaphores are used to guard resources with limited capacity. |
| 475 | |
| 476 | If the semaphore is released too many times it's a sign of a bug. If not |
| 477 | given, value defaults to 1. |
| 478 | |
| 479 | Like regular semaphores, bounded semaphores manage a counter representing |
| 480 | the number of release() calls minus the number of acquire() calls, plus an |
| 481 | initial value. The acquire() method blocks if necessary until it can return |
| 482 | without making the counter negative. If not given, value defaults to 1. |
| 483 | |
| 484 | """ |
| 485 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 486 | def __init__(self, value=1): |
| 487 | Semaphore.__init__(self, value) |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 488 | self._initial_value = value |
| 489 | |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 490 | def release(self, n=1): |
| 491 | """Release a semaphore, incrementing the internal counter by one or more. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 492 | |
| 493 | When the counter is zero on entry and another thread is waiting for it |
| 494 | to become larger than zero again, wake up that thread. |
| 495 | |
| 496 | If the number of releases exceeds the number of acquires, |
| 497 | raise a ValueError. |
| 498 | |
| 499 | """ |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 500 | if n < 1: |
| 501 | raise ValueError('n must be one or more') |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame] | 502 | with self._cond: |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 503 | if self._value + n > self._initial_value: |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame] | 504 | raise ValueError("Semaphore released too many times") |
Raymond Hettinger | 35f6301 | 2019-08-29 01:45:19 -0700 | [diff] [blame] | 505 | self._value += n |
| 506 | for i in range(n): |
| 507 | self._cond.notify() |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 508 | |
| 509 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 510 | class Event: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 511 | """Class implementing event objects. |
| 512 | |
| 513 | Events manage a flag that can be set to true with the set() method and reset |
| 514 | to false with the clear() method. The wait() method blocks until the flag is |
| 515 | true. The flag is initially false. |
| 516 | |
| 517 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 518 | |
| 519 | # After Tim Peters' event class (without is_posted()) |
| 520 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 521 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 522 | self._cond = Condition(Lock()) |
| 523 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 524 | |
Victor Stinner | 87255be | 2020-04-07 23:11:49 +0200 | [diff] [blame] | 525 | def _at_fork_reinit(self): |
| 526 | # Private method called by Thread._reset_internal_locks() |
| 527 | self._cond._at_fork_reinit() |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 528 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 529 | def is_set(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 530 | """Return true if and only if the internal flag is true.""" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 531 | return self._flag |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 532 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 533 | isSet = is_set |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 534 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 535 | def set(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 536 | """Set the internal flag to true. |
| 537 | |
| 538 | All threads waiting for it to become true are awakened. Threads |
| 539 | that call wait() once the flag is true will not block at all. |
| 540 | |
| 541 | """ |
Benjamin Peterson | 414918a | 2015-10-10 19:34:46 -0700 | [diff] [blame] | 542 | with self._cond: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 543 | self._flag = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 544 | self._cond.notify_all() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 545 | |
| 546 | def clear(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 547 | """Reset the internal flag to false. |
| 548 | |
| 549 | Subsequently, threads calling wait() will block until set() is called to |
| 550 | set the internal flag to true again. |
| 551 | |
| 552 | """ |
Benjamin Peterson | 414918a | 2015-10-10 19:34:46 -0700 | [diff] [blame] | 553 | with self._cond: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 554 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 555 | |
| 556 | def wait(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 557 | """Block until the internal flag is true. |
| 558 | |
| 559 | If the internal flag is true on entry, return immediately. Otherwise, |
| 560 | block until another thread calls set() to set the flag to true, or until |
| 561 | the optional timeout occurs. |
| 562 | |
| 563 | When the timeout argument is present and not None, it should be a |
| 564 | floating point number specifying a timeout for the operation in seconds |
| 565 | (or fractions thereof). |
| 566 | |
| 567 | This method returns the internal flag on exit, so it will always return |
| 568 | True except if a timeout is given and the operation times out. |
| 569 | |
| 570 | """ |
Benjamin Peterson | 414918a | 2015-10-10 19:34:46 -0700 | [diff] [blame] | 571 | with self._cond: |
Charles-François Natali | ded0348 | 2012-01-07 18:24:56 +0100 | [diff] [blame] | 572 | signaled = self._flag |
| 573 | if not signaled: |
| 574 | signaled = self._cond.wait(timeout) |
| 575 | return signaled |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 576 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 577 | |
| 578 | # A barrier class. Inspired in part by the pthread_barrier_* api and |
| 579 | # the CyclicBarrier class from Java. See |
| 580 | # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and |
| 581 | # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ |
| 582 | # CyclicBarrier.html |
| 583 | # for information. |
| 584 | # We maintain two main states, 'filling' and 'draining' enabling the barrier |
| 585 | # to be cyclic. Threads are not allowed into it until it has fully drained |
| 586 | # since the previous cycle. In addition, a 'resetting' state exists which is |
| 587 | # similar to 'draining' except that threads leave with a BrokenBarrierError, |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 588 | # and a 'broken' state in which all threads get the exception. |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 589 | class Barrier: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 590 | """Implements a Barrier. |
| 591 | |
| 592 | Useful for synchronizing a fixed number of threads at known synchronization |
Carl Bordum Hansen | 62fa51f | 2019-03-09 18:38:05 +0100 | [diff] [blame] | 593 | points. Threads block on 'wait()' and are simultaneously awoken once they |
| 594 | have all made that call. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 595 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 596 | """ |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 597 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 598 | def __init__(self, parties, action=None, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 599 | """Create a barrier, initialised to 'parties' threads. |
| 600 | |
| 601 | 'action' is a callable which, when supplied, will be called by one of |
| 602 | the threads after they have all entered the barrier and just prior to |
Carl Bordum Hansen | 62fa51f | 2019-03-09 18:38:05 +0100 | [diff] [blame] | 603 | releasing them all. If a 'timeout' is provided, it is used as the |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 604 | default for all subsequent 'wait()' calls. |
| 605 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 606 | """ |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 607 | self._cond = Condition(Lock()) |
| 608 | self._action = action |
| 609 | self._timeout = timeout |
| 610 | self._parties = parties |
| 611 | self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken |
| 612 | self._count = 0 |
| 613 | |
| 614 | def wait(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 615 | """Wait for the barrier. |
| 616 | |
| 617 | When the specified number of threads have started waiting, they are all |
| 618 | simultaneously awoken. If an 'action' was provided for the barrier, one |
| 619 | of the threads will have executed that callback prior to returning. |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 620 | Returns an individual index number from 0 to 'parties-1'. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 621 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 622 | """ |
| 623 | if timeout is None: |
| 624 | timeout = self._timeout |
| 625 | with self._cond: |
| 626 | self._enter() # Block while the barrier drains. |
| 627 | index = self._count |
| 628 | self._count += 1 |
| 629 | try: |
| 630 | if index + 1 == self._parties: |
| 631 | # We release the barrier |
| 632 | self._release() |
| 633 | else: |
| 634 | # We wait until someone releases us |
| 635 | self._wait(timeout) |
| 636 | return index |
| 637 | finally: |
| 638 | self._count -= 1 |
| 639 | # Wake up any threads waiting for barrier to drain. |
| 640 | self._exit() |
| 641 | |
| 642 | # Block until the barrier is ready for us, or raise an exception |
| 643 | # if it is broken. |
| 644 | def _enter(self): |
| 645 | while self._state in (-1, 1): |
| 646 | # It is draining or resetting, wait until done |
| 647 | self._cond.wait() |
| 648 | #see if the barrier is in a broken state |
| 649 | if self._state < 0: |
| 650 | raise BrokenBarrierError |
| 651 | assert self._state == 0 |
| 652 | |
| 653 | # Optionally run the 'action' and release the threads waiting |
| 654 | # in the barrier. |
| 655 | def _release(self): |
| 656 | try: |
| 657 | if self._action: |
| 658 | self._action() |
| 659 | # enter draining state |
| 660 | self._state = 1 |
| 661 | self._cond.notify_all() |
| 662 | except: |
| 663 | #an exception during the _action handler. Break and reraise |
| 664 | self._break() |
| 665 | raise |
| 666 | |
Martin Panter | 69332c1 | 2016-08-04 13:07:31 +0000 | [diff] [blame] | 667 | # Wait in the barrier until we are released. Raise an exception |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 668 | # if the barrier is reset or broken. |
| 669 | def _wait(self, timeout): |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 670 | if not self._cond.wait_for(lambda : self._state != 0, timeout): |
| 671 | #timed out. Break the barrier |
| 672 | self._break() |
| 673 | raise BrokenBarrierError |
| 674 | if self._state < 0: |
| 675 | raise BrokenBarrierError |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 676 | assert self._state == 1 |
| 677 | |
| 678 | # If we are the last thread to exit the barrier, signal any threads |
| 679 | # waiting for the barrier to drain. |
| 680 | def _exit(self): |
| 681 | if self._count == 0: |
| 682 | if self._state in (-1, 1): |
| 683 | #resetting or draining |
| 684 | self._state = 0 |
| 685 | self._cond.notify_all() |
| 686 | |
| 687 | def reset(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 688 | """Reset the barrier to the initial state. |
| 689 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 690 | Any threads currently waiting will get the BrokenBarrier exception |
| 691 | raised. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 692 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 693 | """ |
| 694 | with self._cond: |
| 695 | if self._count > 0: |
| 696 | if self._state == 0: |
| 697 | #reset the barrier, waking up threads |
| 698 | self._state = -1 |
| 699 | elif self._state == -2: |
| 700 | #was broken, set it to reset state |
| 701 | #which clears when the last thread exits |
| 702 | self._state = -1 |
| 703 | else: |
| 704 | self._state = 0 |
| 705 | self._cond.notify_all() |
| 706 | |
| 707 | def abort(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 708 | """Place the barrier into a 'broken' state. |
| 709 | |
| 710 | Useful in case of error. Any currently waiting threads and threads |
| 711 | attempting to 'wait()' will have BrokenBarrierError raised. |
| 712 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 713 | """ |
| 714 | with self._cond: |
| 715 | self._break() |
| 716 | |
| 717 | def _break(self): |
| 718 | # An internal error was detected. The barrier is set to |
| 719 | # a broken state all parties awakened. |
| 720 | self._state = -2 |
| 721 | self._cond.notify_all() |
| 722 | |
| 723 | @property |
| 724 | def parties(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 725 | """Return the number of threads required to trip the barrier.""" |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 726 | return self._parties |
| 727 | |
| 728 | @property |
| 729 | def n_waiting(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 730 | """Return the number of threads currently waiting at the barrier.""" |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 731 | # We don't need synchronization here since this is an ephemeral result |
| 732 | # anyway. It returns the correct value in the steady state. |
| 733 | if self._state == 0: |
| 734 | return self._count |
| 735 | return 0 |
| 736 | |
| 737 | @property |
| 738 | def broken(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 739 | """Return True if the barrier is in a broken state.""" |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 740 | return self._state == -2 |
| 741 | |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 742 | # exception raised by the Barrier class |
| 743 | class BrokenBarrierError(RuntimeError): |
| 744 | pass |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 745 | |
| 746 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 747 | # Helper to generate new thread names |
R David Murray | b186f1df | 2014-10-04 17:43:54 -0400 | [diff] [blame] | 748 | _counter = _count().__next__ |
| 749 | _counter() # Consume 0 so first non-main thread has id 1. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 750 | def _newname(template="Thread-%d"): |
R David Murray | b186f1df | 2014-10-04 17:43:54 -0400 | [diff] [blame] | 751 | return template % _counter() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 752 | |
| 753 | # Active thread administration |
| 754 | _active_limbo_lock = _allocate_lock() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 755 | _active = {} # maps thread id to Thread object |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 756 | _limbo = {} |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 757 | _dangling = WeakSet() |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 758 | # Set of Thread._tstate_lock locks of non-daemon threads used by _shutdown() |
| 759 | # to wait until all Python thread states get deleted: |
| 760 | # see Thread._set_tstate_lock(). |
| 761 | _shutdown_locks_lock = _allocate_lock() |
| 762 | _shutdown_locks = set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 763 | |
| 764 | # Main class for threads |
| 765 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 766 | class Thread: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 767 | """A class that represents a thread of control. |
| 768 | |
| 769 | This class can be safely subclassed in a limited fashion. There are two ways |
| 770 | to specify the activity: by passing a callable object to the constructor, or |
| 771 | by overriding the run() method in a subclass. |
| 772 | |
| 773 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 774 | |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 775 | _initialized = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 776 | |
| 777 | def __init__(self, group=None, target=None, name=None, |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 778 | args=(), kwargs=None, *, daemon=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 779 | """This constructor should always be called with keyword arguments. Arguments are: |
| 780 | |
| 781 | *group* should be None; reserved for future extension when a ThreadGroup |
| 782 | class is implemented. |
| 783 | |
| 784 | *target* is the callable object to be invoked by the run() |
| 785 | method. Defaults to None, meaning nothing is called. |
| 786 | |
| 787 | *name* is the thread name. By default, a unique name is constructed of |
| 788 | the form "Thread-N" where N is a small decimal number. |
| 789 | |
| 790 | *args* is the argument tuple for the target invocation. Defaults to (). |
| 791 | |
| 792 | *kwargs* is a dictionary of keyword arguments for the target |
| 793 | invocation. Defaults to {}. |
| 794 | |
| 795 | If a subclass overrides the constructor, it must make sure to invoke |
| 796 | the base class constructor (Thread.__init__()) before doing anything |
| 797 | else to the thread. |
| 798 | |
| 799 | """ |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 800 | assert group is None, "group argument must be None for now" |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 801 | if kwargs is None: |
| 802 | kwargs = {} |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 803 | self._target = target |
| 804 | self._name = str(name or _newname()) |
| 805 | self._args = args |
| 806 | self._kwargs = kwargs |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 807 | if daemon is not None: |
| 808 | self._daemonic = daemon |
| 809 | else: |
| 810 | self._daemonic = current_thread().daemon |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 811 | self._ident = None |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 812 | if _HAVE_THREAD_NATIVE_ID: |
| 813 | self._native_id = None |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 814 | self._tstate_lock = None |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 815 | self._started = Event() |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 816 | self._is_stopped = False |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 817 | self._initialized = True |
Victor Stinner | cd590a7 | 2019-05-28 00:39:52 +0200 | [diff] [blame] | 818 | # Copy of sys.stderr used by self._invoke_excepthook() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 819 | self._stderr = _sys.stderr |
Victor Stinner | cd590a7 | 2019-05-28 00:39:52 +0200 | [diff] [blame] | 820 | self._invoke_excepthook = _make_invoke_excepthook() |
Antoine Pitrou | 5da7e79 | 2013-09-08 13:19:06 +0200 | [diff] [blame] | 821 | # For debugging and _after_fork() |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 822 | _dangling.add(self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 823 | |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 824 | def _reset_internal_locks(self, is_alive): |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 825 | # private! Called by _after_fork() to reset our internal locks as |
| 826 | # they may be in an invalid state leading to a deadlock or crash. |
Victor Stinner | 87255be | 2020-04-07 23:11:49 +0200 | [diff] [blame] | 827 | self._started._at_fork_reinit() |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 828 | if is_alive: |
Victor Stinner | 87255be | 2020-04-07 23:11:49 +0200 | [diff] [blame] | 829 | self._tstate_lock._at_fork_reinit() |
| 830 | self._tstate_lock.acquire() |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 831 | else: |
| 832 | # The thread isn't alive after fork: it doesn't have a tstate |
| 833 | # anymore. |
Tim Peters | b5e9ac9 | 2013-09-09 14:41:50 -0500 | [diff] [blame] | 834 | self._is_stopped = True |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 835 | self._tstate_lock = None |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 836 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 837 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 838 | assert self._initialized, "Thread.__init__() was not called" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 839 | status = "initial" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 840 | if self._started.is_set(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 841 | status = "started" |
Tim Peters | 72460fa | 2013-09-09 18:48:24 -0500 | [diff] [blame] | 842 | self.is_alive() # easy way to get ._is_stopped set when appropriate |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 843 | if self._is_stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 844 | status = "stopped" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 845 | if self._daemonic: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 846 | status += " daemon" |
| 847 | if self._ident is not None: |
| 848 | status += " %s" % self._ident |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 849 | return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 850 | |
| 851 | def start(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 852 | """Start the thread's activity. |
| 853 | |
| 854 | It must be called at most once per thread object. It arranges for the |
| 855 | object's run() method to be invoked in a separate thread of control. |
| 856 | |
| 857 | This method will raise a RuntimeError if called more than once on the |
| 858 | same thread object. |
| 859 | |
| 860 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 861 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 862 | raise RuntimeError("thread.__init__() not called") |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 863 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 864 | if self._started.is_set(): |
Senthil Kumaran | fdd4d0f | 2010-04-06 03:30:18 +0000 | [diff] [blame] | 865 | raise RuntimeError("threads can only be started once") |
Victor Stinner | 066e5b1 | 2019-06-14 18:55:22 +0200 | [diff] [blame] | 866 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 867 | with _active_limbo_lock: |
| 868 | _limbo[self] = self |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 869 | try: |
| 870 | _start_new_thread(self._bootstrap, ()) |
| 871 | except Exception: |
| 872 | with _active_limbo_lock: |
| 873 | del _limbo[self] |
| 874 | raise |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 875 | self._started.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 876 | |
| 877 | def run(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 878 | """Method representing the thread's activity. |
| 879 | |
| 880 | You may override this method in a subclass. The standard run() method |
| 881 | invokes the callable object passed to the object's constructor as the |
| 882 | target argument, if any, with sequential and keyword arguments taken |
| 883 | from the args and kwargs arguments, respectively. |
| 884 | |
| 885 | """ |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 886 | try: |
| 887 | if self._target: |
| 888 | self._target(*self._args, **self._kwargs) |
| 889 | finally: |
| 890 | # Avoid a refcycle if the thread is running a function with |
| 891 | # an argument that has a member that points to the thread. |
| 892 | del self._target, self._args, self._kwargs |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 893 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 894 | def _bootstrap(self): |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 895 | # Wrapper around the real bootstrap code that ignores |
| 896 | # exceptions during interpreter cleanup. Those typically |
| 897 | # happen when a daemon thread wakes up at an unfortunate |
| 898 | # moment, finds the world around it destroyed, and raises some |
| 899 | # random exception *** while trying to report the exception in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 900 | # _bootstrap_inner() below ***. Those random exceptions |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 901 | # don't help anybody, and they confuse users, so we suppress |
| 902 | # them. We suppress them only when it appears that the world |
| 903 | # indeed has already been destroyed, so that exceptions in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 904 | # _bootstrap_inner() during normal business hours are properly |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 905 | # reported. Also, we only suppress them for daemonic threads; |
| 906 | # if a non-daemonic encounters this, something else is wrong. |
| 907 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 908 | self._bootstrap_inner() |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 909 | except: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 910 | if self._daemonic and _sys is None: |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 911 | return |
| 912 | raise |
| 913 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 914 | def _set_ident(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 915 | self._ident = get_ident() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 916 | |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 917 | if _HAVE_THREAD_NATIVE_ID: |
| 918 | def _set_native_id(self): |
| 919 | self._native_id = get_native_id() |
| 920 | |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 921 | def _set_tstate_lock(self): |
| 922 | """ |
| 923 | Set a lock object which will be released by the interpreter when |
| 924 | the underlying thread state (see pystate.h) gets deleted. |
| 925 | """ |
| 926 | self._tstate_lock = _set_sentinel() |
| 927 | self._tstate_lock.acquire() |
| 928 | |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 929 | if not self.daemon: |
| 930 | with _shutdown_locks_lock: |
| 931 | _shutdown_locks.add(self._tstate_lock) |
| 932 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 933 | def _bootstrap_inner(self): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 934 | try: |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 935 | self._set_ident() |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 936 | self._set_tstate_lock() |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 937 | if _HAVE_THREAD_NATIVE_ID: |
| 938 | self._set_native_id() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 939 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 940 | with _active_limbo_lock: |
| 941 | _active[self._ident] = self |
| 942 | del _limbo[self] |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 943 | |
| 944 | if _trace_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 945 | _sys.settrace(_trace_hook) |
| 946 | if _profile_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 947 | _sys.setprofile(_profile_hook) |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 948 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 949 | try: |
| 950 | self.run() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 951 | except: |
Victor Stinner | cd590a7 | 2019-05-28 00:39:52 +0200 | [diff] [blame] | 952 | self._invoke_excepthook(self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 953 | finally: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 954 | with _active_limbo_lock: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 955 | try: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 956 | # We don't call self._delete() because it also |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 957 | # grabs _active_limbo_lock. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 958 | del _active[get_ident()] |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 959 | except: |
| 960 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 961 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 962 | def _stop(self): |
Tim Peters | b5e9ac9 | 2013-09-09 14:41:50 -0500 | [diff] [blame] | 963 | # After calling ._stop(), .is_alive() returns False and .join() returns |
| 964 | # immediately. ._tstate_lock must be released before calling ._stop(). |
| 965 | # |
| 966 | # Normal case: C code at the end of the thread's life |
| 967 | # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and |
| 968 | # that's detected by our ._wait_for_tstate_lock(), called by .join() |
| 969 | # and .is_alive(). Any number of threads _may_ call ._stop() |
| 970 | # simultaneously (for example, if multiple threads are blocked in |
| 971 | # .join() calls), and they're not serialized. That's harmless - |
| 972 | # they'll just make redundant rebindings of ._is_stopped and |
| 973 | # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the |
| 974 | # "assert self._is_stopped" in ._wait_for_tstate_lock() always works |
| 975 | # (the assert is executed only if ._tstate_lock is None). |
| 976 | # |
| 977 | # Special case: _main_thread releases ._tstate_lock via this |
| 978 | # module's _shutdown() function. |
| 979 | lock = self._tstate_lock |
| 980 | if lock is not None: |
| 981 | assert not lock.locked() |
Tim Peters | 7875523 | 2013-09-09 13:47:16 -0500 | [diff] [blame] | 982 | self._is_stopped = True |
| 983 | self._tstate_lock = None |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 984 | if not self.daemon: |
| 985 | with _shutdown_locks_lock: |
Victor Stinner | 6f75c87 | 2019-06-13 12:06:24 +0200 | [diff] [blame] | 986 | _shutdown_locks.discard(lock) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 987 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 988 | def _delete(self): |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 989 | "Remove current thread from the dict of currently running threads." |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 990 | with _active_limbo_lock: |
| 991 | del _active[get_ident()] |
| 992 | # There must not be any python code between the previous line |
| 993 | # and after the lock is released. Otherwise a tracing function |
| 994 | # could try to acquire the lock again in the same thread, (in |
| 995 | # current_thread()), and would block. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 996 | |
| 997 | def join(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 998 | """Wait until the thread terminates. |
| 999 | |
| 1000 | This blocks the calling thread until the thread whose join() method is |
| 1001 | called terminates -- either normally or through an unhandled exception |
| 1002 | or until the optional timeout occurs. |
| 1003 | |
| 1004 | When the timeout argument is present and not None, it should be a |
| 1005 | floating point number specifying a timeout for the operation in seconds |
| 1006 | (or fractions thereof). As join() always returns None, you must call |
Dong-hee Na | 36d9e9a | 2019-01-18 18:50:47 +0900 | [diff] [blame] | 1007 | is_alive() after join() to decide whether a timeout happened -- if the |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1008 | thread is still alive, the join() call timed out. |
| 1009 | |
| 1010 | When the timeout argument is not present or None, the operation will |
| 1011 | block until the thread terminates. |
| 1012 | |
| 1013 | A thread can be join()ed many times. |
| 1014 | |
| 1015 | join() raises a RuntimeError if an attempt is made to join the current |
| 1016 | thread as that would cause a deadlock. It is also an error to join() a |
| 1017 | thread before it has been started and attempts to do so raises the same |
| 1018 | exception. |
| 1019 | |
| 1020 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1021 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1022 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1023 | if not self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1024 | raise RuntimeError("cannot join thread before it is started") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1025 | if self is current_thread(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1026 | raise RuntimeError("cannot join current thread") |
Tim Peters | e5bb0bf | 2013-10-25 20:46:51 -0500 | [diff] [blame] | 1027 | |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1028 | if timeout is None: |
| 1029 | self._wait_for_tstate_lock() |
Tim Peters | 7bad39f | 2013-10-25 22:33:52 -0500 | [diff] [blame] | 1030 | else: |
| 1031 | # the behavior of a negative timeout isn't documented, but |
Tim Peters | a577f1e | 2013-10-26 11:56:16 -0500 | [diff] [blame] | 1032 | # historically .join(timeout=x) for x<0 has acted as if timeout=0 |
Tim Peters | 7bad39f | 2013-10-25 22:33:52 -0500 | [diff] [blame] | 1033 | self._wait_for_tstate_lock(timeout=max(timeout, 0)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1034 | |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1035 | def _wait_for_tstate_lock(self, block=True, timeout=-1): |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1036 | # Issue #18808: wait for the thread state to be gone. |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1037 | # At the end of the thread's life, after all knowledge of the thread |
| 1038 | # is removed from C data structures, C code releases our _tstate_lock. |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 1039 | # This method passes its arguments to _tstate_lock.acquire(). |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1040 | # If the lock is acquired, the C code is done, and self._stop() is |
| 1041 | # called. That sets ._is_stopped to True, and ._tstate_lock to None. |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1042 | lock = self._tstate_lock |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1043 | if lock is None: # already determined that the C code is done |
| 1044 | assert self._is_stopped |
| 1045 | elif lock.acquire(block, timeout): |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1046 | lock.release() |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1047 | self._stop() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1048 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1049 | @property |
| 1050 | def name(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1051 | """A string used for identification purposes only. |
| 1052 | |
| 1053 | It has no semantics. Multiple threads may be given the same name. The |
| 1054 | initial name is set by the constructor. |
| 1055 | |
| 1056 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1057 | assert self._initialized, "Thread.__init__() not called" |
| 1058 | return self._name |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1059 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1060 | @name.setter |
| 1061 | def name(self, name): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1062 | assert self._initialized, "Thread.__init__() not called" |
| 1063 | self._name = str(name) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1064 | |
Benjamin Peterson | 773c17b | 2008-08-18 16:45:31 +0000 | [diff] [blame] | 1065 | @property |
| 1066 | def ident(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1067 | """Thread identifier of this thread or None if it has not been started. |
| 1068 | |
Skip Montanaro | 5634331 | 2018-05-18 13:38:36 -0500 | [diff] [blame] | 1069 | This is a nonzero integer. See the get_ident() function. Thread |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1070 | identifiers may be recycled when a thread exits and another thread is |
| 1071 | created. The identifier is available even after the thread has exited. |
| 1072 | |
| 1073 | """ |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1074 | assert self._initialized, "Thread.__init__() not called" |
| 1075 | return self._ident |
| 1076 | |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 1077 | if _HAVE_THREAD_NATIVE_ID: |
| 1078 | @property |
| 1079 | def native_id(self): |
| 1080 | """Native integral thread ID of this thread, or None if it has not been started. |
| 1081 | |
| 1082 | This is a non-negative integer. See the get_native_id() function. |
| 1083 | This represents the Thread ID as reported by the kernel. |
| 1084 | |
| 1085 | """ |
| 1086 | assert self._initialized, "Thread.__init__() not called" |
| 1087 | return self._native_id |
| 1088 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1089 | def is_alive(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1090 | """Return whether the thread is alive. |
| 1091 | |
| 1092 | This method returns True just before the run() method starts until just |
| 1093 | after the run() method terminates. The module function enumerate() |
| 1094 | returns a list of all alive threads. |
| 1095 | |
| 1096 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1097 | assert self._initialized, "Thread.__init__() not called" |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1098 | if self._is_stopped or not self._started.is_set(): |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1099 | return False |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1100 | self._wait_for_tstate_lock(False) |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1101 | return not self._is_stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 1102 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1103 | @property |
| 1104 | def daemon(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1105 | """A boolean value indicating whether this thread is a daemon thread. |
| 1106 | |
| 1107 | This must be set before start() is called, otherwise RuntimeError is |
| 1108 | raised. Its initial value is inherited from the creating thread; the |
| 1109 | main thread is not a daemon thread and therefore all threads created in |
| 1110 | the main thread default to daemon = False. |
| 1111 | |
mbarkhau | bb110cc | 2019-06-22 14:51:06 +0200 | [diff] [blame] | 1112 | The entire Python program exits when only daemon threads are left. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1113 | |
| 1114 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1115 | assert self._initialized, "Thread.__init__() not called" |
| 1116 | return self._daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1117 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1118 | @daemon.setter |
| 1119 | def daemon(self, daemonic): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1120 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1121 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1122 | if self._started.is_set(): |
Antoine Pitrou | 1095907 | 2014-03-17 18:22:41 +0100 | [diff] [blame] | 1123 | raise RuntimeError("cannot set daemon status of active thread") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1124 | self._daemonic = daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1125 | |
Benjamin Peterson | 6640d72 | 2008-08-18 18:16:46 +0000 | [diff] [blame] | 1126 | def isDaemon(self): |
| 1127 | return self.daemon |
| 1128 | |
| 1129 | def setDaemon(self, daemonic): |
| 1130 | self.daemon = daemonic |
| 1131 | |
| 1132 | def getName(self): |
| 1133 | return self.name |
| 1134 | |
| 1135 | def setName(self, name): |
| 1136 | self.name = name |
| 1137 | |
Victor Stinner | cd590a7 | 2019-05-28 00:39:52 +0200 | [diff] [blame] | 1138 | |
| 1139 | try: |
| 1140 | from _thread import (_excepthook as excepthook, |
| 1141 | _ExceptHookArgs as ExceptHookArgs) |
| 1142 | except ImportError: |
| 1143 | # Simple Python implementation if _thread._excepthook() is not available |
| 1144 | from traceback import print_exception as _print_exception |
| 1145 | from collections import namedtuple |
| 1146 | |
| 1147 | _ExceptHookArgs = namedtuple( |
| 1148 | 'ExceptHookArgs', |
| 1149 | 'exc_type exc_value exc_traceback thread') |
| 1150 | |
| 1151 | def ExceptHookArgs(args): |
| 1152 | return _ExceptHookArgs(*args) |
| 1153 | |
| 1154 | def excepthook(args, /): |
| 1155 | """ |
| 1156 | Handle uncaught Thread.run() exception. |
| 1157 | """ |
| 1158 | if args.exc_type == SystemExit: |
| 1159 | # silently ignore SystemExit |
| 1160 | return |
| 1161 | |
| 1162 | if _sys is not None and _sys.stderr is not None: |
| 1163 | stderr = _sys.stderr |
| 1164 | elif args.thread is not None: |
| 1165 | stderr = args.thread._stderr |
| 1166 | if stderr is None: |
| 1167 | # do nothing if sys.stderr is None and sys.stderr was None |
| 1168 | # when the thread was created |
| 1169 | return |
| 1170 | else: |
| 1171 | # do nothing if sys.stderr is None and args.thread is None |
| 1172 | return |
| 1173 | |
| 1174 | if args.thread is not None: |
| 1175 | name = args.thread.name |
| 1176 | else: |
| 1177 | name = get_ident() |
| 1178 | print(f"Exception in thread {name}:", |
| 1179 | file=stderr, flush=True) |
| 1180 | _print_exception(args.exc_type, args.exc_value, args.exc_traceback, |
| 1181 | file=stderr) |
| 1182 | stderr.flush() |
| 1183 | |
| 1184 | |
| 1185 | def _make_invoke_excepthook(): |
| 1186 | # Create a local namespace to ensure that variables remain alive |
| 1187 | # when _invoke_excepthook() is called, even if it is called late during |
| 1188 | # Python shutdown. It is mostly needed for daemon threads. |
| 1189 | |
| 1190 | old_excepthook = excepthook |
| 1191 | old_sys_excepthook = _sys.excepthook |
| 1192 | if old_excepthook is None: |
| 1193 | raise RuntimeError("threading.excepthook is None") |
| 1194 | if old_sys_excepthook is None: |
| 1195 | raise RuntimeError("sys.excepthook is None") |
| 1196 | |
| 1197 | sys_exc_info = _sys.exc_info |
| 1198 | local_print = print |
| 1199 | local_sys = _sys |
| 1200 | |
| 1201 | def invoke_excepthook(thread): |
| 1202 | global excepthook |
| 1203 | try: |
| 1204 | hook = excepthook |
| 1205 | if hook is None: |
| 1206 | hook = old_excepthook |
| 1207 | |
| 1208 | args = ExceptHookArgs([*sys_exc_info(), thread]) |
| 1209 | |
| 1210 | hook(args) |
| 1211 | except Exception as exc: |
| 1212 | exc.__suppress_context__ = True |
| 1213 | del exc |
| 1214 | |
| 1215 | if local_sys is not None and local_sys.stderr is not None: |
| 1216 | stderr = local_sys.stderr |
| 1217 | else: |
| 1218 | stderr = thread._stderr |
| 1219 | |
| 1220 | local_print("Exception in threading.excepthook:", |
| 1221 | file=stderr, flush=True) |
| 1222 | |
| 1223 | if local_sys is not None and local_sys.excepthook is not None: |
| 1224 | sys_excepthook = local_sys.excepthook |
| 1225 | else: |
| 1226 | sys_excepthook = old_sys_excepthook |
| 1227 | |
| 1228 | sys_excepthook(*sys_exc_info()) |
| 1229 | finally: |
| 1230 | # Break reference cycle (exception stored in a variable) |
| 1231 | args = None |
| 1232 | |
| 1233 | return invoke_excepthook |
| 1234 | |
| 1235 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1236 | # The timer class was contributed by Itamar Shtull-Trauring |
| 1237 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 1238 | class Timer(Thread): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1239 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1240 | |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1241 | t = Timer(30.0, f, args=None, kwargs=None) |
| 1242 | t.start() |
| 1243 | t.cancel() # stop the timer's action if it's still waiting |
| 1244 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1245 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1246 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 1247 | def __init__(self, interval, function, args=None, kwargs=None): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1248 | Thread.__init__(self) |
| 1249 | self.interval = interval |
| 1250 | self.function = function |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 1251 | self.args = args if args is not None else [] |
| 1252 | self.kwargs = kwargs if kwargs is not None else {} |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1253 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1254 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1255 | def cancel(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1256 | """Stop the timer if it hasn't finished yet.""" |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1257 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1258 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1259 | def run(self): |
| 1260 | self.finished.wait(self.interval) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1261 | if not self.finished.is_set(): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1262 | self.function(*self.args, **self.kwargs) |
| 1263 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1264 | |
Antoine Pitrou | 1023dbb | 2017-10-02 16:42:15 +0200 | [diff] [blame] | 1265 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1266 | # Special thread class to represent the main thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1267 | |
| 1268 | class _MainThread(Thread): |
| 1269 | |
| 1270 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 1271 | Thread.__init__(self, name="MainThread", daemon=False) |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1272 | self._set_tstate_lock() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 1273 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1274 | self._set_ident() |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 1275 | if _HAVE_THREAD_NATIVE_ID: |
| 1276 | self._set_native_id() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1277 | with _active_limbo_lock: |
| 1278 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1279 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1280 | |
| 1281 | # Dummy thread class to represent threads not started here. |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1282 | # These aren't garbage collected when they die, nor can they be waited for. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1283 | # If they invoke anything in threading.py that calls current_thread(), they |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1284 | # leave an entry in the _active dict forever after. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1285 | # Their purpose is to return *something* from current_thread(). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1286 | # They are marked as daemon threads so we won't wait for them |
| 1287 | # when we exit (conform previous semantics). |
| 1288 | |
| 1289 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 1290 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1291 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 1292 | Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1293 | |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 1294 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1295 | self._set_ident() |
Jake Tesler | b121f63 | 2019-05-22 08:43:17 -0700 | [diff] [blame] | 1296 | if _HAVE_THREAD_NATIVE_ID: |
| 1297 | self._set_native_id() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1298 | with _active_limbo_lock: |
| 1299 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1300 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 1301 | def _stop(self): |
| 1302 | pass |
| 1303 | |
Xiang Zhang | f3a9fab | 2017-02-27 11:01:30 +0800 | [diff] [blame] | 1304 | def is_alive(self): |
| 1305 | assert not self._is_stopped and self._started.is_set() |
| 1306 | return True |
| 1307 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 1308 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 1309 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1310 | |
| 1311 | |
| 1312 | # Global API functions |
| 1313 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1314 | def current_thread(): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1315 | """Return the current Thread object, corresponding to the caller's thread of control. |
| 1316 | |
| 1317 | If the caller's thread of control was not created through the threading |
| 1318 | module, a dummy thread object with limited functionality is returned. |
| 1319 | |
| 1320 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1321 | try: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 1322 | return _active[get_ident()] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1323 | except KeyError: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1324 | return _DummyThread() |
| 1325 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1326 | currentThread = current_thread |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1327 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1328 | def active_count(): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1329 | """Return the number of Thread objects currently alive. |
| 1330 | |
| 1331 | The returned count is equal to the length of the list returned by |
| 1332 | enumerate(). |
| 1333 | |
| 1334 | """ |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1335 | with _active_limbo_lock: |
| 1336 | return len(_active) + len(_limbo) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1337 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1338 | activeCount = active_count |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1339 | |
Antoine Pitrou | bdec11f | 2009-11-05 13:49:14 +0000 | [diff] [blame] | 1340 | def _enumerate(): |
| 1341 | # Same as enumerate(), but without the lock. Internal use only. |
| 1342 | return list(_active.values()) + list(_limbo.values()) |
| 1343 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1344 | def enumerate(): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1345 | """Return a list of all Thread objects currently alive. |
| 1346 | |
| 1347 | The list includes daemonic threads, dummy thread objects created by |
| 1348 | current_thread(), and the main thread. It excludes terminated threads and |
| 1349 | threads that have not yet been started. |
| 1350 | |
| 1351 | """ |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1352 | with _active_limbo_lock: |
| 1353 | return list(_active.values()) + list(_limbo.values()) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1354 | |
Kyle Stanley | b61b818 | 2020-03-27 15:31:22 -0400 | [diff] [blame] | 1355 | |
| 1356 | _threading_atexits = [] |
| 1357 | _SHUTTING_DOWN = False |
| 1358 | |
| 1359 | def _register_atexit(func, *arg, **kwargs): |
| 1360 | """CPython internal: register *func* to be called before joining threads. |
| 1361 | |
| 1362 | The registered *func* is called with its arguments just before all |
| 1363 | non-daemon threads are joined in `_shutdown()`. It provides a similar |
| 1364 | purpose to `atexit.register()`, but its functions are called prior to |
| 1365 | threading shutdown instead of interpreter shutdown. |
| 1366 | |
| 1367 | For similarity to atexit, the registered functions are called in reverse. |
| 1368 | """ |
| 1369 | if _SHUTTING_DOWN: |
| 1370 | raise RuntimeError("can't register atexit after shutdown") |
| 1371 | |
| 1372 | call = functools.partial(func, *arg, **kwargs) |
| 1373 | _threading_atexits.append(call) |
| 1374 | |
| 1375 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 1376 | from _thread import stack_size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1377 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1378 | # Create the main thread object, |
| 1379 | # and make it available for the interpreter |
| 1380 | # (Py_Main) as threading._shutdown. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1381 | |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1382 | _main_thread = _MainThread() |
| 1383 | |
| 1384 | def _shutdown(): |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 1385 | """ |
| 1386 | Wait until the Python thread state of all non-daemon threads get deleted. |
| 1387 | """ |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1388 | # Obscure: other threads may be waiting to join _main_thread. That's |
| 1389 | # dubious, but some code does it. We can't wait for C code to release |
| 1390 | # the main thread's tstate_lock - that won't happen until the interpreter |
| 1391 | # is nearly dead. So we release it here. Note that just calling _stop() |
| 1392 | # isn't enough: other threads may already be waiting on _tstate_lock. |
Antoine Pitrou | ee84a60 | 2017-08-16 20:53:28 +0200 | [diff] [blame] | 1393 | if _main_thread._is_stopped: |
| 1394 | # _shutdown() was already called |
| 1395 | return |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 1396 | |
Kyle Stanley | b61b818 | 2020-03-27 15:31:22 -0400 | [diff] [blame] | 1397 | global _SHUTTING_DOWN |
| 1398 | _SHUTTING_DOWN = True |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 1399 | # Main thread |
Tim Peters | b5e9ac9 | 2013-09-09 14:41:50 -0500 | [diff] [blame] | 1400 | tlock = _main_thread._tstate_lock |
| 1401 | # The main thread isn't finished yet, so its thread state lock can't have |
| 1402 | # been released. |
| 1403 | assert tlock is not None |
| 1404 | assert tlock.locked() |
| 1405 | tlock.release() |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1406 | _main_thread._stop() |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1407 | |
Kyle Stanley | b61b818 | 2020-03-27 15:31:22 -0400 | [diff] [blame] | 1408 | # Call registered threading atexit functions before threads are joined. |
| 1409 | # Order is reversed, similar to atexit. |
| 1410 | for atexit_call in reversed(_threading_atexits): |
| 1411 | atexit_call() |
| 1412 | |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 1413 | # Join all non-deamon threads |
| 1414 | while True: |
| 1415 | with _shutdown_locks_lock: |
| 1416 | locks = list(_shutdown_locks) |
| 1417 | _shutdown_locks.clear() |
| 1418 | |
| 1419 | if not locks: |
| 1420 | break |
| 1421 | |
| 1422 | for lock in locks: |
| 1423 | # mimick Thread.join() |
| 1424 | lock.acquire() |
| 1425 | lock.release() |
| 1426 | |
| 1427 | # new threads can be spawned while we were waiting for the other |
| 1428 | # threads to complete |
| 1429 | |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1430 | |
| 1431 | def main_thread(): |
Andrew Svetlov | b1dd557 | 2013-09-04 10:33:11 +0300 | [diff] [blame] | 1432 | """Return the main thread object. |
| 1433 | |
| 1434 | In normal conditions, the main thread is the thread from which the |
| 1435 | Python interpreter was started. |
| 1436 | """ |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1437 | return _main_thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1438 | |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 1439 | # get thread-local implementation, either from the thread |
| 1440 | # module, or from the python fallback |
| 1441 | |
| 1442 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 1443 | from _thread import _local as local |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 1444 | except ImportError: |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 1445 | from _threading_local import local |
| 1446 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1447 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1448 | def _after_fork(): |
Antoine Pitrou | 4a8bcdf | 2017-05-28 14:02:26 +0200 | [diff] [blame] | 1449 | """ |
| 1450 | Cleanup threading module state that should not exist after a fork. |
| 1451 | """ |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1452 | # Reset _active_limbo_lock, in case we forked while the lock was held |
| 1453 | # by another (non-forked) thread. http://bugs.python.org/issue874900 |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1454 | global _active_limbo_lock, _main_thread |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 1455 | global _shutdown_locks_lock, _shutdown_locks |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1456 | _active_limbo_lock = _allocate_lock() |
| 1457 | |
| 1458 | # fork() only copied the current thread; clear references to others. |
| 1459 | new_active = {} |
Victor Stinner | d8ff44c | 2020-03-27 17:50:42 +0100 | [diff] [blame] | 1460 | |
| 1461 | try: |
| 1462 | current = _active[get_ident()] |
| 1463 | except KeyError: |
| 1464 | # fork() was called in a thread which was not spawned |
| 1465 | # by threading.Thread. For example, a thread spawned |
| 1466 | # by thread.start_new_thread(). |
| 1467 | current = _MainThread() |
| 1468 | |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1469 | _main_thread = current |
Victor Stinner | 468e5fe | 2019-06-13 01:30:17 +0200 | [diff] [blame] | 1470 | |
| 1471 | # reset _shutdown() locks: threads re-register their _tstate_lock below |
| 1472 | _shutdown_locks_lock = _allocate_lock() |
| 1473 | _shutdown_locks = set() |
| 1474 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1475 | with _active_limbo_lock: |
Antoine Pitrou | 5da7e79 | 2013-09-08 13:19:06 +0200 | [diff] [blame] | 1476 | # Dangling thread instances must still have their locks reset, |
| 1477 | # because someone may join() them. |
| 1478 | threads = set(_enumerate()) |
| 1479 | threads.update(_dangling) |
| 1480 | for thread in threads: |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 1481 | # Any lock/condition variable may be currently locked or in an |
| 1482 | # invalid state, so we reinitialize them. |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1483 | if thread is current: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 1484 | # There is only one active thread. We reset the ident to |
| 1485 | # its new value since it can have changed. |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1486 | thread._reset_internal_locks(True) |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 1487 | ident = get_ident() |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 1488 | thread._ident = ident |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1489 | new_active[ident] = thread |
| 1490 | else: |
| 1491 | # All the others are already stopped. |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1492 | thread._reset_internal_locks(False) |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 1493 | thread._stop() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1494 | |
| 1495 | _limbo.clear() |
| 1496 | _active.clear() |
| 1497 | _active.update(new_active) |
| 1498 | assert len(_active) == 1 |
Antoine Pitrou | 4a8bcdf | 2017-05-28 14:02:26 +0200 | [diff] [blame] | 1499 | |
| 1500 | |
Gregory P. Smith | 163468a | 2017-05-29 10:03:41 -0700 | [diff] [blame] | 1501 | if hasattr(_os, "register_at_fork"): |
| 1502 | _os.register_at_fork(after_in_child=_after_fork) |