blob: cec9cdb8e6985fc505e1900131cb28e02ed35399 [file] [log] [blame]
Jeremy Hylton92bb6e72002-08-14 19:25:42 +00001"""Thread module emulating a subset of Java's threading model."""
Guido van Rossum7f5013a1998-04-09 22:01:42 +00002
Antoine Pitrou4a8bcdf2017-05-28 14:02:26 +02003import os as _os
Fred Drakea8725952002-12-30 23:32:50 +00004import sys as _sys
Georg Brandl2067bfd2008-05-25 13:05:15 +00005import _thread
Fred Drakea8725952002-12-30 23:32:50 +00006
Victor Stinnerae586492014-09-02 23:18:25 +02007from time import monotonic as _time
Antoine Pitrouc081c0c2011-07-15 22:12:24 +02008from _weakrefset import WeakSet
R David Murrayb186f1df2014-10-04 17:43:54 -04009from itertools import islice as _islice, count as _count
Raymond Hettingerec4b1742013-03-10 17:57:28 -070010try:
Raymond Hettingerec4b1742013-03-10 17:57:28 -070011 from _collections import deque as _deque
Brett Cannoncd171c82013-07-04 17:43:24 -040012except ImportError:
Raymond Hettingerec4b1742013-03-10 17:57:28 -070013 from collections import deque as _deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000014
Benjamin Petersonb3085c92008-09-01 23:09:31 +000015# Note regarding PEP 8 compliant names
16# This threading model was originally inspired by Java, and inherited
17# the convention of camelCase function and method names from that
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030018# language. Those original names are not in any imminent danger of
Benjamin Petersonb3085c92008-09-01 23:09:31 +000019# being deprecated (even for Py3k),so this module provides them as an
20# alias for the PEP 8 compliant names
21# Note that using the new PEP 8 compliant names facilitates substitution
22# with the multiprocessing module, which doesn't provide the old
23# Java inspired names.
24
Victor Stinnerd12e7572019-05-21 12:44:57 +020025__all__ = ['get_ident', 'active_count', 'Condition', 'current_thread',
26 'enumerate', 'main_thread', 'TIMEOUT_MAX',
Martin Panter19e69c52015-11-14 12:46:42 +000027 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
28 'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError',
Victor Stinnercd590a72019-05-28 00:39:52 +020029 'setprofile', 'settrace', 'local', 'stack_size',
30 'excepthook', 'ExceptHookArgs']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000031
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000032# Rename some stuff so "from threading import *" is safe
Georg Brandl2067bfd2008-05-25 13:05:15 +000033_start_new_thread = _thread.start_new_thread
34_allocate_lock = _thread.allocate_lock
Antoine Pitrou7b476992013-09-07 23:38:37 +020035_set_sentinel = _thread._set_sentinel
Victor Stinner2a129742011-05-30 23:02:52 +020036get_ident = _thread.get_ident
Victor Stinner066e5b12019-06-14 18:55:22 +020037_is_main_interpreter = _thread._is_main_interpreter
Jake Teslerb121f632019-05-22 08:43:17 -070038try:
39 get_native_id = _thread.get_native_id
40 _HAVE_THREAD_NATIVE_ID = True
41 __all__.append('get_native_id')
42except AttributeError:
43 _HAVE_THREAD_NATIVE_ID = False
Georg Brandl2067bfd2008-05-25 13:05:15 +000044ThreadError = _thread.error
Antoine Pitrou434736a2009-11-10 18:46:01 +000045try:
46 _CRLock = _thread.RLock
47except AttributeError:
48 _CRLock = None
Antoine Pitrou7c3e5772010-04-14 15:44:10 +000049TIMEOUT_MAX = _thread.TIMEOUT_MAX
Georg Brandl2067bfd2008-05-25 13:05:15 +000050del _thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +000051
Guido van Rossum7f5013a1998-04-09 22:01:42 +000052
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000053# Support for profile and trace hooks
54
55_profile_hook = None
56_trace_hook = None
57
58def setprofile(func):
Georg Brandlc30b59f2013-10-13 10:43:59 +020059 """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 Hyltonbfccb352003-06-29 16:58:41 +000065 global _profile_hook
66 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000067
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000068def settrace(func):
Georg Brandlc30b59f2013-10-13 10:43:59 +020069 """Set a trace function for all threads started from the threading module.
70
71 The func will be passed to sys.settrace() for each thread, before its run()
72 method is called.
73
74 """
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000075 global _trace_hook
76 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000077
78# Synchronization classes
79
80Lock = _allocate_lock
81
Victor Stinner135b6d82012-03-03 01:32:57 +010082def RLock(*args, **kwargs):
Georg Brandlc30b59f2013-10-13 10:43:59 +020083 """Factory function that returns a new reentrant lock.
84
85 A reentrant lock must be released by the thread that acquired it. Once a
86 thread has acquired a reentrant lock, the same thread may acquire it again
87 without blocking; the thread must release it once for each time it has
88 acquired it.
89
90 """
Victor Stinner135b6d82012-03-03 01:32:57 +010091 if _CRLock is None:
92 return _PyRLock(*args, **kwargs)
Antoine Pitrou434736a2009-11-10 18:46:01 +000093 return _CRLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000094
Victor Stinner135b6d82012-03-03 01:32:57 +010095class _RLock:
Georg Brandlc30b59f2013-10-13 10:43:59 +020096 """This class implements reentrant lock objects.
97
98 A reentrant lock must be released by the thread that acquired it. Once a
99 thread has acquired a reentrant lock, the same thread may acquire it
100 again without blocking; the thread must release it once for each time it
101 has acquired it.
102
103 """
Tim Petersb90f89a2001-01-15 03:26:36 +0000104
Victor Stinner135b6d82012-03-03 01:32:57 +0100105 def __init__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000106 self._block = _allocate_lock()
107 self._owner = None
108 self._count = 0
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000109
110 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000111 owner = self._owner
Antoine Pitroub0872682009-11-09 16:08:16 +0000112 try:
113 owner = _active[owner].name
114 except KeyError:
115 pass
Raymond Hettinger62f4dad2014-05-25 18:22:35 -0700116 return "<%s %s.%s object owner=%r count=%d at %s>" % (
117 "locked" if self._block.locked() else "unlocked",
118 self.__class__.__module__,
119 self.__class__.__qualname__,
120 owner,
121 self._count,
122 hex(id(self))
123 )
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000124
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000125 def acquire(self, blocking=True, timeout=-1):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200126 """Acquire a lock, blocking or non-blocking.
127
128 When invoked without arguments: if this thread already owns the lock,
129 increment the recursion level by one, and return immediately. Otherwise,
130 if another thread owns the lock, block until the lock is unlocked. Once
131 the lock is unlocked (not owned by any thread), then grab ownership, set
132 the recursion level to one, and return. If more than one thread is
133 blocked waiting until the lock is unlocked, only one at a time will be
134 able to grab ownership of the lock. There is no return value in this
135 case.
136
137 When invoked with the blocking argument set to true, do the same thing
138 as when called without arguments, and return true.
139
140 When invoked with the blocking argument set to false, do not block. If a
141 call without an argument would block, return false immediately;
142 otherwise, do the same thing as when called without arguments, and
143 return true.
144
145 When invoked with the floating-point timeout argument set to a positive
146 value, block for at most the number of seconds specified by timeout
147 and as long as the lock cannot be acquired. Return true if the lock has
148 been acquired, false if the timeout has elapsed.
149
150 """
Victor Stinner2a129742011-05-30 23:02:52 +0200151 me = get_ident()
Antoine Pitroub0872682009-11-09 16:08:16 +0000152 if self._owner == me:
Raymond Hettinger720da572013-03-10 15:13:35 -0700153 self._count += 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000154 return 1
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000155 rc = self._block.acquire(blocking, timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000156 if rc:
Guido van Rossumd0648992007-08-20 19:25:41 +0000157 self._owner = me
158 self._count = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000159 return rc
160
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000161 __enter__ = acquire
162
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000163 def release(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200164 """Release a lock, decrementing the recursion level.
165
166 If after the decrement it is zero, reset the lock to unlocked (not owned
167 by any thread), and if any other threads are blocked waiting for the
168 lock to become unlocked, allow exactly one of them to proceed. If after
169 the decrement the recursion level is still nonzero, the lock remains
170 locked and owned by the calling thread.
171
172 Only call this method when the calling thread owns the lock. A
173 RuntimeError is raised if this method is called when the lock is
174 unlocked.
175
176 There is no return value.
177
178 """
Victor Stinner2a129742011-05-30 23:02:52 +0200179 if self._owner != get_ident():
Georg Brandl495f7b52009-10-27 15:28:25 +0000180 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000181 self._count = count = self._count - 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000182 if not count:
Guido van Rossumd0648992007-08-20 19:25:41 +0000183 self._owner = None
184 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000185
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000186 def __exit__(self, t, v, tb):
187 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000188
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000189 # Internal methods used by condition variables
190
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000191 def _acquire_restore(self, state):
Guido van Rossumd0648992007-08-20 19:25:41 +0000192 self._block.acquire()
193 self._count, self._owner = state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000194
195 def _release_save(self):
Victor Stinnerc2824d42011-04-24 23:41:33 +0200196 if self._count == 0:
197 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000198 count = self._count
199 self._count = 0
200 owner = self._owner
201 self._owner = None
202 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000203 return (count, owner)
204
205 def _is_owned(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200206 return self._owner == get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000207
Antoine Pitrou434736a2009-11-10 18:46:01 +0000208_PyRLock = _RLock
209
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000210
Victor Stinner135b6d82012-03-03 01:32:57 +0100211class Condition:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200212 """Class that implements a condition variable.
213
214 A condition variable allows one or more threads to wait until they are
215 notified by another thread.
216
217 If the lock argument is given and not None, it must be a Lock or RLock
218 object, and it is used as the underlying lock. Otherwise, a new RLock object
219 is created and used as the underlying lock.
220
221 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000222
Victor Stinner135b6d82012-03-03 01:32:57 +0100223 def __init__(self, lock=None):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000224 if lock is None:
225 lock = RLock()
Guido van Rossumd0648992007-08-20 19:25:41 +0000226 self._lock = lock
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000227 # Export the lock's acquire() and release() methods
228 self.acquire = lock.acquire
229 self.release = lock.release
230 # If the lock defines _release_save() and/or _acquire_restore(),
231 # these override the default implementations (which just call
232 # release() and acquire() on the lock). Ditto for _is_owned().
233 try:
234 self._release_save = lock._release_save
235 except AttributeError:
236 pass
237 try:
238 self._acquire_restore = lock._acquire_restore
239 except AttributeError:
240 pass
241 try:
242 self._is_owned = lock._is_owned
243 except AttributeError:
244 pass
Raymond Hettingerec4b1742013-03-10 17:57:28 -0700245 self._waiters = _deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000246
Thomas Wouters477c8d52006-05-27 19:21:47 +0000247 def __enter__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000248 return self._lock.__enter__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000249
Thomas Wouters477c8d52006-05-27 19:21:47 +0000250 def __exit__(self, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +0000251 return self._lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000252
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000253 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000254 return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000255
256 def _release_save(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000257 self._lock.release() # No state to save
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000258
259 def _acquire_restore(self, x):
Guido van Rossumd0648992007-08-20 19:25:41 +0000260 self._lock.acquire() # Ignore saved state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000261
262 def _is_owned(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000263 # Return True if lock is owned by current_thread.
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300264 # This method is called only if _lock doesn't have _is_owned().
Guido van Rossumd0648992007-08-20 19:25:41 +0000265 if self._lock.acquire(0):
266 self._lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000267 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000268 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000269 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000270
271 def wait(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200272 """Wait until notified or until a timeout occurs.
273
274 If the calling thread has not acquired the lock when this method is
275 called, a RuntimeError is raised.
276
277 This method releases the underlying lock, and then blocks until it is
278 awakened by a notify() or notify_all() call for the same condition
279 variable in another thread, or until the optional timeout occurs. Once
280 awakened or timed out, it re-acquires the lock and returns.
281
282 When the timeout argument is present and not None, it should be a
283 floating point number specifying a timeout for the operation in seconds
284 (or fractions thereof).
285
286 When the underlying lock is an RLock, it is not released using its
287 release() method, since this may not actually unlock the lock when it
288 was acquired multiple times recursively. Instead, an internal interface
289 of the RLock class is used, which really unlocks it even when it has
290 been recursively acquired several times. Another internal interface is
291 then used to restore the recursion level when the lock is reacquired.
292
293 """
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000294 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000295 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000296 waiter = _allocate_lock()
297 waiter.acquire()
Guido van Rossumd0648992007-08-20 19:25:41 +0000298 self._waiters.append(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000299 saved_state = self._release_save()
Antoine Pitroua64b92e2014-08-29 23:26:36 +0200300 gotit = False
Tim Petersc951bf92001-04-02 20:15:57 +0000301 try: # restore state no matter what (e.g., KeyboardInterrupt)
302 if timeout is None:
303 waiter.acquire()
Georg Brandlb9a43912010-10-28 09:03:20 +0000304 gotit = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000305 else:
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000306 if timeout > 0:
307 gotit = waiter.acquire(True, timeout)
308 else:
309 gotit = waiter.acquire(False)
Georg Brandlb9a43912010-10-28 09:03:20 +0000310 return gotit
Tim Petersc951bf92001-04-02 20:15:57 +0000311 finally:
312 self._acquire_restore(saved_state)
Antoine Pitroua64b92e2014-08-29 23:26:36 +0200313 if not gotit:
314 try:
315 self._waiters.remove(waiter)
316 except ValueError:
317 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000318
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000319 def wait_for(self, predicate, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200320 """Wait until a condition evaluates to True.
321
322 predicate should be a callable which result will be interpreted as a
323 boolean value. A timeout may be provided giving the maximum time to
324 wait.
325
326 """
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000327 endtime = None
328 waittime = timeout
329 result = predicate()
330 while not result:
331 if waittime is not None:
332 if endtime is None:
333 endtime = _time() + waittime
334 else:
335 waittime = endtime - _time()
336 if waittime <= 0:
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000337 break
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000338 self.wait(waittime)
339 result = predicate()
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000340 return result
341
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000342 def notify(self, n=1):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200343 """Wake up one or more threads waiting on this condition, if any.
344
345 If the calling thread has not acquired the lock when this method is
346 called, a RuntimeError is raised.
347
348 This method wakes up at most n of the threads waiting for the condition
349 variable; it is a no-op if no threads are waiting.
350
351 """
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000352 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000353 raise RuntimeError("cannot notify on un-acquired lock")
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700354 all_waiters = self._waiters
355 waiters_to_notify = _deque(_islice(all_waiters, n))
356 if not waiters_to_notify:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000357 return
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700358 for waiter in waiters_to_notify:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000359 waiter.release()
360 try:
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700361 all_waiters.remove(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000362 except ValueError:
363 pass
364
Benjamin Peterson672b8032008-06-11 19:14:14 +0000365 def notify_all(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200366 """Wake up all threads waiting on this condition.
367
368 If the calling thread has not acquired the lock when this method
369 is called, a RuntimeError is raised.
370
371 """
Guido van Rossumd0648992007-08-20 19:25:41 +0000372 self.notify(len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000373
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000374 notifyAll = notify_all
375
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000376
Victor Stinner135b6d82012-03-03 01:32:57 +0100377class Semaphore:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200378 """This class implements semaphore objects.
379
380 Semaphores manage a counter representing the number of release() calls minus
381 the number of acquire() calls, plus an initial value. The acquire() method
382 blocks if necessary until it can return without making the counter
383 negative. If not given, value defaults to 1.
384
385 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000386
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000387 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000388
Victor Stinner135b6d82012-03-03 01:32:57 +0100389 def __init__(self, value=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000390 if value < 0:
391 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossumd0648992007-08-20 19:25:41 +0000392 self._cond = Condition(Lock())
393 self._value = value
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000394
Antoine Pitrou0454af92010-04-17 23:51:58 +0000395 def acquire(self, blocking=True, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200396 """Acquire a semaphore, decrementing the internal counter by one.
397
398 When invoked without arguments: if the internal counter is larger than
399 zero on entry, decrement it by one and return immediately. If it is zero
400 on entry, block, waiting until some other thread has called release() to
401 make it larger than zero. This is done with proper interlocking so that
402 if multiple acquire() calls are blocked, release() will wake exactly one
403 of them up. The implementation may pick one at random, so the order in
404 which blocked threads are awakened should not be relied on. There is no
405 return value in this case.
406
407 When invoked with blocking set to true, do the same thing as when called
408 without arguments, and return true.
409
410 When invoked with blocking set to false, do not block. If a call without
411 an argument would block, return false immediately; otherwise, do the
412 same thing as when called without arguments, and return true.
413
414 When invoked with a timeout other than None, it will block for at
415 most timeout seconds. If acquire does not complete successfully in
416 that interval, return false. Return true otherwise.
417
418 """
Antoine Pitrou0454af92010-04-17 23:51:58 +0000419 if not blocking and timeout is not None:
420 raise ValueError("can't specify timeout for non-blocking acquire")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000421 rc = False
Antoine Pitrou0454af92010-04-17 23:51:58 +0000422 endtime = None
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300423 with self._cond:
424 while self._value == 0:
425 if not blocking:
426 break
427 if timeout is not None:
428 if endtime is None:
429 endtime = _time() + timeout
430 else:
431 timeout = endtime - _time()
432 if timeout <= 0:
433 break
434 self._cond.wait(timeout)
435 else:
Serhiy Storchakab00b5962013-04-22 22:54:16 +0300436 self._value -= 1
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300437 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000438 return rc
439
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000440 __enter__ = acquire
441
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000442 def release(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200443 """Release a semaphore, incrementing the internal counter by one.
444
445 When the counter is zero on entry and another thread is waiting for it
446 to become larger than zero again, wake up that thread.
447
448 """
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300449 with self._cond:
Serhiy Storchakab00b5962013-04-22 22:54:16 +0300450 self._value += 1
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300451 self._cond.notify()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000452
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000453 def __exit__(self, t, v, tb):
454 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000455
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000456
Éric Araujo0cdd4452011-07-28 00:28:28 +0200457class BoundedSemaphore(Semaphore):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200458 """Implements a bounded semaphore.
459
460 A bounded semaphore checks to make sure its current value doesn't exceed its
461 initial value. If it does, ValueError is raised. In most situations
462 semaphores are used to guard resources with limited capacity.
463
464 If the semaphore is released too many times it's a sign of a bug. If not
465 given, value defaults to 1.
466
467 Like regular semaphores, bounded semaphores manage a counter representing
468 the number of release() calls minus the number of acquire() calls, plus an
469 initial value. The acquire() method blocks if necessary until it can return
470 without making the counter negative. If not given, value defaults to 1.
471
472 """
473
Victor Stinner135b6d82012-03-03 01:32:57 +0100474 def __init__(self, value=1):
475 Semaphore.__init__(self, value)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000476 self._initial_value = value
477
478 def release(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200479 """Release a semaphore, incrementing the internal counter by one.
480
481 When the counter is zero on entry and another thread is waiting for it
482 to become larger than zero again, wake up that thread.
483
484 If the number of releases exceeds the number of acquires,
485 raise a ValueError.
486
487 """
Tim Peters7634e1c2013-10-08 20:55:51 -0500488 with self._cond:
489 if self._value >= self._initial_value:
490 raise ValueError("Semaphore released too many times")
491 self._value += 1
492 self._cond.notify()
Skip Montanaroe428bb72001-08-20 20:27:58 +0000493
494
Victor Stinner135b6d82012-03-03 01:32:57 +0100495class Event:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200496 """Class implementing event objects.
497
498 Events manage a flag that can be set to true with the set() method and reset
499 to false with the clear() method. The wait() method blocks until the flag is
500 true. The flag is initially false.
501
502 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000503
504 # After Tim Peters' event class (without is_posted())
505
Victor Stinner135b6d82012-03-03 01:32:57 +0100506 def __init__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000507 self._cond = Condition(Lock())
508 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000509
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000510 def _reset_internal_locks(self):
511 # private! called by Thread._reset_internal_locks by _after_fork()
Benjamin Peterson15982aa2015-10-05 21:56:22 -0700512 self._cond.__init__(Lock())
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000513
Benjamin Peterson672b8032008-06-11 19:14:14 +0000514 def is_set(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200515 """Return true if and only if the internal flag is true."""
Guido van Rossumd0648992007-08-20 19:25:41 +0000516 return self._flag
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000517
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000518 isSet = is_set
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000519
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000520 def set(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200521 """Set the internal flag to true.
522
523 All threads waiting for it to become true are awakened. Threads
524 that call wait() once the flag is true will not block at all.
525
526 """
Benjamin Peterson414918a2015-10-10 19:34:46 -0700527 with self._cond:
Guido van Rossumd0648992007-08-20 19:25:41 +0000528 self._flag = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000529 self._cond.notify_all()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000530
531 def clear(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200532 """Reset the internal flag to false.
533
534 Subsequently, threads calling wait() will block until set() is called to
535 set the internal flag to true again.
536
537 """
Benjamin Peterson414918a2015-10-10 19:34:46 -0700538 with self._cond:
Guido van Rossumd0648992007-08-20 19:25:41 +0000539 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000540
541 def wait(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200542 """Block until the internal flag is true.
543
544 If the internal flag is true on entry, return immediately. Otherwise,
545 block until another thread calls set() to set the flag to true, or until
546 the optional timeout occurs.
547
548 When the timeout argument is present and not None, it should be a
549 floating point number specifying a timeout for the operation in seconds
550 (or fractions thereof).
551
552 This method returns the internal flag on exit, so it will always return
553 True except if a timeout is given and the operation times out.
554
555 """
Benjamin Peterson414918a2015-10-10 19:34:46 -0700556 with self._cond:
Charles-François Natalided03482012-01-07 18:24:56 +0100557 signaled = self._flag
558 if not signaled:
559 signaled = self._cond.wait(timeout)
560 return signaled
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000561
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000562
563# A barrier class. Inspired in part by the pthread_barrier_* api and
564# the CyclicBarrier class from Java. See
565# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
566# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
567# CyclicBarrier.html
568# for information.
569# We maintain two main states, 'filling' and 'draining' enabling the barrier
570# to be cyclic. Threads are not allowed into it until it has fully drained
571# since the previous cycle. In addition, a 'resetting' state exists which is
572# similar to 'draining' except that threads leave with a BrokenBarrierError,
Ezio Melottie130a522011-10-19 10:58:56 +0300573# and a 'broken' state in which all threads get the exception.
Victor Stinner135b6d82012-03-03 01:32:57 +0100574class Barrier:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200575 """Implements a Barrier.
576
577 Useful for synchronizing a fixed number of threads at known synchronization
Carl Bordum Hansen62fa51f2019-03-09 18:38:05 +0100578 points. Threads block on 'wait()' and are simultaneously awoken once they
579 have all made that call.
Georg Brandlc30b59f2013-10-13 10:43:59 +0200580
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000581 """
Georg Brandlc30b59f2013-10-13 10:43:59 +0200582
Victor Stinner135b6d82012-03-03 01:32:57 +0100583 def __init__(self, parties, action=None, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200584 """Create a barrier, initialised to 'parties' threads.
585
586 'action' is a callable which, when supplied, will be called by one of
587 the threads after they have all entered the barrier and just prior to
Carl Bordum Hansen62fa51f2019-03-09 18:38:05 +0100588 releasing them all. If a 'timeout' is provided, it is used as the
Georg Brandlc30b59f2013-10-13 10:43:59 +0200589 default for all subsequent 'wait()' calls.
590
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000591 """
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000592 self._cond = Condition(Lock())
593 self._action = action
594 self._timeout = timeout
595 self._parties = parties
596 self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
597 self._count = 0
598
599 def wait(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200600 """Wait for the barrier.
601
602 When the specified number of threads have started waiting, they are all
603 simultaneously awoken. If an 'action' was provided for the barrier, one
604 of the threads will have executed that callback prior to returning.
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000605 Returns an individual index number from 0 to 'parties-1'.
Georg Brandlc30b59f2013-10-13 10:43:59 +0200606
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000607 """
608 if timeout is None:
609 timeout = self._timeout
610 with self._cond:
611 self._enter() # Block while the barrier drains.
612 index = self._count
613 self._count += 1
614 try:
615 if index + 1 == self._parties:
616 # We release the barrier
617 self._release()
618 else:
619 # We wait until someone releases us
620 self._wait(timeout)
621 return index
622 finally:
623 self._count -= 1
624 # Wake up any threads waiting for barrier to drain.
625 self._exit()
626
627 # Block until the barrier is ready for us, or raise an exception
628 # if it is broken.
629 def _enter(self):
630 while self._state in (-1, 1):
631 # It is draining or resetting, wait until done
632 self._cond.wait()
633 #see if the barrier is in a broken state
634 if self._state < 0:
635 raise BrokenBarrierError
636 assert self._state == 0
637
638 # Optionally run the 'action' and release the threads waiting
639 # in the barrier.
640 def _release(self):
641 try:
642 if self._action:
643 self._action()
644 # enter draining state
645 self._state = 1
646 self._cond.notify_all()
647 except:
648 #an exception during the _action handler. Break and reraise
649 self._break()
650 raise
651
Martin Panter69332c12016-08-04 13:07:31 +0000652 # Wait in the barrier until we are released. Raise an exception
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000653 # if the barrier is reset or broken.
654 def _wait(self, timeout):
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000655 if not self._cond.wait_for(lambda : self._state != 0, timeout):
656 #timed out. Break the barrier
657 self._break()
658 raise BrokenBarrierError
659 if self._state < 0:
660 raise BrokenBarrierError
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000661 assert self._state == 1
662
663 # If we are the last thread to exit the barrier, signal any threads
664 # waiting for the barrier to drain.
665 def _exit(self):
666 if self._count == 0:
667 if self._state in (-1, 1):
668 #resetting or draining
669 self._state = 0
670 self._cond.notify_all()
671
672 def reset(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200673 """Reset the barrier to the initial state.
674
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000675 Any threads currently waiting will get the BrokenBarrier exception
676 raised.
Georg Brandlc30b59f2013-10-13 10:43:59 +0200677
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000678 """
679 with self._cond:
680 if self._count > 0:
681 if self._state == 0:
682 #reset the barrier, waking up threads
683 self._state = -1
684 elif self._state == -2:
685 #was broken, set it to reset state
686 #which clears when the last thread exits
687 self._state = -1
688 else:
689 self._state = 0
690 self._cond.notify_all()
691
692 def abort(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200693 """Place the barrier into a 'broken' state.
694
695 Useful in case of error. Any currently waiting threads and threads
696 attempting to 'wait()' will have BrokenBarrierError raised.
697
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000698 """
699 with self._cond:
700 self._break()
701
702 def _break(self):
703 # An internal error was detected. The barrier is set to
704 # a broken state all parties awakened.
705 self._state = -2
706 self._cond.notify_all()
707
708 @property
709 def parties(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200710 """Return the number of threads required to trip the barrier."""
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000711 return self._parties
712
713 @property
714 def n_waiting(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200715 """Return the number of threads currently waiting at the barrier."""
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000716 # We don't need synchronization here since this is an ephemeral result
717 # anyway. It returns the correct value in the steady state.
718 if self._state == 0:
719 return self._count
720 return 0
721
722 @property
723 def broken(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200724 """Return True if the barrier is in a broken state."""
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000725 return self._state == -2
726
Georg Brandlc30b59f2013-10-13 10:43:59 +0200727# exception raised by the Barrier class
728class BrokenBarrierError(RuntimeError):
729 pass
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000730
731
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000732# Helper to generate new thread names
R David Murrayb186f1df2014-10-04 17:43:54 -0400733_counter = _count().__next__
734_counter() # Consume 0 so first non-main thread has id 1.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000735def _newname(template="Thread-%d"):
R David Murrayb186f1df2014-10-04 17:43:54 -0400736 return template % _counter()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000737
738# Active thread administration
739_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000740_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000741_limbo = {}
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200742_dangling = WeakSet()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200743# Set of Thread._tstate_lock locks of non-daemon threads used by _shutdown()
744# to wait until all Python thread states get deleted:
745# see Thread._set_tstate_lock().
746_shutdown_locks_lock = _allocate_lock()
747_shutdown_locks = set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000748
749# Main class for threads
750
Victor Stinner135b6d82012-03-03 01:32:57 +0100751class Thread:
Georg Brandlc30b59f2013-10-13 10:43:59 +0200752 """A class that represents a thread of control.
753
754 This class can be safely subclassed in a limited fashion. There are two ways
755 to specify the activity: by passing a callable object to the constructor, or
756 by overriding the run() method in a subclass.
757
758 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000759
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300760 _initialized = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000761
762 def __init__(self, group=None, target=None, name=None,
Victor Stinner135b6d82012-03-03 01:32:57 +0100763 args=(), kwargs=None, *, daemon=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200764 """This constructor should always be called with keyword arguments. Arguments are:
765
766 *group* should be None; reserved for future extension when a ThreadGroup
767 class is implemented.
768
769 *target* is the callable object to be invoked by the run()
770 method. Defaults to None, meaning nothing is called.
771
772 *name* is the thread name. By default, a unique name is constructed of
773 the form "Thread-N" where N is a small decimal number.
774
775 *args* is the argument tuple for the target invocation. Defaults to ().
776
777 *kwargs* is a dictionary of keyword arguments for the target
778 invocation. Defaults to {}.
779
780 If a subclass overrides the constructor, it must make sure to invoke
781 the base class constructor (Thread.__init__()) before doing anything
782 else to the thread.
783
784 """
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000785 assert group is None, "group argument must be None for now"
Georg Brandla4a8b822005-07-15 09:13:21 +0000786 if kwargs is None:
787 kwargs = {}
Guido van Rossumd0648992007-08-20 19:25:41 +0000788 self._target = target
789 self._name = str(name or _newname())
790 self._args = args
791 self._kwargs = kwargs
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000792 if daemon is not None:
793 self._daemonic = daemon
794 else:
795 self._daemonic = current_thread().daemon
Georg Brandl0c77a822008-06-10 16:37:50 +0000796 self._ident = None
Jake Teslerb121f632019-05-22 08:43:17 -0700797 if _HAVE_THREAD_NATIVE_ID:
798 self._native_id = None
Antoine Pitrou7b476992013-09-07 23:38:37 +0200799 self._tstate_lock = None
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000800 self._started = Event()
Tim Petersc363a232013-09-08 18:44:40 -0500801 self._is_stopped = False
Guido van Rossumd0648992007-08-20 19:25:41 +0000802 self._initialized = True
Victor Stinnercd590a72019-05-28 00:39:52 +0200803 # Copy of sys.stderr used by self._invoke_excepthook()
Guido van Rossumd0648992007-08-20 19:25:41 +0000804 self._stderr = _sys.stderr
Victor Stinnercd590a72019-05-28 00:39:52 +0200805 self._invoke_excepthook = _make_invoke_excepthook()
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200806 # For debugging and _after_fork()
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200807 _dangling.add(self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000808
Antoine Pitrou7b476992013-09-07 23:38:37 +0200809 def _reset_internal_locks(self, is_alive):
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000810 # private! Called by _after_fork() to reset our internal locks as
811 # they may be in an invalid state leading to a deadlock or crash.
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000812 self._started._reset_internal_locks()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200813 if is_alive:
814 self._set_tstate_lock()
815 else:
816 # The thread isn't alive after fork: it doesn't have a tstate
817 # anymore.
Tim Petersb5e9ac92013-09-09 14:41:50 -0500818 self._is_stopped = True
Antoine Pitrou7b476992013-09-07 23:38:37 +0200819 self._tstate_lock = None
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000820
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000821 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000822 assert self._initialized, "Thread.__init__() was not called"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000823 status = "initial"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000824 if self._started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000825 status = "started"
Tim Peters72460fa2013-09-09 18:48:24 -0500826 self.is_alive() # easy way to get ._is_stopped set when appropriate
Tim Petersc363a232013-09-08 18:44:40 -0500827 if self._is_stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000828 status = "stopped"
Guido van Rossumd0648992007-08-20 19:25:41 +0000829 if self._daemonic:
Georg Brandl0c77a822008-06-10 16:37:50 +0000830 status += " daemon"
831 if self._ident is not None:
832 status += " %s" % self._ident
Guido van Rossumd0648992007-08-20 19:25:41 +0000833 return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000834
835 def start(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200836 """Start the thread's activity.
837
838 It must be called at most once per thread object. It arranges for the
839 object's run() method to be invoked in a separate thread of control.
840
841 This method will raise a RuntimeError if called more than once on the
842 same thread object.
843
844 """
Guido van Rossumd0648992007-08-20 19:25:41 +0000845 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000846 raise RuntimeError("thread.__init__() not called")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000847
Benjamin Peterson672b8032008-06-11 19:14:14 +0000848 if self._started.is_set():
Senthil Kumaranfdd4d0f2010-04-06 03:30:18 +0000849 raise RuntimeError("threads can only be started once")
Victor Stinner066e5b12019-06-14 18:55:22 +0200850
851 if self.daemon and not _is_main_interpreter():
852 raise RuntimeError("daemon thread are not supported "
853 "in subinterpreters")
854
Benjamin Petersond23f8222009-04-05 19:13:16 +0000855 with _active_limbo_lock:
856 _limbo[self] = self
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000857 try:
858 _start_new_thread(self._bootstrap, ())
859 except Exception:
860 with _active_limbo_lock:
861 del _limbo[self]
862 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000863 self._started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000864
865 def run(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200866 """Method representing the thread's activity.
867
868 You may override this method in a subclass. The standard run() method
869 invokes the callable object passed to the object's constructor as the
870 target argument, if any, with sequential and keyword arguments taken
871 from the args and kwargs arguments, respectively.
872
873 """
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000874 try:
875 if self._target:
876 self._target(*self._args, **self._kwargs)
877 finally:
878 # Avoid a refcycle if the thread is running a function with
879 # an argument that has a member that points to the thread.
880 del self._target, self._args, self._kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000881
Guido van Rossumd0648992007-08-20 19:25:41 +0000882 def _bootstrap(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000883 # Wrapper around the real bootstrap code that ignores
884 # exceptions during interpreter cleanup. Those typically
885 # happen when a daemon thread wakes up at an unfortunate
886 # moment, finds the world around it destroyed, and raises some
887 # random exception *** while trying to report the exception in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000888 # _bootstrap_inner() below ***. Those random exceptions
Guido van Rossum61e21b52007-08-20 19:06:03 +0000889 # don't help anybody, and they confuse users, so we suppress
890 # them. We suppress them only when it appears that the world
891 # indeed has already been destroyed, so that exceptions in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000892 # _bootstrap_inner() during normal business hours are properly
Guido van Rossum61e21b52007-08-20 19:06:03 +0000893 # reported. Also, we only suppress them for daemonic threads;
894 # if a non-daemonic encounters this, something else is wrong.
895 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000896 self._bootstrap_inner()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000897 except:
Guido van Rossumd0648992007-08-20 19:25:41 +0000898 if self._daemonic and _sys is None:
Guido van Rossum61e21b52007-08-20 19:06:03 +0000899 return
900 raise
901
Benjamin Petersond23f8222009-04-05 19:13:16 +0000902 def _set_ident(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200903 self._ident = get_ident()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000904
Jake Teslerb121f632019-05-22 08:43:17 -0700905 if _HAVE_THREAD_NATIVE_ID:
906 def _set_native_id(self):
907 self._native_id = get_native_id()
908
Antoine Pitrou7b476992013-09-07 23:38:37 +0200909 def _set_tstate_lock(self):
910 """
911 Set a lock object which will be released by the interpreter when
912 the underlying thread state (see pystate.h) gets deleted.
913 """
914 self._tstate_lock = _set_sentinel()
915 self._tstate_lock.acquire()
916
Victor Stinner468e5fe2019-06-13 01:30:17 +0200917 if not self.daemon:
918 with _shutdown_locks_lock:
919 _shutdown_locks.add(self._tstate_lock)
920
Guido van Rossumd0648992007-08-20 19:25:41 +0000921 def _bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000922 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000923 self._set_ident()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200924 self._set_tstate_lock()
Jake Teslerb121f632019-05-22 08:43:17 -0700925 if _HAVE_THREAD_NATIVE_ID:
926 self._set_native_id()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000927 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000928 with _active_limbo_lock:
929 _active[self._ident] = self
930 del _limbo[self]
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000931
932 if _trace_hook:
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000933 _sys.settrace(_trace_hook)
934 if _profile_hook:
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000935 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000936
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000937 try:
938 self.run()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000939 except:
Victor Stinnercd590a72019-05-28 00:39:52 +0200940 self._invoke_excepthook(self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000941 finally:
Christian Heimes1af737c2008-01-23 08:24:23 +0000942 with _active_limbo_lock:
Christian Heimes1af737c2008-01-23 08:24:23 +0000943 try:
Georg Brandl0c77a822008-06-10 16:37:50 +0000944 # We don't call self._delete() because it also
Christian Heimes1af737c2008-01-23 08:24:23 +0000945 # grabs _active_limbo_lock.
Victor Stinner2a129742011-05-30 23:02:52 +0200946 del _active[get_ident()]
Christian Heimes1af737c2008-01-23 08:24:23 +0000947 except:
948 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000949
Guido van Rossumd0648992007-08-20 19:25:41 +0000950 def _stop(self):
Tim Petersb5e9ac92013-09-09 14:41:50 -0500951 # After calling ._stop(), .is_alive() returns False and .join() returns
952 # immediately. ._tstate_lock must be released before calling ._stop().
953 #
954 # Normal case: C code at the end of the thread's life
955 # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and
956 # that's detected by our ._wait_for_tstate_lock(), called by .join()
957 # and .is_alive(). Any number of threads _may_ call ._stop()
958 # simultaneously (for example, if multiple threads are blocked in
959 # .join() calls), and they're not serialized. That's harmless -
960 # they'll just make redundant rebindings of ._is_stopped and
961 # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the
962 # "assert self._is_stopped" in ._wait_for_tstate_lock() always works
963 # (the assert is executed only if ._tstate_lock is None).
964 #
965 # Special case: _main_thread releases ._tstate_lock via this
966 # module's _shutdown() function.
967 lock = self._tstate_lock
968 if lock is not None:
969 assert not lock.locked()
Tim Peters78755232013-09-09 13:47:16 -0500970 self._is_stopped = True
971 self._tstate_lock = None
Victor Stinner468e5fe2019-06-13 01:30:17 +0200972 if not self.daemon:
973 with _shutdown_locks_lock:
Victor Stinner6f75c872019-06-13 12:06:24 +0200974 _shutdown_locks.discard(lock)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000975
Guido van Rossumd0648992007-08-20 19:25:41 +0000976 def _delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000977 "Remove current thread from the dict of currently running threads."
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200978 with _active_limbo_lock:
979 del _active[get_ident()]
980 # There must not be any python code between the previous line
981 # and after the lock is released. Otherwise a tracing function
982 # could try to acquire the lock again in the same thread, (in
983 # current_thread()), and would block.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000984
985 def join(self, timeout=None):
Georg Brandlc30b59f2013-10-13 10:43:59 +0200986 """Wait until the thread terminates.
987
988 This blocks the calling thread until the thread whose join() method is
989 called terminates -- either normally or through an unhandled exception
990 or until the optional timeout occurs.
991
992 When the timeout argument is present and not None, it should be a
993 floating point number specifying a timeout for the operation in seconds
994 (or fractions thereof). As join() always returns None, you must call
Dong-hee Na36d9e9a2019-01-18 18:50:47 +0900995 is_alive() after join() to decide whether a timeout happened -- if the
Georg Brandlc30b59f2013-10-13 10:43:59 +0200996 thread is still alive, the join() call timed out.
997
998 When the timeout argument is not present or None, the operation will
999 block until the thread terminates.
1000
1001 A thread can be join()ed many times.
1002
1003 join() raises a RuntimeError if an attempt is made to join the current
1004 thread as that would cause a deadlock. It is also an error to join() a
1005 thread before it has been started and attempts to do so raises the same
1006 exception.
1007
1008 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001009 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001010 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +00001011 if not self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001012 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson672b8032008-06-11 19:14:14 +00001013 if self is current_thread():
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001014 raise RuntimeError("cannot join current thread")
Tim Peterse5bb0bf2013-10-25 20:46:51 -05001015
Tim Petersc363a232013-09-08 18:44:40 -05001016 if timeout is None:
1017 self._wait_for_tstate_lock()
Tim Peters7bad39f2013-10-25 22:33:52 -05001018 else:
1019 # the behavior of a negative timeout isn't documented, but
Tim Petersa577f1e2013-10-26 11:56:16 -05001020 # historically .join(timeout=x) for x<0 has acted as if timeout=0
Tim Peters7bad39f2013-10-25 22:33:52 -05001021 self._wait_for_tstate_lock(timeout=max(timeout, 0))
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001022
Tim Petersc363a232013-09-08 18:44:40 -05001023 def _wait_for_tstate_lock(self, block=True, timeout=-1):
Antoine Pitrou7b476992013-09-07 23:38:37 +02001024 # Issue #18808: wait for the thread state to be gone.
Tim Petersc363a232013-09-08 18:44:40 -05001025 # At the end of the thread's life, after all knowledge of the thread
1026 # is removed from C data structures, C code releases our _tstate_lock.
Martin Panter46f50722016-05-26 05:35:26 +00001027 # This method passes its arguments to _tstate_lock.acquire().
Tim Petersc363a232013-09-08 18:44:40 -05001028 # If the lock is acquired, the C code is done, and self._stop() is
1029 # called. That sets ._is_stopped to True, and ._tstate_lock to None.
Antoine Pitrou7b476992013-09-07 23:38:37 +02001030 lock = self._tstate_lock
Tim Petersc363a232013-09-08 18:44:40 -05001031 if lock is None: # already determined that the C code is done
1032 assert self._is_stopped
1033 elif lock.acquire(block, timeout):
Antoine Pitrou7b476992013-09-07 23:38:37 +02001034 lock.release()
Tim Petersc363a232013-09-08 18:44:40 -05001035 self._stop()
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001036
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001037 @property
1038 def name(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001039 """A string used for identification purposes only.
1040
1041 It has no semantics. Multiple threads may be given the same name. The
1042 initial name is set by the constructor.
1043
1044 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001045 assert self._initialized, "Thread.__init__() not called"
1046 return self._name
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001047
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001048 @name.setter
1049 def name(self, name):
Guido van Rossumd0648992007-08-20 19:25:41 +00001050 assert self._initialized, "Thread.__init__() not called"
1051 self._name = str(name)
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001052
Benjamin Peterson773c17b2008-08-18 16:45:31 +00001053 @property
1054 def ident(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001055 """Thread identifier of this thread or None if it has not been started.
1056
Skip Montanaro56343312018-05-18 13:38:36 -05001057 This is a nonzero integer. See the get_ident() function. Thread
Georg Brandlc30b59f2013-10-13 10:43:59 +02001058 identifiers may be recycled when a thread exits and another thread is
1059 created. The identifier is available even after the thread has exited.
1060
1061 """
Georg Brandl0c77a822008-06-10 16:37:50 +00001062 assert self._initialized, "Thread.__init__() not called"
1063 return self._ident
1064
Jake Teslerb121f632019-05-22 08:43:17 -07001065 if _HAVE_THREAD_NATIVE_ID:
1066 @property
1067 def native_id(self):
1068 """Native integral thread ID of this thread, or None if it has not been started.
1069
1070 This is a non-negative integer. See the get_native_id() function.
1071 This represents the Thread ID as reported by the kernel.
1072
1073 """
1074 assert self._initialized, "Thread.__init__() not called"
1075 return self._native_id
1076
Benjamin Peterson672b8032008-06-11 19:14:14 +00001077 def is_alive(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001078 """Return whether the thread is alive.
1079
1080 This method returns True just before the run() method starts until just
1081 after the run() method terminates. The module function enumerate()
1082 returns a list of all alive threads.
1083
1084 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001085 assert self._initialized, "Thread.__init__() not called"
Tim Petersc363a232013-09-08 18:44:40 -05001086 if self._is_stopped or not self._started.is_set():
Antoine Pitrou7b476992013-09-07 23:38:37 +02001087 return False
Antoine Pitrou7b476992013-09-07 23:38:37 +02001088 self._wait_for_tstate_lock(False)
Tim Petersc363a232013-09-08 18:44:40 -05001089 return not self._is_stopped
Tim Petersb90f89a2001-01-15 03:26:36 +00001090
Dong-hee Na89669ff2019-01-17 21:14:45 +09001091 def isAlive(self):
1092 """Return whether the thread is alive.
1093
1094 This method is deprecated, use is_alive() instead.
1095 """
1096 import warnings
1097 warnings.warn('isAlive() is deprecated, use is_alive() instead',
1098 DeprecationWarning, stacklevel=2)
1099 return self.is_alive()
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001100
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001101 @property
1102 def daemon(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001103 """A boolean value indicating whether this thread is a daemon thread.
1104
1105 This must be set before start() is called, otherwise RuntimeError is
1106 raised. Its initial value is inherited from the creating thread; the
1107 main thread is not a daemon thread and therefore all threads created in
1108 the main thread default to daemon = False.
1109
mbarkhaubb110cc2019-06-22 14:51:06 +02001110 The entire Python program exits when only daemon threads are left.
Georg Brandlc30b59f2013-10-13 10:43:59 +02001111
1112 """
Guido van Rossumd0648992007-08-20 19:25:41 +00001113 assert self._initialized, "Thread.__init__() not called"
1114 return self._daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001115
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001116 @daemon.setter
1117 def daemon(self, daemonic):
Guido van Rossumd0648992007-08-20 19:25:41 +00001118 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001119 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +00001120 if self._started.is_set():
Antoine Pitrou10959072014-03-17 18:22:41 +01001121 raise RuntimeError("cannot set daemon status of active thread")
Guido van Rossumd0648992007-08-20 19:25:41 +00001122 self._daemonic = daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001123
Benjamin Peterson6640d722008-08-18 18:16:46 +00001124 def isDaemon(self):
1125 return self.daemon
1126
1127 def setDaemon(self, daemonic):
1128 self.daemon = daemonic
1129
1130 def getName(self):
1131 return self.name
1132
1133 def setName(self, name):
1134 self.name = name
1135
Victor Stinnercd590a72019-05-28 00:39:52 +02001136
1137try:
1138 from _thread import (_excepthook as excepthook,
1139 _ExceptHookArgs as ExceptHookArgs)
1140except ImportError:
1141 # Simple Python implementation if _thread._excepthook() is not available
1142 from traceback import print_exception as _print_exception
1143 from collections import namedtuple
1144
1145 _ExceptHookArgs = namedtuple(
1146 'ExceptHookArgs',
1147 'exc_type exc_value exc_traceback thread')
1148
1149 def ExceptHookArgs(args):
1150 return _ExceptHookArgs(*args)
1151
1152 def excepthook(args, /):
1153 """
1154 Handle uncaught Thread.run() exception.
1155 """
1156 if args.exc_type == SystemExit:
1157 # silently ignore SystemExit
1158 return
1159
1160 if _sys is not None and _sys.stderr is not None:
1161 stderr = _sys.stderr
1162 elif args.thread is not None:
1163 stderr = args.thread._stderr
1164 if stderr is None:
1165 # do nothing if sys.stderr is None and sys.stderr was None
1166 # when the thread was created
1167 return
1168 else:
1169 # do nothing if sys.stderr is None and args.thread is None
1170 return
1171
1172 if args.thread is not None:
1173 name = args.thread.name
1174 else:
1175 name = get_ident()
1176 print(f"Exception in thread {name}:",
1177 file=stderr, flush=True)
1178 _print_exception(args.exc_type, args.exc_value, args.exc_traceback,
1179 file=stderr)
1180 stderr.flush()
1181
1182
1183def _make_invoke_excepthook():
1184 # Create a local namespace to ensure that variables remain alive
1185 # when _invoke_excepthook() is called, even if it is called late during
1186 # Python shutdown. It is mostly needed for daemon threads.
1187
1188 old_excepthook = excepthook
1189 old_sys_excepthook = _sys.excepthook
1190 if old_excepthook is None:
1191 raise RuntimeError("threading.excepthook is None")
1192 if old_sys_excepthook is None:
1193 raise RuntimeError("sys.excepthook is None")
1194
1195 sys_exc_info = _sys.exc_info
1196 local_print = print
1197 local_sys = _sys
1198
1199 def invoke_excepthook(thread):
1200 global excepthook
1201 try:
1202 hook = excepthook
1203 if hook is None:
1204 hook = old_excepthook
1205
1206 args = ExceptHookArgs([*sys_exc_info(), thread])
1207
1208 hook(args)
1209 except Exception as exc:
1210 exc.__suppress_context__ = True
1211 del exc
1212
1213 if local_sys is not None and local_sys.stderr is not None:
1214 stderr = local_sys.stderr
1215 else:
1216 stderr = thread._stderr
1217
1218 local_print("Exception in threading.excepthook:",
1219 file=stderr, flush=True)
1220
1221 if local_sys is not None and local_sys.excepthook is not None:
1222 sys_excepthook = local_sys.excepthook
1223 else:
1224 sys_excepthook = old_sys_excepthook
1225
1226 sys_excepthook(*sys_exc_info())
1227 finally:
1228 # Break reference cycle (exception stored in a variable)
1229 args = None
1230
1231 return invoke_excepthook
1232
1233
Martin v. Löwis44f86962001-09-05 13:44:54 +00001234# The timer class was contributed by Itamar Shtull-Trauring
1235
Éric Araujo0cdd4452011-07-28 00:28:28 +02001236class Timer(Thread):
Martin v. Löwis44f86962001-09-05 13:44:54 +00001237 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +00001238
Georg Brandlc30b59f2013-10-13 10:43:59 +02001239 t = Timer(30.0, f, args=None, kwargs=None)
1240 t.start()
1241 t.cancel() # stop the timer's action if it's still waiting
1242
Martin v. Löwis44f86962001-09-05 13:44:54 +00001243 """
Tim Petersb64bec32001-09-18 02:26:39 +00001244
R David Murray19aeb432013-03-30 17:19:38 -04001245 def __init__(self, interval, function, args=None, kwargs=None):
Martin v. Löwis44f86962001-09-05 13:44:54 +00001246 Thread.__init__(self)
1247 self.interval = interval
1248 self.function = function
R David Murray19aeb432013-03-30 17:19:38 -04001249 self.args = args if args is not None else []
1250 self.kwargs = kwargs if kwargs is not None else {}
Martin v. Löwis44f86962001-09-05 13:44:54 +00001251 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +00001252
Martin v. Löwis44f86962001-09-05 13:44:54 +00001253 def cancel(self):
Georg Brandlc30b59f2013-10-13 10:43:59 +02001254 """Stop the timer if it hasn't finished yet."""
Martin v. Löwis44f86962001-09-05 13:44:54 +00001255 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +00001256
Martin v. Löwis44f86962001-09-05 13:44:54 +00001257 def run(self):
1258 self.finished.wait(self.interval)
Benjamin Peterson672b8032008-06-11 19:14:14 +00001259 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +00001260 self.function(*self.args, **self.kwargs)
1261 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001262
Antoine Pitrou1023dbb2017-10-02 16:42:15 +02001263
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001264# Special thread class to represent the main thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001265
1266class _MainThread(Thread):
1267
1268 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +00001269 Thread.__init__(self, name="MainThread", daemon=False)
Tim Petersc363a232013-09-08 18:44:40 -05001270 self._set_tstate_lock()
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001271 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +00001272 self._set_ident()
Jake Teslerb121f632019-05-22 08:43:17 -07001273 if _HAVE_THREAD_NATIVE_ID:
1274 self._set_native_id()
Benjamin Petersond23f8222009-04-05 19:13:16 +00001275 with _active_limbo_lock:
1276 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001277
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001278
1279# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +00001280# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson672b8032008-06-11 19:14:14 +00001281# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +00001282# leave an entry in the _active dict forever after.
Benjamin Peterson672b8032008-06-11 19:14:14 +00001283# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001284# They are marked as daemon threads so we won't wait for them
1285# when we exit (conform previous semantics).
1286
1287class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +00001288
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001289 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +00001290 Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
Tim Peters711906e2005-01-08 07:30:42 +00001291
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001292 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +00001293 self._set_ident()
Jake Teslerb121f632019-05-22 08:43:17 -07001294 if _HAVE_THREAD_NATIVE_ID:
1295 self._set_native_id()
Benjamin Petersond23f8222009-04-05 19:13:16 +00001296 with _active_limbo_lock:
1297 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001298
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02001299 def _stop(self):
1300 pass
1301
Xiang Zhangf3a9fab2017-02-27 11:01:30 +08001302 def is_alive(self):
1303 assert not self._is_stopped and self._started.is_set()
1304 return True
1305
Neal Norwitz45bec8c2002-02-19 03:01:36 +00001306 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +00001307 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001308
1309
1310# Global API functions
1311
Benjamin Peterson672b8032008-06-11 19:14:14 +00001312def current_thread():
Georg Brandlc30b59f2013-10-13 10:43:59 +02001313 """Return the current Thread object, corresponding to the caller's thread of control.
1314
1315 If the caller's thread of control was not created through the threading
1316 module, a dummy thread object with limited functionality is returned.
1317
1318 """
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001319 try:
Victor Stinner2a129742011-05-30 23:02:52 +02001320 return _active[get_ident()]
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001321 except KeyError:
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001322 return _DummyThread()
1323
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001324currentThread = current_thread
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001325
Benjamin Peterson672b8032008-06-11 19:14:14 +00001326def active_count():
Georg Brandlc30b59f2013-10-13 10:43:59 +02001327 """Return the number of Thread objects currently alive.
1328
1329 The returned count is equal to the length of the list returned by
1330 enumerate().
1331
1332 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001333 with _active_limbo_lock:
1334 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001335
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001336activeCount = active_count
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001337
Antoine Pitroubdec11f2009-11-05 13:49:14 +00001338def _enumerate():
1339 # Same as enumerate(), but without the lock. Internal use only.
1340 return list(_active.values()) + list(_limbo.values())
1341
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001342def enumerate():
Georg Brandlc30b59f2013-10-13 10:43:59 +02001343 """Return a list of all Thread objects currently alive.
1344
1345 The list includes daemonic threads, dummy thread objects created by
1346 current_thread(), and the main thread. It excludes terminated threads and
1347 threads that have not yet been started.
1348
1349 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001350 with _active_limbo_lock:
1351 return list(_active.values()) + list(_limbo.values())
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001352
Georg Brandl2067bfd2008-05-25 13:05:15 +00001353from _thread import stack_size
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001354
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001355# Create the main thread object,
1356# and make it available for the interpreter
1357# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001358
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001359_main_thread = _MainThread()
1360
1361def _shutdown():
Victor Stinner468e5fe2019-06-13 01:30:17 +02001362 """
1363 Wait until the Python thread state of all non-daemon threads get deleted.
1364 """
Tim Petersc363a232013-09-08 18:44:40 -05001365 # Obscure: other threads may be waiting to join _main_thread. That's
1366 # dubious, but some code does it. We can't wait for C code to release
1367 # the main thread's tstate_lock - that won't happen until the interpreter
1368 # is nearly dead. So we release it here. Note that just calling _stop()
1369 # isn't enough: other threads may already be waiting on _tstate_lock.
Antoine Pitrouee84a602017-08-16 20:53:28 +02001370 if _main_thread._is_stopped:
1371 # _shutdown() was already called
1372 return
Victor Stinner468e5fe2019-06-13 01:30:17 +02001373
1374 # Main thread
Tim Petersb5e9ac92013-09-09 14:41:50 -05001375 tlock = _main_thread._tstate_lock
1376 # The main thread isn't finished yet, so its thread state lock can't have
1377 # been released.
1378 assert tlock is not None
1379 assert tlock.locked()
1380 tlock.release()
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001381 _main_thread._stop()
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001382
Victor Stinner468e5fe2019-06-13 01:30:17 +02001383 # Join all non-deamon threads
1384 while True:
1385 with _shutdown_locks_lock:
1386 locks = list(_shutdown_locks)
1387 _shutdown_locks.clear()
1388
1389 if not locks:
1390 break
1391
1392 for lock in locks:
1393 # mimick Thread.join()
1394 lock.acquire()
1395 lock.release()
1396
1397 # new threads can be spawned while we were waiting for the other
1398 # threads to complete
1399
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001400
1401def main_thread():
Andrew Svetlovb1dd5572013-09-04 10:33:11 +03001402 """Return the main thread object.
1403
1404 In normal conditions, the main thread is the thread from which the
1405 Python interpreter was started.
1406 """
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001407 return _main_thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001408
Jim Fultond15dc062004-07-14 19:11:50 +00001409# get thread-local implementation, either from the thread
1410# module, or from the python fallback
1411
1412try:
Georg Brandl2067bfd2008-05-25 13:05:15 +00001413 from _thread import _local as local
Brett Cannoncd171c82013-07-04 17:43:24 -04001414except ImportError:
Jim Fultond15dc062004-07-14 19:11:50 +00001415 from _threading_local import local
1416
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001417
Jesse Nollera8513972008-07-17 16:49:17 +00001418def _after_fork():
Antoine Pitrou4a8bcdf2017-05-28 14:02:26 +02001419 """
1420 Cleanup threading module state that should not exist after a fork.
1421 """
Jesse Nollera8513972008-07-17 16:49:17 +00001422 # Reset _active_limbo_lock, in case we forked while the lock was held
1423 # by another (non-forked) thread. http://bugs.python.org/issue874900
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001424 global _active_limbo_lock, _main_thread
Victor Stinner468e5fe2019-06-13 01:30:17 +02001425 global _shutdown_locks_lock, _shutdown_locks
Jesse Nollera8513972008-07-17 16:49:17 +00001426 _active_limbo_lock = _allocate_lock()
1427
1428 # fork() only copied the current thread; clear references to others.
1429 new_active = {}
1430 current = current_thread()
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +03001431 _main_thread = current
Victor Stinner468e5fe2019-06-13 01:30:17 +02001432
1433 # reset _shutdown() locks: threads re-register their _tstate_lock below
1434 _shutdown_locks_lock = _allocate_lock()
1435 _shutdown_locks = set()
1436
Jesse Nollera8513972008-07-17 16:49:17 +00001437 with _active_limbo_lock:
Antoine Pitrou5da7e792013-09-08 13:19:06 +02001438 # Dangling thread instances must still have their locks reset,
1439 # because someone may join() them.
1440 threads = set(_enumerate())
1441 threads.update(_dangling)
1442 for thread in threads:
Charles-François Natalib055bf62011-12-18 18:45:16 +01001443 # Any lock/condition variable may be currently locked or in an
1444 # invalid state, so we reinitialize them.
Jesse Nollera8513972008-07-17 16:49:17 +00001445 if thread is current:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001446 # There is only one active thread. We reset the ident to
1447 # its new value since it can have changed.
Antoine Pitrou7b476992013-09-07 23:38:37 +02001448 thread._reset_internal_locks(True)
Victor Stinner2a129742011-05-30 23:02:52 +02001449 ident = get_ident()
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001450 thread._ident = ident
Jesse Nollera8513972008-07-17 16:49:17 +00001451 new_active[ident] = thread
1452 else:
1453 # All the others are already stopped.
Antoine Pitrou7b476992013-09-07 23:38:37 +02001454 thread._reset_internal_locks(False)
Charles-François Natalib055bf62011-12-18 18:45:16 +01001455 thread._stop()
Jesse Nollera8513972008-07-17 16:49:17 +00001456
1457 _limbo.clear()
1458 _active.clear()
1459 _active.update(new_active)
1460 assert len(_active) == 1
Antoine Pitrou4a8bcdf2017-05-28 14:02:26 +02001461
1462
Gregory P. Smith163468a2017-05-29 10:03:41 -07001463if hasattr(_os, "register_at_fork"):
1464 _os.register_at_fork(after_in_child=_after_fork)