threading.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. """Thread module emulating a subset of Java's threading model."""
  2. import os as _os
  3. import sys as _sys
  4. import _thread
  5. from time import monotonic as _time
  6. from _weakrefset import WeakSet
  7. from itertools import islice as _islice, count as _count
  8. try:
  9. from _collections import deque as _deque
  10. except ImportError:
  11. from collections import deque as _deque
  12. # Note regarding PEP 8 compliant names
  13. # This threading model was originally inspired by Java, and inherited
  14. # the convention of camelCase function and method names from that
  15. # language. Those original names are not in any imminent danger of
  16. # being deprecated (even for Py3k),so this module provides them as an
  17. # alias for the PEP 8 compliant names
  18. # Note that using the new PEP 8 compliant names facilitates substitution
  19. # with the multiprocessing module, which doesn't provide the old
  20. # Java inspired names.
  21. __all__ = ['get_ident', 'active_count', 'Condition', 'current_thread',
  22. 'enumerate', 'main_thread', 'TIMEOUT_MAX',
  23. 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
  24. 'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError',
  25. 'setprofile', 'settrace', 'local', 'stack_size',
  26. 'excepthook', 'ExceptHookArgs']
  27. # Rename some stuff so "from threading import *" is safe
  28. _start_new_thread = _thread.start_new_thread
  29. _allocate_lock = _thread.allocate_lock
  30. _set_sentinel = _thread._set_sentinel
  31. get_ident = _thread.get_ident
  32. try:
  33. get_native_id = _thread.get_native_id
  34. _HAVE_THREAD_NATIVE_ID = True
  35. __all__.append('get_native_id')
  36. except AttributeError:
  37. _HAVE_THREAD_NATIVE_ID = False
  38. ThreadError = _thread.error
  39. try:
  40. _CRLock = _thread.RLock
  41. except AttributeError:
  42. _CRLock = None
  43. TIMEOUT_MAX = _thread.TIMEOUT_MAX
  44. del _thread
  45. # Support for profile and trace hooks
  46. _profile_hook = None
  47. _trace_hook = None
  48. def setprofile(func):
  49. """Set a profile function for all threads started from the threading module.
  50. The func will be passed to sys.setprofile() for each thread, before its
  51. run() method is called.
  52. """
  53. global _profile_hook
  54. _profile_hook = func
  55. def settrace(func):
  56. """Set a trace function for all threads started from the threading module.
  57. The func will be passed to sys.settrace() for each thread, before its run()
  58. method is called.
  59. """
  60. global _trace_hook
  61. _trace_hook = func
  62. # Synchronization classes
  63. Lock = _allocate_lock
  64. def RLock(*args, **kwargs):
  65. """Factory function that returns a new reentrant lock.
  66. A reentrant lock must be released by the thread that acquired it. Once a
  67. thread has acquired a reentrant lock, the same thread may acquire it again
  68. without blocking; the thread must release it once for each time it has
  69. acquired it.
  70. """
  71. if _CRLock is None:
  72. return _PyRLock(*args, **kwargs)
  73. return _CRLock(*args, **kwargs)
  74. class _RLock:
  75. """This class implements reentrant lock objects.
  76. A reentrant lock must be released by the thread that acquired it. Once a
  77. thread has acquired a reentrant lock, the same thread may acquire it
  78. again without blocking; the thread must release it once for each time it
  79. has acquired it.
  80. """
  81. def __init__(self):
  82. self._block = _allocate_lock()
  83. self._owner = None
  84. self._count = 0
  85. def __repr__(self):
  86. owner = self._owner
  87. try:
  88. owner = _active[owner].name
  89. except KeyError:
  90. pass
  91. return "<%s %s.%s object owner=%r count=%d at %s>" % (
  92. "locked" if self._block.locked() else "unlocked",
  93. self.__class__.__module__,
  94. self.__class__.__qualname__,
  95. owner,
  96. self._count,
  97. hex(id(self))
  98. )
  99. def acquire(self, blocking=True, timeout=-1):
  100. """Acquire a lock, blocking or non-blocking.
  101. When invoked without arguments: if this thread already owns the lock,
  102. increment the recursion level by one, and return immediately. Otherwise,
  103. if another thread owns the lock, block until the lock is unlocked. Once
  104. the lock is unlocked (not owned by any thread), then grab ownership, set
  105. the recursion level to one, and return. If more than one thread is
  106. blocked waiting until the lock is unlocked, only one at a time will be
  107. able to grab ownership of the lock. There is no return value in this
  108. case.
  109. When invoked with the blocking argument set to true, do the same thing
  110. as when called without arguments, and return true.
  111. When invoked with the blocking argument set to false, do not block. If a
  112. call without an argument would block, return false immediately;
  113. otherwise, do the same thing as when called without arguments, and
  114. return true.
  115. When invoked with the floating-point timeout argument set to a positive
  116. value, block for at most the number of seconds specified by timeout
  117. and as long as the lock cannot be acquired. Return true if the lock has
  118. been acquired, false if the timeout has elapsed.
  119. """
  120. me = get_ident()
  121. if self._owner == me:
  122. self._count += 1
  123. return 1
  124. rc = self._block.acquire(blocking, timeout)
  125. if rc:
  126. self._owner = me
  127. self._count = 1
  128. return rc
  129. __enter__ = acquire
  130. def release(self):
  131. """Release a lock, decrementing the recursion level.
  132. If after the decrement it is zero, reset the lock to unlocked (not owned
  133. by any thread), and if any other threads are blocked waiting for the
  134. lock to become unlocked, allow exactly one of them to proceed. If after
  135. the decrement the recursion level is still nonzero, the lock remains
  136. locked and owned by the calling thread.
  137. Only call this method when the calling thread owns the lock. A
  138. RuntimeError is raised if this method is called when the lock is
  139. unlocked.
  140. There is no return value.
  141. """
  142. if self._owner != get_ident():
  143. raise RuntimeError("cannot release un-acquired lock")
  144. self._count = count = self._count - 1
  145. if not count:
  146. self._owner = None
  147. self._block.release()
  148. def __exit__(self, t, v, tb):
  149. self.release()
  150. # Internal methods used by condition variables
  151. def _acquire_restore(self, state):
  152. self._block.acquire()
  153. self._count, self._owner = state
  154. def _release_save(self):
  155. if self._count == 0:
  156. raise RuntimeError("cannot release un-acquired lock")
  157. count = self._count
  158. self._count = 0
  159. owner = self._owner
  160. self._owner = None
  161. self._block.release()
  162. return (count, owner)
  163. def _is_owned(self):
  164. return self._owner == get_ident()
  165. _PyRLock = _RLock
  166. class Condition:
  167. """Class that implements a condition variable.
  168. A condition variable allows one or more threads to wait until they are
  169. notified by another thread.
  170. If the lock argument is given and not None, it must be a Lock or RLock
  171. object, and it is used as the underlying lock. Otherwise, a new RLock object
  172. is created and used as the underlying lock.
  173. """
  174. def __init__(self, lock=None):
  175. if lock is None:
  176. lock = RLock()
  177. self._lock = lock
  178. # Export the lock's acquire() and release() methods
  179. self.acquire = lock.acquire
  180. self.release = lock.release
  181. # If the lock defines _release_save() and/or _acquire_restore(),
  182. # these override the default implementations (which just call
  183. # release() and acquire() on the lock). Ditto for _is_owned().
  184. try:
  185. self._release_save = lock._release_save
  186. except AttributeError:
  187. pass
  188. try:
  189. self._acquire_restore = lock._acquire_restore
  190. except AttributeError:
  191. pass
  192. try:
  193. self._is_owned = lock._is_owned
  194. except AttributeError:
  195. pass
  196. self._waiters = _deque()
  197. def __enter__(self):
  198. return self._lock.__enter__()
  199. def __exit__(self, *args):
  200. return self._lock.__exit__(*args)
  201. def __repr__(self):
  202. return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
  203. def _release_save(self):
  204. self._lock.release() # No state to save
  205. def _acquire_restore(self, x):
  206. self._lock.acquire() # Ignore saved state
  207. def _is_owned(self):
  208. # Return True if lock is owned by current_thread.
  209. # This method is called only if _lock doesn't have _is_owned().
  210. if self._lock.acquire(0):
  211. self._lock.release()
  212. return False
  213. else:
  214. return True
  215. def wait(self, timeout=None):
  216. """Wait until notified or until a timeout occurs.
  217. If the calling thread has not acquired the lock when this method is
  218. called, a RuntimeError is raised.
  219. This method releases the underlying lock, and then blocks until it is
  220. awakened by a notify() or notify_all() call for the same condition
  221. variable in another thread, or until the optional timeout occurs. Once
  222. awakened or timed out, it re-acquires the lock and returns.
  223. When the timeout argument is present and not None, it should be a
  224. floating point number specifying a timeout for the operation in seconds
  225. (or fractions thereof).
  226. When the underlying lock is an RLock, it is not released using its
  227. release() method, since this may not actually unlock the lock when it
  228. was acquired multiple times recursively. Instead, an internal interface
  229. of the RLock class is used, which really unlocks it even when it has
  230. been recursively acquired several times. Another internal interface is
  231. then used to restore the recursion level when the lock is reacquired.
  232. """
  233. if not self._is_owned():
  234. raise RuntimeError("cannot wait on un-acquired lock")
  235. waiter = _allocate_lock()
  236. waiter.acquire()
  237. self._waiters.append(waiter)
  238. saved_state = self._release_save()
  239. gotit = False
  240. try: # restore state no matter what (e.g., KeyboardInterrupt)
  241. if timeout is None:
  242. waiter.acquire()
  243. gotit = True
  244. else:
  245. if timeout > 0:
  246. gotit = waiter.acquire(True, timeout)
  247. else:
  248. gotit = waiter.acquire(False)
  249. return gotit
  250. finally:
  251. self._acquire_restore(saved_state)
  252. if not gotit:
  253. try:
  254. self._waiters.remove(waiter)
  255. except ValueError:
  256. pass
  257. def wait_for(self, predicate, timeout=None):
  258. """Wait until a condition evaluates to True.
  259. predicate should be a callable which result will be interpreted as a
  260. boolean value. A timeout may be provided giving the maximum time to
  261. wait.
  262. """
  263. endtime = None
  264. waittime = timeout
  265. result = predicate()
  266. while not result:
  267. if waittime is not None:
  268. if endtime is None:
  269. endtime = _time() + waittime
  270. else:
  271. waittime = endtime - _time()
  272. if waittime <= 0:
  273. break
  274. self.wait(waittime)
  275. result = predicate()
  276. return result
  277. def notify(self, n=1):
  278. """Wake up one or more threads waiting on this condition, if any.
  279. If the calling thread has not acquired the lock when this method is
  280. called, a RuntimeError is raised.
  281. This method wakes up at most n of the threads waiting for the condition
  282. variable; it is a no-op if no threads are waiting.
  283. """
  284. if not self._is_owned():
  285. raise RuntimeError("cannot notify on un-acquired lock")
  286. all_waiters = self._waiters
  287. waiters_to_notify = _deque(_islice(all_waiters, n))
  288. if not waiters_to_notify:
  289. return
  290. for waiter in waiters_to_notify:
  291. waiter.release()
  292. try:
  293. all_waiters.remove(waiter)
  294. except ValueError:
  295. pass
  296. def notify_all(self):
  297. """Wake up all threads waiting on this condition.
  298. If the calling thread has not acquired the lock when this method
  299. is called, a RuntimeError is raised.
  300. """
  301. self.notify(len(self._waiters))
  302. notifyAll = notify_all
  303. class Semaphore:
  304. """This class implements semaphore objects.
  305. Semaphores manage a counter representing the number of release() calls minus
  306. the number of acquire() calls, plus an initial value. The acquire() method
  307. blocks if necessary until it can return without making the counter
  308. negative. If not given, value defaults to 1.
  309. """
  310. # After Tim Peters' semaphore class, but not quite the same (no maximum)
  311. def __init__(self, value=1):
  312. if value < 0:
  313. raise ValueError("semaphore initial value must be >= 0")
  314. self._cond = Condition(Lock())
  315. self._value = value
  316. def acquire(self, blocking=True, timeout=None):
  317. """Acquire a semaphore, decrementing the internal counter by one.
  318. When invoked without arguments: if the internal counter is larger than
  319. zero on entry, decrement it by one and return immediately. If it is zero
  320. on entry, block, waiting until some other thread has called release() to
  321. make it larger than zero. This is done with proper interlocking so that
  322. if multiple acquire() calls are blocked, release() will wake exactly one
  323. of them up. The implementation may pick one at random, so the order in
  324. which blocked threads are awakened should not be relied on. There is no
  325. return value in this case.
  326. When invoked with blocking set to true, do the same thing as when called
  327. without arguments, and return true.
  328. When invoked with blocking set to false, do not block. If a call without
  329. an argument would block, return false immediately; otherwise, do the
  330. same thing as when called without arguments, and return true.
  331. When invoked with a timeout other than None, it will block for at
  332. most timeout seconds. If acquire does not complete successfully in
  333. that interval, return false. Return true otherwise.
  334. """
  335. if not blocking and timeout is not None:
  336. raise ValueError("can't specify timeout for non-blocking acquire")
  337. rc = False
  338. endtime = None
  339. with self._cond:
  340. while self._value == 0:
  341. if not blocking:
  342. break
  343. if timeout is not None:
  344. if endtime is None:
  345. endtime = _time() + timeout
  346. else:
  347. timeout = endtime - _time()
  348. if timeout <= 0:
  349. break
  350. self._cond.wait(timeout)
  351. else:
  352. self._value -= 1
  353. rc = True
  354. return rc
  355. __enter__ = acquire
  356. def release(self):
  357. """Release a semaphore, incrementing the internal counter by one.
  358. When the counter is zero on entry and another thread is waiting for it
  359. to become larger than zero again, wake up that thread.
  360. """
  361. with self._cond:
  362. self._value += 1
  363. self._cond.notify()
  364. def __exit__(self, t, v, tb):
  365. self.release()
  366. class BoundedSemaphore(Semaphore):
  367. """Implements a bounded semaphore.
  368. A bounded semaphore checks to make sure its current value doesn't exceed its
  369. initial value. If it does, ValueError is raised. In most situations
  370. semaphores are used to guard resources with limited capacity.
  371. If the semaphore is released too many times it's a sign of a bug. If not
  372. given, value defaults to 1.
  373. Like regular semaphores, bounded semaphores manage a counter representing
  374. the number of release() calls minus the number of acquire() calls, plus an
  375. initial value. The acquire() method blocks if necessary until it can return
  376. without making the counter negative. If not given, value defaults to 1.
  377. """
  378. def __init__(self, value=1):
  379. Semaphore.__init__(self, value)
  380. self._initial_value = value
  381. def release(self):
  382. """Release a semaphore, incrementing the internal counter by one.
  383. When the counter is zero on entry and another thread is waiting for it
  384. to become larger than zero again, wake up that thread.
  385. If the number of releases exceeds the number of acquires,
  386. raise a ValueError.
  387. """
  388. with self._cond:
  389. if self._value >= self._initial_value:
  390. raise ValueError("Semaphore released too many times")
  391. self._value += 1
  392. self._cond.notify()
  393. class Event:
  394. """Class implementing event objects.
  395. Events manage a flag that can be set to true with the set() method and reset
  396. to false with the clear() method. The wait() method blocks until the flag is
  397. true. The flag is initially false.
  398. """
  399. # After Tim Peters' event class (without is_posted())
  400. def __init__(self):
  401. self._cond = Condition(Lock())
  402. self._flag = False
  403. def _reset_internal_locks(self):
  404. # private! called by Thread._reset_internal_locks by _after_fork()
  405. self._cond.__init__(Lock())
  406. def is_set(self):
  407. """Return true if and only if the internal flag is true."""
  408. return self._flag
  409. isSet = is_set
  410. def set(self):
  411. """Set the internal flag to true.
  412. All threads waiting for it to become true are awakened. Threads
  413. that call wait() once the flag is true will not block at all.
  414. """
  415. with self._cond:
  416. self._flag = True
  417. self._cond.notify_all()
  418. def clear(self):
  419. """Reset the internal flag to false.
  420. Subsequently, threads calling wait() will block until set() is called to
  421. set the internal flag to true again.
  422. """
  423. with self._cond:
  424. self._flag = False
  425. def wait(self, timeout=None):
  426. """Block until the internal flag is true.
  427. If the internal flag is true on entry, return immediately. Otherwise,
  428. block until another thread calls set() to set the flag to true, or until
  429. the optional timeout occurs.
  430. When the timeout argument is present and not None, it should be a
  431. floating point number specifying a timeout for the operation in seconds
  432. (or fractions thereof).
  433. This method returns the internal flag on exit, so it will always return
  434. True except if a timeout is given and the operation times out.
  435. """
  436. with self._cond:
  437. signaled = self._flag
  438. if not signaled:
  439. signaled = self._cond.wait(timeout)
  440. return signaled
  441. # A barrier class. Inspired in part by the pthread_barrier_* api and
  442. # the CyclicBarrier class from Java. See
  443. # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
  444. # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
  445. # CyclicBarrier.html
  446. # for information.
  447. # We maintain two main states, 'filling' and 'draining' enabling the barrier
  448. # to be cyclic. Threads are not allowed into it until it has fully drained
  449. # since the previous cycle. In addition, a 'resetting' state exists which is
  450. # similar to 'draining' except that threads leave with a BrokenBarrierError,
  451. # and a 'broken' state in which all threads get the exception.
  452. class Barrier:
  453. """Implements a Barrier.
  454. Useful for synchronizing a fixed number of threads at known synchronization
  455. points. Threads block on 'wait()' and are simultaneously awoken once they
  456. have all made that call.
  457. """
  458. def __init__(self, parties, action=None, timeout=None):
  459. """Create a barrier, initialised to 'parties' threads.
  460. 'action' is a callable which, when supplied, will be called by one of
  461. the threads after they have all entered the barrier and just prior to
  462. releasing them all. If a 'timeout' is provided, it is used as the
  463. default for all subsequent 'wait()' calls.
  464. """
  465. self._cond = Condition(Lock())
  466. self._action = action
  467. self._timeout = timeout
  468. self._parties = parties
  469. self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
  470. self._count = 0
  471. def wait(self, timeout=None):
  472. """Wait for the barrier.
  473. When the specified number of threads have started waiting, they are all
  474. simultaneously awoken. If an 'action' was provided for the barrier, one
  475. of the threads will have executed that callback prior to returning.
  476. Returns an individual index number from 0 to 'parties-1'.
  477. """
  478. if timeout is None:
  479. timeout = self._timeout
  480. with self._cond:
  481. self._enter() # Block while the barrier drains.
  482. index = self._count
  483. self._count += 1
  484. try:
  485. if index + 1 == self._parties:
  486. # We release the barrier
  487. self._release()
  488. else:
  489. # We wait until someone releases us
  490. self._wait(timeout)
  491. return index
  492. finally:
  493. self._count -= 1
  494. # Wake up any threads waiting for barrier to drain.
  495. self._exit()
  496. # Block until the barrier is ready for us, or raise an exception
  497. # if it is broken.
  498. def _enter(self):
  499. while self._state in (-1, 1):
  500. # It is draining or resetting, wait until done
  501. self._cond.wait()
  502. #see if the barrier is in a broken state
  503. if self._state < 0:
  504. raise BrokenBarrierError
  505. assert self._state == 0
  506. # Optionally run the 'action' and release the threads waiting
  507. # in the barrier.
  508. def _release(self):
  509. try:
  510. if self._action:
  511. self._action()
  512. # enter draining state
  513. self._state = 1
  514. self._cond.notify_all()
  515. except:
  516. #an exception during the _action handler. Break and reraise
  517. self._break()
  518. raise
  519. # Wait in the barrier until we are released. Raise an exception
  520. # if the barrier is reset or broken.
  521. def _wait(self, timeout):
  522. if not self._cond.wait_for(lambda : self._state != 0, timeout):
  523. #timed out. Break the barrier
  524. self._break()
  525. raise BrokenBarrierError
  526. if self._state < 0:
  527. raise BrokenBarrierError
  528. assert self._state == 1
  529. # If we are the last thread to exit the barrier, signal any threads
  530. # waiting for the barrier to drain.
  531. def _exit(self):
  532. if self._count == 0:
  533. if self._state in (-1, 1):
  534. #resetting or draining
  535. self._state = 0
  536. self._cond.notify_all()
  537. def reset(self):
  538. """Reset the barrier to the initial state.
  539. Any threads currently waiting will get the BrokenBarrier exception
  540. raised.
  541. """
  542. with self._cond:
  543. if self._count > 0:
  544. if self._state == 0:
  545. #reset the barrier, waking up threads
  546. self._state = -1
  547. elif self._state == -2:
  548. #was broken, set it to reset state
  549. #which clears when the last thread exits
  550. self._state = -1
  551. else:
  552. self._state = 0
  553. self._cond.notify_all()
  554. def abort(self):
  555. """Place the barrier into a 'broken' state.
  556. Useful in case of error. Any currently waiting threads and threads
  557. attempting to 'wait()' will have BrokenBarrierError raised.
  558. """
  559. with self._cond:
  560. self._break()
  561. def _break(self):
  562. # An internal error was detected. The barrier is set to
  563. # a broken state all parties awakened.
  564. self._state = -2
  565. self._cond.notify_all()
  566. @property
  567. def parties(self):
  568. """Return the number of threads required to trip the barrier."""
  569. return self._parties
  570. @property
  571. def n_waiting(self):
  572. """Return the number of threads currently waiting at the barrier."""
  573. # We don't need synchronization here since this is an ephemeral result
  574. # anyway. It returns the correct value in the steady state.
  575. if self._state == 0:
  576. return self._count
  577. return 0
  578. @property
  579. def broken(self):
  580. """Return True if the barrier is in a broken state."""
  581. return self._state == -2
  582. # exception raised by the Barrier class
  583. class BrokenBarrierError(RuntimeError):
  584. pass
  585. # Helper to generate new thread names
  586. _counter = _count().__next__
  587. _counter() # Consume 0 so first non-main thread has id 1.
  588. def _newname(template="Thread-%d"):
  589. return template % _counter()
  590. # Active thread administration
  591. _active_limbo_lock = _allocate_lock()
  592. _active = {} # maps thread id to Thread object
  593. _limbo = {}
  594. _dangling = WeakSet()
  595. # Set of Thread._tstate_lock locks of non-daemon threads used by _shutdown()
  596. # to wait until all Python thread states get deleted:
  597. # see Thread._set_tstate_lock().
  598. _shutdown_locks_lock = _allocate_lock()
  599. _shutdown_locks = set()
  600. # Main class for threads
  601. class Thread:
  602. """A class that represents a thread of control.
  603. This class can be safely subclassed in a limited fashion. There are two ways
  604. to specify the activity: by passing a callable object to the constructor, or
  605. by overriding the run() method in a subclass.
  606. """
  607. _initialized = False
  608. def __init__(self, group=None, target=None, name=None,
  609. args=(), kwargs=None, *, daemon=None):
  610. """This constructor should always be called with keyword arguments. Arguments are:
  611. *group* should be None; reserved for future extension when a ThreadGroup
  612. class is implemented.
  613. *target* is the callable object to be invoked by the run()
  614. method. Defaults to None, meaning nothing is called.
  615. *name* is the thread name. By default, a unique name is constructed of
  616. the form "Thread-N" where N is a small decimal number.
  617. *args* is the argument tuple for the target invocation. Defaults to ().
  618. *kwargs* is a dictionary of keyword arguments for the target
  619. invocation. Defaults to {}.
  620. If a subclass overrides the constructor, it must make sure to invoke
  621. the base class constructor (Thread.__init__()) before doing anything
  622. else to the thread.
  623. """
  624. assert group is None, "group argument must be None for now"
  625. if kwargs is None:
  626. kwargs = {}
  627. self._target = target
  628. self._name = str(name or _newname())
  629. self._args = args
  630. self._kwargs = kwargs
  631. if daemon is not None:
  632. self._daemonic = daemon
  633. else:
  634. self._daemonic = current_thread().daemon
  635. self._ident = None
  636. if _HAVE_THREAD_NATIVE_ID:
  637. self._native_id = None
  638. self._tstate_lock = None
  639. self._started = Event()
  640. self._is_stopped = False
  641. self._initialized = True
  642. # Copy of sys.stderr used by self._invoke_excepthook()
  643. self._stderr = _sys.stderr
  644. self._invoke_excepthook = _make_invoke_excepthook()
  645. # For debugging and _after_fork()
  646. _dangling.add(self)
  647. def _reset_internal_locks(self, is_alive):
  648. # private! Called by _after_fork() to reset our internal locks as
  649. # they may be in an invalid state leading to a deadlock or crash.
  650. self._started._reset_internal_locks()
  651. if is_alive:
  652. self._set_tstate_lock()
  653. else:
  654. # The thread isn't alive after fork: it doesn't have a tstate
  655. # anymore.
  656. self._is_stopped = True
  657. self._tstate_lock = None
  658. def __repr__(self):
  659. assert self._initialized, "Thread.__init__() was not called"
  660. status = "initial"
  661. if self._started.is_set():
  662. status = "started"
  663. self.is_alive() # easy way to get ._is_stopped set when appropriate
  664. if self._is_stopped:
  665. status = "stopped"
  666. if self._daemonic:
  667. status += " daemon"
  668. if self._ident is not None:
  669. status += " %s" % self._ident
  670. return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
  671. def start(self):
  672. """Start the thread's activity.
  673. It must be called at most once per thread object. It arranges for the
  674. object's run() method to be invoked in a separate thread of control.
  675. This method will raise a RuntimeError if called more than once on the
  676. same thread object.
  677. """
  678. if not self._initialized:
  679. raise RuntimeError("thread.__init__() not called")
  680. if self._started.is_set():
  681. raise RuntimeError("threads can only be started once")
  682. with _active_limbo_lock:
  683. _limbo[self] = self
  684. try:
  685. _start_new_thread(self._bootstrap, ())
  686. except Exception:
  687. with _active_limbo_lock:
  688. del _limbo[self]
  689. raise
  690. self._started.wait()
  691. def run(self):
  692. """Method representing the thread's activity.
  693. You may override this method in a subclass. The standard run() method
  694. invokes the callable object passed to the object's constructor as the
  695. target argument, if any, with sequential and keyword arguments taken
  696. from the args and kwargs arguments, respectively.
  697. """
  698. try:
  699. if self._target:
  700. self._target(*self._args, **self._kwargs)
  701. finally:
  702. # Avoid a refcycle if the thread is running a function with
  703. # an argument that has a member that points to the thread.
  704. del self._target, self._args, self._kwargs
  705. def _bootstrap(self):
  706. # Wrapper around the real bootstrap code that ignores
  707. # exceptions during interpreter cleanup. Those typically
  708. # happen when a daemon thread wakes up at an unfortunate
  709. # moment, finds the world around it destroyed, and raises some
  710. # random exception *** while trying to report the exception in
  711. # _bootstrap_inner() below ***. Those random exceptions
  712. # don't help anybody, and they confuse users, so we suppress
  713. # them. We suppress them only when it appears that the world
  714. # indeed has already been destroyed, so that exceptions in
  715. # _bootstrap_inner() during normal business hours are properly
  716. # reported. Also, we only suppress them for daemonic threads;
  717. # if a non-daemonic encounters this, something else is wrong.
  718. try:
  719. self._bootstrap_inner()
  720. except:
  721. if self._daemonic and _sys is None:
  722. return
  723. raise
  724. def _set_ident(self):
  725. self._ident = get_ident()
  726. if _HAVE_THREAD_NATIVE_ID:
  727. def _set_native_id(self):
  728. self._native_id = get_native_id()
  729. def _set_tstate_lock(self):
  730. """
  731. Set a lock object which will be released by the interpreter when
  732. the underlying thread state (see pystate.h) gets deleted.
  733. """
  734. self._tstate_lock = _set_sentinel()
  735. self._tstate_lock.acquire()
  736. if not self.daemon:
  737. with _shutdown_locks_lock:
  738. _shutdown_locks.add(self._tstate_lock)
  739. def _bootstrap_inner(self):
  740. try:
  741. self._set_ident()
  742. self._set_tstate_lock()
  743. if _HAVE_THREAD_NATIVE_ID:
  744. self._set_native_id()
  745. self._started.set()
  746. with _active_limbo_lock:
  747. _active[self._ident] = self
  748. del _limbo[self]
  749. if _trace_hook:
  750. _sys.settrace(_trace_hook)
  751. if _profile_hook:
  752. _sys.setprofile(_profile_hook)
  753. try:
  754. self.run()
  755. except:
  756. self._invoke_excepthook(self)
  757. finally:
  758. with _active_limbo_lock:
  759. try:
  760. # We don't call self._delete() because it also
  761. # grabs _active_limbo_lock.
  762. del _active[get_ident()]
  763. except:
  764. pass
  765. def _stop(self):
  766. # After calling ._stop(), .is_alive() returns False and .join() returns
  767. # immediately. ._tstate_lock must be released before calling ._stop().
  768. #
  769. # Normal case: C code at the end of the thread's life
  770. # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and
  771. # that's detected by our ._wait_for_tstate_lock(), called by .join()
  772. # and .is_alive(). Any number of threads _may_ call ._stop()
  773. # simultaneously (for example, if multiple threads are blocked in
  774. # .join() calls), and they're not serialized. That's harmless -
  775. # they'll just make redundant rebindings of ._is_stopped and
  776. # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the
  777. # "assert self._is_stopped" in ._wait_for_tstate_lock() always works
  778. # (the assert is executed only if ._tstate_lock is None).
  779. #
  780. # Special case: _main_thread releases ._tstate_lock via this
  781. # module's _shutdown() function.
  782. lock = self._tstate_lock
  783. if lock is not None:
  784. assert not lock.locked()
  785. self._is_stopped = True
  786. self._tstate_lock = None
  787. if not self.daemon:
  788. with _shutdown_locks_lock:
  789. _shutdown_locks.discard(lock)
  790. def _delete(self):
  791. "Remove current thread from the dict of currently running threads."
  792. with _active_limbo_lock:
  793. del _active[get_ident()]
  794. # There must not be any python code between the previous line
  795. # and after the lock is released. Otherwise a tracing function
  796. # could try to acquire the lock again in the same thread, (in
  797. # current_thread()), and would block.
  798. def join(self, timeout=None):
  799. """Wait until the thread terminates.
  800. This blocks the calling thread until the thread whose join() method is
  801. called terminates -- either normally or through an unhandled exception
  802. or until the optional timeout occurs.
  803. When the timeout argument is present and not None, it should be a
  804. floating point number specifying a timeout for the operation in seconds
  805. (or fractions thereof). As join() always returns None, you must call
  806. is_alive() after join() to decide whether a timeout happened -- if the
  807. thread is still alive, the join() call timed out.
  808. When the timeout argument is not present or None, the operation will
  809. block until the thread terminates.
  810. A thread can be join()ed many times.
  811. join() raises a RuntimeError if an attempt is made to join the current
  812. thread as that would cause a deadlock. It is also an error to join() a
  813. thread before it has been started and attempts to do so raises the same
  814. exception.
  815. """
  816. if not self._initialized:
  817. raise RuntimeError("Thread.__init__() not called")
  818. if not self._started.is_set():
  819. raise RuntimeError("cannot join thread before it is started")
  820. if self is current_thread():
  821. raise RuntimeError("cannot join current thread")
  822. if timeout is None:
  823. self._wait_for_tstate_lock()
  824. else:
  825. # the behavior of a negative timeout isn't documented, but
  826. # historically .join(timeout=x) for x<0 has acted as if timeout=0
  827. self._wait_for_tstate_lock(timeout=max(timeout, 0))
  828. def _wait_for_tstate_lock(self, block=True, timeout=-1):
  829. # Issue #18808: wait for the thread state to be gone.
  830. # At the end of the thread's life, after all knowledge of the thread
  831. # is removed from C data structures, C code releases our _tstate_lock.
  832. # This method passes its arguments to _tstate_lock.acquire().
  833. # If the lock is acquired, the C code is done, and self._stop() is
  834. # called. That sets ._is_stopped to True, and ._tstate_lock to None.
  835. lock = self._tstate_lock
  836. if lock is None: # already determined that the C code is done
  837. assert self._is_stopped
  838. elif lock.acquire(block, timeout):
  839. lock.release()
  840. self._stop()
  841. @property
  842. def name(self):
  843. """A string used for identification purposes only.
  844. It has no semantics. Multiple threads may be given the same name. The
  845. initial name is set by the constructor.
  846. """
  847. assert self._initialized, "Thread.__init__() not called"
  848. return self._name
  849. @name.setter
  850. def name(self, name):
  851. assert self._initialized, "Thread.__init__() not called"
  852. self._name = str(name)
  853. @property
  854. def ident(self):
  855. """Thread identifier of this thread or None if it has not been started.
  856. This is a nonzero integer. See the get_ident() function. Thread
  857. identifiers may be recycled when a thread exits and another thread is
  858. created. The identifier is available even after the thread has exited.
  859. """
  860. assert self._initialized, "Thread.__init__() not called"
  861. return self._ident
  862. if _HAVE_THREAD_NATIVE_ID:
  863. @property
  864. def native_id(self):
  865. """Native integral thread ID of this thread, or None if it has not been started.
  866. This is a non-negative integer. See the get_native_id() function.
  867. This represents the Thread ID as reported by the kernel.
  868. """
  869. assert self._initialized, "Thread.__init__() not called"
  870. return self._native_id
  871. def is_alive(self):
  872. """Return whether the thread is alive.
  873. This method returns True just before the run() method starts until just
  874. after the run() method terminates. The module function enumerate()
  875. returns a list of all alive threads.
  876. """
  877. assert self._initialized, "Thread.__init__() not called"
  878. if self._is_stopped or not self._started.is_set():
  879. return False
  880. self._wait_for_tstate_lock(False)
  881. return not self._is_stopped
  882. def isAlive(self):
  883. """Return whether the thread is alive.
  884. This method is deprecated, use is_alive() instead.
  885. """
  886. import warnings
  887. warnings.warn('isAlive() is deprecated, use is_alive() instead',
  888. DeprecationWarning, stacklevel=2)
  889. return self.is_alive()
  890. @property
  891. def daemon(self):
  892. """A boolean value indicating whether this thread is a daemon thread.
  893. This must be set before start() is called, otherwise RuntimeError is
  894. raised. Its initial value is inherited from the creating thread; the
  895. main thread is not a daemon thread and therefore all threads created in
  896. the main thread default to daemon = False.
  897. The entire Python program exits when only daemon threads are left.
  898. """
  899. assert self._initialized, "Thread.__init__() not called"
  900. return self._daemonic
  901. @daemon.setter
  902. def daemon(self, daemonic):
  903. if not self._initialized:
  904. raise RuntimeError("Thread.__init__() not called")
  905. if self._started.is_set():
  906. raise RuntimeError("cannot set daemon status of active thread")
  907. self._daemonic = daemonic
  908. def isDaemon(self):
  909. return self.daemon
  910. def setDaemon(self, daemonic):
  911. self.daemon = daemonic
  912. def getName(self):
  913. return self.name
  914. def setName(self, name):
  915. self.name = name
  916. try:
  917. from _thread import (_excepthook as excepthook,
  918. _ExceptHookArgs as ExceptHookArgs)
  919. except ImportError:
  920. # Simple Python implementation if _thread._excepthook() is not available
  921. from traceback import print_exception as _print_exception
  922. from collections import namedtuple
  923. _ExceptHookArgs = namedtuple(
  924. 'ExceptHookArgs',
  925. 'exc_type exc_value exc_traceback thread')
  926. def ExceptHookArgs(args):
  927. return _ExceptHookArgs(*args)
  928. def excepthook(args, /):
  929. """
  930. Handle uncaught Thread.run() exception.
  931. """
  932. if args.exc_type == SystemExit:
  933. # silently ignore SystemExit
  934. return
  935. if _sys is not None and _sys.stderr is not None:
  936. stderr = _sys.stderr
  937. elif args.thread is not None:
  938. stderr = args.thread._stderr
  939. if stderr is None:
  940. # do nothing if sys.stderr is None and sys.stderr was None
  941. # when the thread was created
  942. return
  943. else:
  944. # do nothing if sys.stderr is None and args.thread is None
  945. return
  946. if args.thread is not None:
  947. name = args.thread.name
  948. else:
  949. name = get_ident()
  950. print(f"Exception in thread {name}:",
  951. file=stderr, flush=True)
  952. _print_exception(args.exc_type, args.exc_value, args.exc_traceback,
  953. file=stderr)
  954. stderr.flush()
  955. def _make_invoke_excepthook():
  956. # Create a local namespace to ensure that variables remain alive
  957. # when _invoke_excepthook() is called, even if it is called late during
  958. # Python shutdown. It is mostly needed for daemon threads.
  959. old_excepthook = excepthook
  960. old_sys_excepthook = _sys.excepthook
  961. if old_excepthook is None:
  962. raise RuntimeError("threading.excepthook is None")
  963. if old_sys_excepthook is None:
  964. raise RuntimeError("sys.excepthook is None")
  965. sys_exc_info = _sys.exc_info
  966. local_print = print
  967. local_sys = _sys
  968. def invoke_excepthook(thread):
  969. global excepthook
  970. try:
  971. hook = excepthook
  972. if hook is None:
  973. hook = old_excepthook
  974. args = ExceptHookArgs([*sys_exc_info(), thread])
  975. hook(args)
  976. except Exception as exc:
  977. exc.__suppress_context__ = True
  978. del exc
  979. if local_sys is not None and local_sys.stderr is not None:
  980. stderr = local_sys.stderr
  981. else:
  982. stderr = thread._stderr
  983. local_print("Exception in threading.excepthook:",
  984. file=stderr, flush=True)
  985. if local_sys is not None and local_sys.excepthook is not None:
  986. sys_excepthook = local_sys.excepthook
  987. else:
  988. sys_excepthook = old_sys_excepthook
  989. sys_excepthook(*sys_exc_info())
  990. finally:
  991. # Break reference cycle (exception stored in a variable)
  992. args = None
  993. return invoke_excepthook
  994. # The timer class was contributed by Itamar Shtull-Trauring
  995. class Timer(Thread):
  996. """Call a function after a specified number of seconds:
  997. t = Timer(30.0, f, args=None, kwargs=None)
  998. t.start()
  999. t.cancel() # stop the timer's action if it's still waiting
  1000. """
  1001. def __init__(self, interval, function, args=None, kwargs=None):
  1002. Thread.__init__(self)
  1003. self.interval = interval
  1004. self.function = function
  1005. self.args = args if args is not None else []
  1006. self.kwargs = kwargs if kwargs is not None else {}
  1007. self.finished = Event()
  1008. def cancel(self):
  1009. """Stop the timer if it hasn't finished yet."""
  1010. self.finished.set()
  1011. def run(self):
  1012. self.finished.wait(self.interval)
  1013. if not self.finished.is_set():
  1014. self.function(*self.args, **self.kwargs)
  1015. self.finished.set()
  1016. # Special thread class to represent the main thread
  1017. class _MainThread(Thread):
  1018. def __init__(self):
  1019. Thread.__init__(self, name="MainThread", daemon=False)
  1020. self._set_tstate_lock()
  1021. self._started.set()
  1022. self._set_ident()
  1023. if _HAVE_THREAD_NATIVE_ID:
  1024. self._set_native_id()
  1025. with _active_limbo_lock:
  1026. _active[self._ident] = self
  1027. # Dummy thread class to represent threads not started here.
  1028. # These aren't garbage collected when they die, nor can they be waited for.
  1029. # If they invoke anything in threading.py that calls current_thread(), they
  1030. # leave an entry in the _active dict forever after.
  1031. # Their purpose is to return *something* from current_thread().
  1032. # They are marked as daemon threads so we won't wait for them
  1033. # when we exit (conform previous semantics).
  1034. class _DummyThread(Thread):
  1035. def __init__(self):
  1036. Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
  1037. self._started.set()
  1038. self._set_ident()
  1039. if _HAVE_THREAD_NATIVE_ID:
  1040. self._set_native_id()
  1041. with _active_limbo_lock:
  1042. _active[self._ident] = self
  1043. def _stop(self):
  1044. pass
  1045. def is_alive(self):
  1046. assert not self._is_stopped and self._started.is_set()
  1047. return True
  1048. def join(self, timeout=None):
  1049. assert False, "cannot join a dummy thread"
  1050. # Global API functions
  1051. def current_thread():
  1052. """Return the current Thread object, corresponding to the caller's thread of control.
  1053. If the caller's thread of control was not created through the threading
  1054. module, a dummy thread object with limited functionality is returned.
  1055. """
  1056. try:
  1057. return _active[get_ident()]
  1058. except KeyError:
  1059. return _DummyThread()
  1060. currentThread = current_thread
  1061. def active_count():
  1062. """Return the number of Thread objects currently alive.
  1063. The returned count is equal to the length of the list returned by
  1064. enumerate().
  1065. """
  1066. with _active_limbo_lock:
  1067. return len(_active) + len(_limbo)
  1068. activeCount = active_count
  1069. def _enumerate():
  1070. # Same as enumerate(), but without the lock. Internal use only.
  1071. return list(_active.values()) + list(_limbo.values())
  1072. def enumerate():
  1073. """Return a list of all Thread objects currently alive.
  1074. The list includes daemonic threads, dummy thread objects created by
  1075. current_thread(), and the main thread. It excludes terminated threads and
  1076. threads that have not yet been started.
  1077. """
  1078. with _active_limbo_lock:
  1079. return list(_active.values()) + list(_limbo.values())
  1080. from _thread import stack_size
  1081. # Create the main thread object,
  1082. # and make it available for the interpreter
  1083. # (Py_Main) as threading._shutdown.
  1084. _main_thread = _MainThread()
  1085. def _shutdown():
  1086. """
  1087. Wait until the Python thread state of all non-daemon threads get deleted.
  1088. """
  1089. # Obscure: other threads may be waiting to join _main_thread. That's
  1090. # dubious, but some code does it. We can't wait for C code to release
  1091. # the main thread's tstate_lock - that won't happen until the interpreter
  1092. # is nearly dead. So we release it here. Note that just calling _stop()
  1093. # isn't enough: other threads may already be waiting on _tstate_lock.
  1094. if _main_thread._is_stopped:
  1095. # _shutdown() was already called
  1096. return
  1097. # Main thread
  1098. tlock = _main_thread._tstate_lock
  1099. # The main thread isn't finished yet, so its thread state lock can't have
  1100. # been released.
  1101. assert tlock is not None
  1102. assert tlock.locked()
  1103. tlock.release()
  1104. _main_thread._stop()
  1105. # Join all non-deamon threads
  1106. while True:
  1107. with _shutdown_locks_lock:
  1108. locks = list(_shutdown_locks)
  1109. _shutdown_locks.clear()
  1110. if not locks:
  1111. break
  1112. for lock in locks:
  1113. # mimick Thread.join()
  1114. lock.acquire()
  1115. lock.release()
  1116. # new threads can be spawned while we were waiting for the other
  1117. # threads to complete
  1118. def main_thread():
  1119. """Return the main thread object.
  1120. In normal conditions, the main thread is the thread from which the
  1121. Python interpreter was started.
  1122. """
  1123. return _main_thread
  1124. # get thread-local implementation, either from the thread
  1125. # module, or from the python fallback
  1126. try:
  1127. from _thread import _local as local
  1128. except ImportError:
  1129. from _threading_local import local
  1130. def _after_fork():
  1131. """
  1132. Cleanup threading module state that should not exist after a fork.
  1133. """
  1134. # Reset _active_limbo_lock, in case we forked while the lock was held
  1135. # by another (non-forked) thread. http://bugs.python.org/issue874900
  1136. global _active_limbo_lock, _main_thread
  1137. global _shutdown_locks_lock, _shutdown_locks
  1138. _active_limbo_lock = _allocate_lock()
  1139. # fork() only copied the current thread; clear references to others.
  1140. new_active = {}
  1141. try:
  1142. current = _active[get_ident()]
  1143. except KeyError:
  1144. # fork() was called in a thread which was not spawned
  1145. # by threading.Thread. For example, a thread spawned
  1146. # by thread.start_new_thread().
  1147. current = _MainThread()
  1148. _main_thread = current
  1149. # reset _shutdown() locks: threads re-register their _tstate_lock below
  1150. _shutdown_locks_lock = _allocate_lock()
  1151. _shutdown_locks = set()
  1152. with _active_limbo_lock:
  1153. # Dangling thread instances must still have their locks reset,
  1154. # because someone may join() them.
  1155. threads = set(_enumerate())
  1156. threads.update(_dangling)
  1157. for thread in threads:
  1158. # Any lock/condition variable may be currently locked or in an
  1159. # invalid state, so we reinitialize them.
  1160. if thread is current:
  1161. # There is only one active thread. We reset the ident to
  1162. # its new value since it can have changed.
  1163. thread._reset_internal_locks(True)
  1164. ident = get_ident()
  1165. thread._ident = ident
  1166. new_active[ident] = thread
  1167. else:
  1168. # All the others are already stopped.
  1169. thread._reset_internal_locks(False)
  1170. thread._stop()
  1171. _limbo.clear()
  1172. _active.clear()
  1173. _active.update(new_active)
  1174. assert len(_active) == 1
  1175. if hasattr(_os, "register_at_fork"):
  1176. _os.register_at_fork(after_in_child=_after_fork)