Debian Codegraph @

lib-python/3/threading.py

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