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