logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

threading.py (55961B)


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