Debian Codegraph @

Lib/test/test_threading.py

raw
1 """
2 Tests for the threading module.
3 """
4
5 import test.support
6 from test.support import threading_helper, requires_subprocess, requires_gil_enabled
7 from test.support import verbose, cpython_only, os_helper
8 from test.support.import_helper import import_module
9 from test.support.script_helper import assert_python_ok, assert_python_failure
10 from test.support import force_not_colorized
11
12 import random
13 import sys
14 import _thread
15 import threading
16 import time
17 import unittest
18 import weakref
19 import os
20 import subprocess
21 import signal
22 import textwrap
23 import traceback
24 import warnings
25
26 from unittest import mock
27 from test import lock_tests
28 from test import support
29
30 try:
31 from test.support import interpreters
32 except ImportError:
33 interpreters = None
34
35 threading_helper.requires_working_threading(module=True)
36
37 # Between fork() and exec(), only async-safe functions are allowed (issues
38 # #12316 and #11870), and fork() from a worker thread is known to trigger
39 # problems with some operating systems (issue #3863): skip problematic tests
40 # on platforms known to behave badly.
41 platforms_to_skip = ('netbsd5', 'hp-ux11')
42
43
44 def skip_unless_reliable_fork(test):
45 if not support.has_fork_support:
46 return unittest.skip("requires working os.fork()")(test)
47 if sys.platform in platforms_to_skip:
48 return unittest.skip("due to known OS bug related to thread+fork")(test)
49 if support.HAVE_ASAN_FORK_BUG:
50 return unittest.skip("libasan has a pthread_create() dead lock related to thread+fork")(test)
51 if support.check_sanitizer(thread=True):
52 return unittest.skip("TSAN doesn't support threads after fork")(test)
53 return test
54
55
56 def requires_subinterpreters(meth):
57 """Decorator to skip a test if subinterpreters are not supported."""
58 return unittest.skipIf(interpreters is None,
59 'subinterpreters required')(meth)
60
61
62 def restore_default_excepthook(testcase):
63 testcase.addCleanup(setattr, threading, 'excepthook', threading.excepthook)
64 threading.excepthook = threading.__excepthook__
65
66
67 # A trivial mutable counter.
68 class Counter(object):
69 def __init__(self):
70 self.value = 0
71 def inc(self):
72 self.value += 1
73 def dec(self):
74 self.value -= 1
75 def get(self):
76 return self.value
77
78 class TestThread(threading.Thread):
79 def __init__(self, name, testcase, sema, mutex, nrunning):
80 threading.Thread.__init__(self, name=name)
81 self.testcase = testcase
82 self.sema = sema
83 self.mutex = mutex
84 self.nrunning = nrunning
85
86 def run(self):
87 delay = random.random() / 10000.0
88 if verbose:
89 print('task %s will run for %.1f usec' %
90 (self.name, delay * 1e6))
91
92 with self.sema:
93 with self.mutex:
94 self.nrunning.inc()
95 if verbose:
96 print(self.nrunning.get(), 'tasks are running')
97 self.testcase.assertLessEqual(self.nrunning.get(), 3)
98
99 time.sleep(delay)
100 if verbose:
101 print('task', self.name, 'done')
102
103 with self.mutex:
104 self.nrunning.dec()
105 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
106 if verbose:
107 print('%s is finished. %d tasks are running' %
108 (self.name, self.nrunning.get()))
109
110
111 class BaseTestCase(unittest.TestCase):
112 def setUp(self):
113 self._threads = threading_helper.threading_setup()
114
115 def tearDown(self):
116 threading_helper.threading_cleanup(*self._threads)
117 test.support.reap_children()
118
119
120 class ThreadTests(BaseTestCase):
121 maxDiff = 9999
122
123 @cpython_only
124 def test_name(self):
125 def func(): pass
126
127 thread = threading.Thread(name="myname1")
128 self.assertEqual(thread.name, "myname1")
129
130 # Convert int name to str
131 thread = threading.Thread(name=123)
132 self.assertEqual(thread.name, "123")
133
134 # target name is ignored if name is specified
135 thread = threading.Thread(target=func, name="myname2")
136 self.assertEqual(thread.name, "myname2")
137
138 with mock.patch.object(threading, '_counter', return_value=2):
139 thread = threading.Thread(name="")
140 self.assertEqual(thread.name, "Thread-2")
141
142 with mock.patch.object(threading, '_counter', return_value=3):
143 thread = threading.Thread()
144 self.assertEqual(thread.name, "Thread-3")
145
146 with mock.patch.object(threading, '_counter', return_value=5):
147 thread = threading.Thread(target=func)
148 self.assertEqual(thread.name, "Thread-5 (func)")
149
150 def test_args_argument(self):
151 # bpo-45735: Using list or tuple as *args* in constructor could
152 # achieve the same effect.
153 num_list = [1]
154 num_tuple = (1,)
155
156 str_list = ["str"]
157 str_tuple = ("str",)
158
159 list_in_tuple = ([1],)
160 tuple_in_list = [(1,)]
161
162 test_cases = (
163 (num_list, lambda arg: self.assertEqual(arg, 1)),
164 (num_tuple, lambda arg: self.assertEqual(arg, 1)),
165 (str_list, lambda arg: self.assertEqual(arg, "str")),
166 (str_tuple, lambda arg: self.assertEqual(arg, "str")),
167 (list_in_tuple, lambda arg: self.assertEqual(arg, [1])),
168 (tuple_in_list, lambda arg: self.assertEqual(arg, (1,)))
169 )
170
171 for args, target in test_cases:
172 with self.subTest(target=target, args=args):
173 t = threading.Thread(target=target, args=args)
174 t.start()
175 t.join()
176
177 def test_lock_no_args(self):
178 threading.Lock() # works
179 self.assertRaises(TypeError, threading.Lock, 1)
180 self.assertRaises(TypeError, threading.Lock, a=1)
181 self.assertRaises(TypeError, threading.Lock, 1, 2, a=1, b=2)
182
183 def test_lock_no_subclass(self):
184 # Intentionally disallow subclasses of threading.Lock because they have
185 # never been allowed, so why start now just because the type is public?
186 with self.assertRaises(TypeError):
187 class MyLock(threading.Lock): pass
188
189 def test_lock_or_none(self):
190 import types
191 self.assertIsInstance(threading.Lock | None, types.UnionType)
192
193 # Create a bunch of threads, let each do some work, wait until all are
194 # done.
195 def test_various_ops(self):
196 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
197 # times about 1 second per clump).
198 NUMTASKS = 10
199
200 # no more than 3 of the 10 can run at once
201 sema = threading.BoundedSemaphore(value=3)
202 mutex = threading.RLock()
203 numrunning = Counter()
204
205 threads = []
206
207 for i in range(NUMTASKS):
208 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
209 threads.append(t)
210 self.assertIsNone(t.ident)
211 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
212 t.start()
213
214 if hasattr(threading, 'get_native_id'):
215 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
216 self.assertNotIn(None, native_ids)
217 self.assertEqual(len(native_ids), NUMTASKS + 1)
218
219 if verbose:
220 print('waiting for all tasks to complete')
221 for t in threads:
222 t.join()
223 self.assertFalse(t.is_alive())
224 self.assertNotEqual(t.ident, 0)
225 self.assertIsNotNone(t.ident)
226 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
227 if verbose:
228 print('all tasks done')
229 self.assertEqual(numrunning.get(), 0)
230
231 def test_ident_of_no_threading_threads(self):
232 # The ident still must work for the main thread and dummy threads.
233 self.assertIsNotNone(threading.current_thread().ident)
234 def f():
235 ident.append(threading.current_thread().ident)
236 done.set()
237 done = threading.Event()
238 ident = []
239 with threading_helper.wait_threads_exit():
240 tid = _thread.start_new_thread(f, ())
241 done.wait()
242 self.assertEqual(ident[0], tid)
243
244 # run with a small(ish) thread stack size (256 KiB)
245 def test_various_ops_small_stack(self):
246 if verbose:
247 print('with 256 KiB thread stack size...')
248 try:
249 threading.stack_size(262144)
250 except _thread.error:
251 raise unittest.SkipTest(
252 'platform does not support changing thread stack size')
253 self.test_various_ops()
254 threading.stack_size(0)
255
256 # run with a large thread stack size (1 MiB)
257 def test_various_ops_large_stack(self):
258 if verbose:
259 print('with 1 MiB thread stack size...')
260 try:
261 threading.stack_size(0x100000)
262 except _thread.error:
263 raise unittest.SkipTest(
264 'platform does not support changing thread stack size')
265 self.test_various_ops()
266 threading.stack_size(0)
267
268 def test_foreign_thread(self):
269 # Check that a "foreign" thread can use the threading module.
270 dummy_thread = None
271 error = None
272 def f(mutex):
273 try:
274 nonlocal dummy_thread
275 nonlocal error
276 # Calling current_thread() forces an entry for the foreign
277 # thread to get made in the threading._active map.
278 dummy_thread = threading.current_thread()
279 tid = dummy_thread.ident
280 self.assertIn(tid, threading._active)
281 self.assertIsInstance(dummy_thread, threading._DummyThread)
282 self.assertIs(threading._active.get(tid), dummy_thread)
283 # gh-29376
284 self.assertTrue(
285 dummy_thread.is_alive(),
286 'Expected _DummyThread to be considered alive.'
287 )
288 self.assertIn('_DummyThread', repr(dummy_thread))
289 except BaseException as e:
290 error = e
291 finally:
292 mutex.release()
293
294 mutex = threading.Lock()
295 mutex.acquire()
296 with threading_helper.wait_threads_exit():
297 tid = _thread.start_new_thread(f, (mutex,))
298 # Wait for the thread to finish.
299 mutex.acquire()
300 if error is not None:
301 raise error
302 self.assertEqual(tid, dummy_thread.ident)
303 # Issue gh-106236:
304 with self.assertRaises(RuntimeError):
305 dummy_thread.join()
306 dummy_thread._started.clear()
307 with self.assertRaises(RuntimeError):
308 dummy_thread.is_alive()
309 # Busy wait for the following condition: after the thread dies, the
310 # related dummy thread must be removed from threading._active.
311 timeout = 5
312 timeout_at = time.monotonic() + timeout
313 while time.monotonic() < timeout_at:
314 if threading._active.get(dummy_thread.ident) is not dummy_thread:
315 break
316 time.sleep(.1)
317 else:
318 self.fail('It was expected that the created threading._DummyThread was removed from threading._active.')
319
320 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
321 # exposed at the Python level. This test relies on ctypes to get at it.
322 def test_PyThreadState_SetAsyncExc(self):
323 ctypes = import_module("ctypes")
324
325 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
326 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
327
328 class AsyncExc(Exception):
329 pass
330
331 exception = ctypes.py_object(AsyncExc)
332
333 # First check it works when setting the exception from the same thread.
334 tid = threading.get_ident()
335 self.assertIsInstance(tid, int)
336 self.assertGreater(tid, 0)
337
338 try:
339 result = set_async_exc(tid, exception)
340 # The exception is async, so we might have to keep the VM busy until
341 # it notices.
342 while True:
343 pass
344 except AsyncExc:
345 pass
346 else:
347 # This code is unreachable but it reflects the intent. If we wanted
348 # to be smarter the above loop wouldn't be infinite.
349 self.fail("AsyncExc not raised")
350 try:
351 self.assertEqual(result, 1) # one thread state modified
352 except UnboundLocalError:
353 # The exception was raised too quickly for us to get the result.
354 pass
355
356 # `worker_started` is set by the thread when it's inside a try/except
357 # block waiting to catch the asynchronously set AsyncExc exception.
358 # `worker_saw_exception` is set by the thread upon catching that
359 # exception.
360 worker_started = threading.Event()
361 worker_saw_exception = threading.Event()
362
363 class Worker(threading.Thread):
364 def run(self):
365 self.id = threading.get_ident()
366 self.finished = False
367
368 try:
369 while True:
370 worker_started.set()
371 time.sleep(0.1)
372 except AsyncExc:
373 self.finished = True
374 worker_saw_exception.set()
375
376 t = Worker()
377 t.daemon = True # so if this fails, we don't hang Python at shutdown
378 t.start()
379 if verbose:
380 print(" started worker thread")
381
382 # Try a thread id that doesn't make sense.
383 if verbose:
384 print(" trying nonsensical thread id")
385 result = set_async_exc(-1, exception)
386 self.assertEqual(result, 0) # no thread states modified
387
388 # Now raise an exception in the worker thread.
389 if verbose:
390 print(" waiting for worker thread to get started")
391 ret = worker_started.wait()
392 self.assertTrue(ret)
393 if verbose:
394 print(" verifying worker hasn't exited")
395 self.assertFalse(t.finished)
396 if verbose:
397 print(" attempting to raise asynch exception in worker")
398 result = set_async_exc(t.id, exception)
399 self.assertEqual(result, 1) # one thread state modified
400 if verbose:
401 print(" waiting for worker to say it caught the exception")
402 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
403 self.assertTrue(t.finished)
404 if verbose:
405 print(" all OK -- joining worker")
406 if t.finished:
407 t.join()
408 # else the thread is still running, and we have no way to kill it
409
410 def test_limbo_cleanup(self):
411 # Issue 7481: Failure to start thread should cleanup the limbo map.
412 def fail_new_thread(*args, **kwargs):
413 raise threading.ThreadError()
414 _start_joinable_thread = threading._start_joinable_thread
415 threading._start_joinable_thread = fail_new_thread
416 try:
417 t = threading.Thread(target=lambda: None)
418 self.assertRaises(threading.ThreadError, t.start)
419 self.assertFalse(
420 t in threading._limbo,
421 "Failed to cleanup _limbo map on failure of Thread.start().")
422 finally:
423 threading._start_joinable_thread = _start_joinable_thread
424
425 def test_finalize_running_thread(self):
426 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
427 # very late on python exit: on deallocation of a running thread for
428 # example.
429 if support.check_sanitizer(thread=True):
430 # the thread running `time.sleep(100)` below will still be alive
431 # at process exit
432 self.skipTest("TSAN would report thread leak")
433 import_module("ctypes")
434
435 rc, out, err = assert_python_failure("-c", """if 1:
436 import ctypes, sys, time, _thread
437
438 # This lock is used as a simple event variable.
439 ready = _thread.allocate_lock()
440 ready.acquire()
441
442 # Module globals are cleared before __del__ is run
443 # So we save the functions in class dict
444 class C:
445 ensure = ctypes.pythonapi.PyGILState_Ensure
446 release = ctypes.pythonapi.PyGILState_Release
447 def __del__(self):
448 state = self.ensure()
449 self.release(state)
450
451 def waitingThread():
452 x = C()
453 ready.release()
454 time.sleep(100)
455
456 _thread.start_new_thread(waitingThread, ())
457 ready.acquire() # Be sure the other thread is waiting.
458 sys.exit(42)
459 """)
460 self.assertEqual(rc, 42)
461
462 def test_finalize_with_trace(self):
463 # Issue1733757
464 # Avoid a deadlock when sys.settrace steps into threading._shutdown
465 if support.check_sanitizer(thread=True):
466 # the thread running `time.sleep(2)` below will still be alive
467 # at process exit
468 self.skipTest("TSAN would report thread leak")
469
470 assert_python_ok("-c", """if 1:
471 import sys, threading
472
473 # A deadlock-killer, to prevent the
474 # testsuite to hang forever
475 def killer():
476 import os, time
477 time.sleep(2)
478 print('program blocked; aborting')
479 os._exit(2)
480 t = threading.Thread(target=killer)
481 t.daemon = True
482 t.start()
483
484 # This is the trace function
485 def func(frame, event, arg):
486 threading.current_thread()
487 return func
488
489 sys.settrace(func)
490 """)
491
492 def test_join_nondaemon_on_shutdown(self):
493 # Issue 1722344
494 # Raising SystemExit skipped threading._shutdown
495 rc, out, err = assert_python_ok("-c", """if 1:
496 import threading
497 from time import sleep
498
499 def child():
500 sleep(1)
501 # As a non-daemon thread we SHOULD wake up and nothing
502 # should be torn down yet
503 print("Woke up, sleep function is:", sleep)
504
505 threading.Thread(target=child).start()
506 raise SystemExit
507 """)
508 self.assertEqual(out.strip(),
509 b"Woke up, sleep function is: <built-in function sleep>")
510 self.assertEqual(err, b"")
511
512 def test_enumerate_after_join(self):
513 # Try hard to trigger #1703448: a thread is still returned in
514 # threading.enumerate() after it has been join()ed.
515 enum = threading.enumerate
516 old_interval = sys.getswitchinterval()
517 try:
518 for i in range(1, 100):
519 support.setswitchinterval(i * 0.0002)
520 t = threading.Thread(target=lambda: None)
521 t.start()
522 t.join()
523 l = enum()
524 self.assertNotIn(t, l,
525 "#1703448 triggered after %d trials: %s" % (i, l))
526 finally:
527 sys.setswitchinterval(old_interval)
528
529 @support.bigmemtest(size=20, memuse=72*2**20, dry_run=False)
530 def test_join_from_multiple_threads(self, size):
531 # Thread.join() should be thread-safe
532 errors = []
533
534 def worker():
535 time.sleep(0.005)
536
537 def joiner(thread):
538 try:
539 thread.join()
540 except Exception as e:
541 errors.append(e)
542
543 for N in range(2, 20):
544 threads = [threading.Thread(target=worker)]
545 for i in range(N):
546 threads.append(threading.Thread(target=joiner,
547 args=(threads[0],)))
548 for t in threads:
549 t.start()
550 time.sleep(0.01)
551 for t in threads:
552 t.join()
553 if errors:
554 raise errors[0]
555
556 def test_join_with_timeout(self):
557 lock = _thread.allocate_lock()
558 lock.acquire()
559
560 def worker():
561 lock.acquire()
562
563 thread = threading.Thread(target=worker)
564 thread.start()
565 thread.join(timeout=0.01)
566 assert thread.is_alive()
567 lock.release()
568 thread.join()
569 assert not thread.is_alive()
570
571 def test_no_refcycle_through_target(self):
572 class RunSelfFunction(object):
573 def __init__(self, should_raise):
574 # The links in this refcycle from Thread back to self
575 # should be cleaned up when the thread completes.
576 self.should_raise = should_raise
577 self.thread = threading.Thread(target=self._run,
578 args=(self,),
579 kwargs={'yet_another':self})
580 self.thread.start()
581
582 def _run(self, other_ref, yet_another):
583 if self.should_raise:
584 raise SystemExit
585
586 restore_default_excepthook(self)
587
588 cyclic_object = RunSelfFunction(should_raise=False)
589 weak_cyclic_object = weakref.ref(cyclic_object)
590 cyclic_object.thread.join()
591 del cyclic_object
592 self.assertIsNone(weak_cyclic_object(),
593 msg=('%d references still around' %
594 sys.getrefcount(weak_cyclic_object())))
595
596 raising_cyclic_object = RunSelfFunction(should_raise=True)
597 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
598 raising_cyclic_object.thread.join()
599 del raising_cyclic_object
600 self.assertIsNone(weak_raising_cyclic_object(),
601 msg=('%d references still around' %
602 sys.getrefcount(weak_raising_cyclic_object())))
603
604 def test_old_threading_api(self):
605 # Just a quick sanity check to make sure the old method names are
606 # still present
607 t = threading.Thread()
608 with self.assertWarnsRegex(DeprecationWarning,
609 r'get the daemon attribute'):
610 t.isDaemon()
611 with self.assertWarnsRegex(DeprecationWarning,
612 r'set the daemon attribute'):
613 t.setDaemon(True)
614 with self.assertWarnsRegex(DeprecationWarning,
615 r'get the name attribute'):
616 t.getName()
617 with self.assertWarnsRegex(DeprecationWarning,
618 r'set the name attribute'):
619 t.setName("name")
620
621 e = threading.Event()
622 with self.assertWarnsRegex(DeprecationWarning, 'use is_set()'):
623 e.isSet()
624
625 cond = threading.Condition()
626 cond.acquire()
627 with self.assertWarnsRegex(DeprecationWarning, 'use notify_all()'):
628 cond.notifyAll()
629
630 with self.assertWarnsRegex(DeprecationWarning, 'use active_count()'):
631 threading.activeCount()
632 with self.assertWarnsRegex(DeprecationWarning, 'use current_thread()'):
633 threading.currentThread()
634
635 def test_repr_daemon(self):
636 t = threading.Thread()
637 self.assertNotIn('daemon', repr(t))
638 t.daemon = True
639 self.assertIn('daemon', repr(t))
640
641 def test_daemon_param(self):
642 t = threading.Thread()
643 self.assertFalse(t.daemon)
644 t = threading.Thread(daemon=False)
645 self.assertFalse(t.daemon)
646 t = threading.Thread(daemon=True)
647 self.assertTrue(t.daemon)
648
649 @skip_unless_reliable_fork
650 def test_dummy_thread_after_fork(self):
651 # Issue #14308: a dummy thread in the active list doesn't mess up
652 # the after-fork mechanism.
653 code = """if 1:
654 import _thread, threading, os, time, warnings
655
656 def background_thread(evt):
657 # Creates and registers the _DummyThread instance
658 threading.current_thread()
659 evt.set()
660 time.sleep(10)
661
662 evt = threading.Event()
663 _thread.start_new_thread(background_thread, (evt,))
664 evt.wait()
665 assert threading.active_count() == 2, threading.active_count()
666 with warnings.catch_warnings(record=True) as ws:
667 warnings.filterwarnings(
668 "always", category=DeprecationWarning)
669 if os.fork() == 0:
670 assert threading.active_count() == 1, threading.active_count()
671 os._exit(0)
672 else:
673 assert ws[0].category == DeprecationWarning, ws[0]
674 assert 'fork' in str(ws[0].message), ws[0]
675 os.wait()
676 """
677 _, out, err = assert_python_ok("-c", code)
678 self.assertEqual(out, b'')
679 self.assertEqual(err, b'')
680
681 @skip_unless_reliable_fork
682 def test_is_alive_after_fork(self):
683 # Try hard to trigger #18418: is_alive() could sometimes be True on
684 # threads that vanished after a fork.
685 old_interval = sys.getswitchinterval()
686 self.addCleanup(sys.setswitchinterval, old_interval)
687
688 # Make the bug more likely to manifest.
689 test.support.setswitchinterval(1e-6)
690
691 for i in range(20):
692 t = threading.Thread(target=lambda: None)
693 t.start()
694 # Ignore the warning about fork with threads.
695 with warnings.catch_warnings(category=DeprecationWarning,
696 action="ignore"):
697 if (pid := os.fork()) == 0:
698 os._exit(11 if t.is_alive() else 10)
699 else:
700 t.join()
701
702 support.wait_process(pid, exitcode=10)
703
704 def test_main_thread(self):
705 main = threading.main_thread()
706 self.assertEqual(main.name, 'MainThread')
707 self.assertEqual(main.ident, threading.current_thread().ident)
708 self.assertEqual(main.ident, threading.get_ident())
709
710 def f():
711 self.assertNotEqual(threading.main_thread().ident,
712 threading.current_thread().ident)
713 th = threading.Thread(target=f)
714 th.start()
715 th.join()
716
717 @skip_unless_reliable_fork
718 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
719 def test_main_thread_after_fork(self):
720 code = """if 1:
721 import os, threading
722 from test import support
723
724 ident = threading.get_ident()
725 pid = os.fork()
726 if pid == 0:
727 print("current ident", threading.get_ident() == ident)
728 main = threading.main_thread()
729 print("main", main.name)
730 print("main ident", main.ident == ident)
731 print("current is main", threading.current_thread() is main)
732 else:
733 support.wait_process(pid, exitcode=0)
734 """
735 _, out, err = assert_python_ok("-c", code)
736 data = out.decode().replace('\r', '')
737 self.assertEqual(err, b"")
738 self.assertEqual(data,
739 "current ident True\n"
740 "main MainThread\n"
741 "main ident True\n"
742 "current is main True\n")
743
744 @skip_unless_reliable_fork
745 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
746 def test_main_thread_after_fork_from_nonmain_thread(self):
747 code = """if 1:
748 import os, threading, sys, warnings
749 from test import support
750
751 def func():
752 ident = threading.get_ident()
753 with warnings.catch_warnings(record=True) as ws:
754 warnings.filterwarnings(
755 "always", category=DeprecationWarning)
756 pid = os.fork()
757 if pid == 0:
758 print("current ident", threading.get_ident() == ident)
759 main = threading.main_thread()
760 print("main", main.name, type(main).__name__)
761 print("main ident", main.ident == ident)
762 print("current is main", threading.current_thread() is main)
763 # stdout is fully buffered because not a tty,
764 # we have to flush before exit.
765 sys.stdout.flush()
766 else:
767 assert ws[0].category == DeprecationWarning, ws[0]
768 assert 'fork' in str(ws[0].message), ws[0]
769 support.wait_process(pid, exitcode=0)
770
771 th = threading.Thread(target=func)
772 th.start()
773 th.join()
774 """
775 _, out, err = assert_python_ok("-c", code)
776 data = out.decode().replace('\r', '')
777 self.assertEqual(err.decode('utf-8'), "")
778 self.assertEqual(data,
779 "current ident True\n"
780 "main Thread-1 (func) Thread\n"
781 "main ident True\n"
782 "current is main True\n"
783 )
784
785 @skip_unless_reliable_fork
786 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
787 def test_main_thread_after_fork_from_foreign_thread(self, create_dummy=False):
788 code = """if 1:
789 import os, threading, sys, traceback, _thread
790 from test import support
791
792 def func(lock):
793 ident = threading.get_ident()
794 if %s:
795 # call current_thread() before fork to allocate DummyThread
796 current = threading.current_thread()
797 print("current", current.name, type(current).__name__)
798 print("ident in _active", ident in threading._active)
799 # flush before fork, so child won't flush it again
800 sys.stdout.flush()
801 pid = os.fork()
802 if pid == 0:
803 print("current ident", threading.get_ident() == ident)
804 main = threading.main_thread()
805 print("main", main.name, type(main).__name__)
806 print("main ident", main.ident == ident)
807 print("current is main", threading.current_thread() is main)
808 print("_dangling", [t.name for t in list(threading._dangling)])
809 # stdout is fully buffered because not a tty,
810 # we have to flush before exit.
811 sys.stdout.flush()
812 try:
813 threading._shutdown()
814 os._exit(0)
815 except:
816 traceback.print_exc()
817 sys.stderr.flush()
818 os._exit(1)
819 else:
820 try:
821 support.wait_process(pid, exitcode=0)
822 except Exception:
823 # avoid 'could not acquire lock for
824 # <_io.BufferedWriter name='<stderr>'> at interpreter shutdown,'
825 traceback.print_exc()
826 sys.stderr.flush()
827 finally:
828 lock.release()
829
830 join_lock = _thread.allocate_lock()
831 join_lock.acquire()
832 th = _thread.start_new_thread(func, (join_lock,))
833 join_lock.acquire()
834 """ % create_dummy
835 # "DeprecationWarning: This process is multi-threaded, use of fork()
836 # may lead to deadlocks in the child"
837 _, out, err = assert_python_ok("-W", "ignore::DeprecationWarning", "-c", code)
838 data = out.decode().replace('\r', '')
839 self.assertEqual(err.decode(), "")
840 self.assertEqual(data,
841 ("current Dummy-1 _DummyThread\n" if create_dummy else "") +
842 f"ident in _active {create_dummy!s}\n" +
843 "current ident True\n"
844 "main MainThread _MainThread\n"
845 "main ident True\n"
846 "current is main True\n"
847 "_dangling ['MainThread']\n")
848
849 def test_main_thread_after_fork_from_dummy_thread(self, create_dummy=False):
850 self.test_main_thread_after_fork_from_foreign_thread(create_dummy=True)
851
852 def test_main_thread_during_shutdown(self):
853 # bpo-31516: current_thread() should still point to the main thread
854 # at shutdown
855 code = """if 1:
856 import gc, threading
857
858 main_thread = threading.current_thread()
859 assert main_thread is threading.main_thread() # sanity check
860
861 class RefCycle:
862 def __init__(self):
863 self.cycle = self
864
865 def __del__(self):
866 print("GC:",
867 threading.current_thread() is main_thread,
868 threading.main_thread() is main_thread,
869 threading.enumerate() == [main_thread])
870
871 RefCycle()
872 gc.collect() # sanity check
873 x = RefCycle()
874 """
875 _, out, err = assert_python_ok("-c", code)
876 data = out.decode()
877 self.assertEqual(err, b"")
878 self.assertEqual(data.splitlines(),
879 ["GC: True True True"] * 2)
880
881 def test_finalization_shutdown(self):
882 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
883 # until Python thread states of all non-daemon threads get deleted.
884 #
885 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
886 # test the finalization of the main interpreter.
887 code = """if 1:
888 import os
889 import threading
890 import time
891 import random
892
893 def random_sleep():
894 seconds = random.random() * 0.010
895 time.sleep(seconds)
896
897 class Sleeper:
898 def __del__(self):
899 random_sleep()
900
901 tls = threading.local()
902
903 def f():
904 # Sleep a bit so that the thread is still running when
905 # Py_Finalize() is called.
906 random_sleep()
907 tls.x = Sleeper()
908 random_sleep()
909
910 threading.Thread(target=f).start()
911 random_sleep()
912 """
913 rc, out, err = assert_python_ok("-c", code)
914 self.assertEqual(err, b"")
915
916 def test_repr_stopped(self):
917 # Verify that "stopped" shows up in repr(Thread) appropriately.
918 started = _thread.allocate_lock()
919 finish = _thread.allocate_lock()
920 started.acquire()
921 finish.acquire()
922 def f():
923 started.release()
924 finish.acquire()
925 t = threading.Thread(target=f)
926 t.start()
927 started.acquire()
928 self.assertIn("started", repr(t))
929 finish.release()
930 # "stopped" should appear in the repr in a reasonable amount of time.
931 # Implementation detail: as of this writing, that's trivially true
932 # if .join() is called, and almost trivially true if .is_alive() is
933 # called. The detail we're testing here is that "stopped" shows up
934 # "all on its own".
935 LOOKING_FOR = "stopped"
936 for i in range(500):
937 if LOOKING_FOR in repr(t):
938 break
939 time.sleep(0.01)
940 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
941 t.join()
942
943 def test_BoundedSemaphore_limit(self):
944 # BoundedSemaphore should raise ValueError if released too often.
945 for limit in range(1, 10):
946 bs = threading.BoundedSemaphore(limit)
947 threads = [threading.Thread(target=bs.acquire)
948 for _ in range(limit)]
949 for t in threads:
950 t.start()
951 for t in threads:
952 t.join()
953 threads = [threading.Thread(target=bs.release)
954 for _ in range(limit)]
955 for t in threads:
956 t.start()
957 for t in threads:
958 t.join()
959 self.assertRaises(ValueError, bs.release)
960
961 @cpython_only
962 def test_frame_tstate_tracing(self):
963 _testcapi = import_module("_testcapi")
964 # Issue #14432: Crash when a generator is created in a C thread that is
965 # destroyed while the generator is still used. The issue was that a
966 # generator contains a frame, and the frame kept a reference to the
967 # Python state of the destroyed C thread. The crash occurs when a trace
968 # function is setup.
969
970 def noop_trace(frame, event, arg):
971 # no operation
972 return noop_trace
973
974 def generator():
975 while 1:
976 yield "generator"
977
978 def callback():
979 if callback.gen is None:
980 callback.gen = generator()
981 return next(callback.gen)
982 callback.gen = None
983
984 old_trace = sys.gettrace()
985 sys.settrace(noop_trace)
986 try:
987 # Install a trace function
988 threading.settrace(noop_trace)
989
990 # Create a generator in a C thread which exits after the call
991 _testcapi.call_in_temporary_c_thread(callback)
992
993 # Call the generator in a different Python thread, check that the
994 # generator didn't keep a reference to the destroyed thread state
995 for test in range(3):
996 # The trace function is still called here
997 callback()
998 finally:
999 sys.settrace(old_trace)
1000 threading.settrace(old_trace)
1001
1002 def test_gettrace(self):
1003 def noop_trace(frame, event, arg):
1004 # no operation
1005 return noop_trace
1006 old_trace = threading.gettrace()
1007 try:
1008 threading.settrace(noop_trace)
1009 trace_func = threading.gettrace()
1010 self.assertEqual(noop_trace,trace_func)
1011 finally:
1012 threading.settrace(old_trace)
1013
1014 def test_gettrace_all_threads(self):
1015 def fn(*args): pass
1016 old_trace = threading.gettrace()
1017 first_check = threading.Event()
1018 second_check = threading.Event()
1019
1020 trace_funcs = []
1021 def checker():
1022 trace_funcs.append(sys.gettrace())
1023 first_check.set()
1024 second_check.wait()
1025 trace_funcs.append(sys.gettrace())
1026
1027 try:
1028 t = threading.Thread(target=checker)
1029 t.start()
1030 first_check.wait()
1031 threading.settrace_all_threads(fn)
1032 second_check.set()
1033 t.join()
1034 self.assertEqual(trace_funcs, [None, fn])
1035 self.assertEqual(threading.gettrace(), fn)
1036 self.assertEqual(sys.gettrace(), fn)
1037 finally:
1038 threading.settrace_all_threads(old_trace)
1039
1040 self.assertEqual(threading.gettrace(), old_trace)
1041 self.assertEqual(sys.gettrace(), old_trace)
1042
1043 def test_getprofile(self):
1044 def fn(*args): pass
1045 old_profile = threading.getprofile()
1046 try:
1047 threading.setprofile(fn)
1048 self.assertEqual(fn, threading.getprofile())
1049 finally:
1050 threading.setprofile(old_profile)
1051
1052 def test_getprofile_all_threads(self):
1053 def fn(*args): pass
1054 old_profile = threading.getprofile()
1055 first_check = threading.Event()
1056 second_check = threading.Event()
1057
1058 profile_funcs = []
1059 def checker():
1060 profile_funcs.append(sys.getprofile())
1061 first_check.set()
1062 second_check.wait()
1063 profile_funcs.append(sys.getprofile())
1064
1065 try:
1066 t = threading.Thread(target=checker)
1067 t.start()
1068 first_check.wait()
1069 threading.setprofile_all_threads(fn)
1070 second_check.set()
1071 t.join()
1072 self.assertEqual(profile_funcs, [None, fn])
1073 self.assertEqual(threading.getprofile(), fn)
1074 self.assertEqual(sys.getprofile(), fn)
1075 finally:
1076 threading.setprofile_all_threads(old_profile)
1077
1078 self.assertEqual(threading.getprofile(), old_profile)
1079 self.assertEqual(sys.getprofile(), old_profile)
1080
1081 def test_locals_at_exit(self):
1082 # bpo-19466: thread locals must not be deleted before destructors
1083 # are called
1084 rc, out, err = assert_python_ok("-c", """if 1:
1085 import threading
1086
1087 class Atexit:
1088 def __del__(self):
1089 print("thread_dict.atexit = %r" % thread_dict.atexit)
1090
1091 thread_dict = threading.local()
1092 thread_dict.atexit = "value"
1093
1094 atexit = Atexit()
1095 """)
1096 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
1097
1098 def test_boolean_target(self):
1099 # bpo-41149: A thread that had a boolean value of False would not
1100 # run, regardless of whether it was callable. The correct behaviour
1101 # is for a thread to do nothing if its target is None, and to call
1102 # the target otherwise.
1103 class BooleanTarget(object):
1104 def __init__(self):
1105 self.ran = False
1106 def __bool__(self):
1107 return False
1108 def __call__(self):
1109 self.ran = True
1110
1111 target = BooleanTarget()
1112 thread = threading.Thread(target=target)
1113 thread.start()
1114 thread.join()
1115 self.assertTrue(target.ran)
1116
1117 def test_leak_without_join(self):
1118 # bpo-37788: Test that a thread which is not joined explicitly
1119 # does not leak. Test written for reference leak checks.
1120 def noop(): pass
1121 with threading_helper.wait_threads_exit():
1122 threading.Thread(target=noop).start()
1123 # Thread.join() is not called
1124
1125 def test_import_from_another_thread(self):
1126 # bpo-1596321: If the threading module is first import from a thread
1127 # different than the main thread, threading._shutdown() must handle
1128 # this case without logging an error at Python exit.
1129 code = textwrap.dedent('''
1130 import _thread
1131 import sys
1132
1133 event = _thread.allocate_lock()
1134 event.acquire()
1135
1136 def import_threading():
1137 import threading
1138 event.release()
1139
1140 if 'threading' in sys.modules:
1141 raise Exception('threading is already imported')
1142
1143 _thread.start_new_thread(import_threading, ())
1144
1145 # wait until the threading module is imported
1146 event.acquire()
1147 event.release()
1148
1149 if 'threading' not in sys.modules:
1150 raise Exception('threading is not imported')
1151
1152 # don't wait until the thread completes
1153 ''')
1154 rc, out, err = assert_python_ok("-c", code)
1155 self.assertEqual(out, b'')
1156 self.assertEqual(err, b'')
1157
1158 def test_start_new_thread_at_finalization(self):
1159 code = """if 1:
1160 import _thread
1161
1162 def f():
1163 print("shouldn't be printed")
1164
1165 class AtFinalization:
1166 def __del__(self):
1167 print("OK")
1168 _thread.start_new_thread(f, ())
1169 at_finalization = AtFinalization()
1170 """
1171 _, out, err = assert_python_ok("-c", code)
1172 self.assertEqual(out.strip(), b"OK")
1173 self.assertIn(b"can't create new thread at interpreter shutdown", err)
1174
1175 def test_start_new_thread_failed(self):
1176 # gh-109746: if Python fails to start newly created thread
1177 # due to failure of underlying PyThread_start_new_thread() call,
1178 # its state should be removed from interpreter' thread states list
1179 # to avoid its double cleanup
1180 try:
1181 from resource import setrlimit, RLIMIT_NPROC
1182 except ImportError as err:
1183 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1184 code = """if 1:
1185 import resource
1186 import _thread
1187
1188 def f():
1189 print("shouldn't be printed")
1190
1191 limits = resource.getrlimit(resource.RLIMIT_NPROC)
1192 [_, hard] = limits
1193 resource.setrlimit(resource.RLIMIT_NPROC, (0, hard))
1194
1195 try:
1196 handle = _thread.start_joinable_thread(f)
1197 except RuntimeError:
1198 print('ok')
1199 else:
1200 print('!skip!')
1201 handle.join()
1202 """
1203 _, out, err = assert_python_ok("-u", "-c", code)
1204 out = out.strip()
1205 if b'!skip!' in out:
1206 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
1207 self.assertEqual(out, b'ok')
1208 self.assertEqual(err, b'')
1209
1210
1211 @skip_unless_reliable_fork
1212 @unittest.skipUnless(hasattr(threading, 'get_native_id'), "test needs threading.get_native_id()")
1213 def test_native_id_after_fork(self):
1214 script = """if True:
1215 import threading
1216 import os
1217 from test import support
1218
1219 parent_thread_native_id = threading.current_thread().native_id
1220 print(parent_thread_native_id, flush=True)
1221 assert parent_thread_native_id == threading.get_native_id()
1222 childpid = os.fork()
1223 if childpid == 0:
1224 print(threading.current_thread().native_id, flush=True)
1225 assert threading.current_thread().native_id == threading.get_native_id()
1226 else:
1227 try:
1228 assert parent_thread_native_id == threading.current_thread().native_id
1229 assert parent_thread_native_id == threading.get_native_id()
1230 finally:
1231 support.wait_process(childpid, exitcode=0)
1232 """
1233 rc, out, err = assert_python_ok('-c', script)
1234 self.assertEqual(rc, 0)
1235 self.assertEqual(err, b"")
1236 native_ids = out.strip().splitlines()
1237 self.assertEqual(len(native_ids), 2)
1238 self.assertNotEqual(native_ids[0], native_ids[1])
1239
1240 @cpython_only
1241 def test_finalize_daemon_thread_hang(self):
1242 if support.check_sanitizer(thread=True, memory=True):
1243 # the thread running `time.sleep(100)` below will still be alive
1244 # at process exit
1245 self.skipTest(
1246 "https://github.com/python/cpython/issues/124878 - Known"
1247 " race condition that TSAN identifies.")
1248 # gh-87135: tests that daemon threads hang during finalization
1249 script = textwrap.dedent('''
1250 import os
1251 import sys
1252 import threading
1253 import time
1254 import _testcapi
1255
1256 lock = threading.Lock()
1257 lock.acquire()
1258 thread_started_event = threading.Event()
1259 def thread_func():
1260 try:
1261 thread_started_event.set()
1262 _testcapi.finalize_thread_hang(lock.acquire)
1263 finally:
1264 # Control must not reach here.
1265 os._exit(2)
1266
1267 t = threading.Thread(target=thread_func)
1268 t.daemon = True
1269 t.start()
1270 thread_started_event.wait()
1271 # Sleep to ensure daemon thread is blocked on `lock.acquire`
1272 #
1273 # Note: This test is designed so that in the unlikely case that
1274 # `0.1` seconds is not sufficient time for the thread to become
1275 # blocked on `lock.acquire`, the test will still pass, it just
1276 # won't be properly testing the thread behavior during
1277 # finalization.
1278 time.sleep(0.1)
1279
1280 def run_during_finalization():
1281 # Wake up daemon thread
1282 lock.release()
1283 # Sleep to give the daemon thread time to crash if it is going
1284 # to.
1285 #
1286 # Note: If due to an exceptionally slow execution this delay is
1287 # insufficient, the test will still pass but will simply be
1288 # ineffective as a test.
1289 time.sleep(0.1)
1290 # If control reaches here, the test succeeded.
1291 os._exit(0)
1292
1293 # Replace sys.stderr.flush as a way to run code during finalization
1294 orig_flush = sys.stderr.flush
1295 def do_flush(*args, **kwargs):
1296 orig_flush(*args, **kwargs)
1297 if not sys.is_finalizing:
1298 return
1299 sys.stderr.flush = orig_flush
1300 run_during_finalization()
1301
1302 sys.stderr.flush = do_flush
1303
1304 # If the follow exit code is retained, `run_during_finalization`
1305 # did not run.
1306 sys.exit(1)
1307 ''')
1308 assert_python_ok("-c", script)
1309
1310
1311 class ThreadJoinOnShutdown(BaseTestCase):
1312
1313 def _run_and_join(self, script):
1314 script = """if 1:
1315 import sys, os, time, threading
1316
1317 # a thread, which waits for the main program to terminate
1318 def joiningfunc(mainthread):
1319 mainthread.join()
1320 print('end of thread')
1321 # stdout is fully buffered because not a tty, we have to flush
1322 # before exit.
1323 sys.stdout.flush()
1324 \n""" + script
1325
1326 rc, out, err = assert_python_ok("-c", script)
1327 data = out.decode().replace('\r', '')
1328 self.assertEqual(data, "end of main\nend of thread\n")
1329
1330 def test_1_join_on_shutdown(self):
1331 # The usual case: on exit, wait for a non-daemon thread
1332 script = """if 1:
1333 import os
1334 t = threading.Thread(target=joiningfunc,
1335 args=(threading.current_thread(),))
1336 t.start()
1337 time.sleep(0.1)
1338 print('end of main')
1339 """
1340 self._run_and_join(script)
1341
1342 @skip_unless_reliable_fork
1343 def test_2_join_in_forked_process(self):
1344 # Like the test above, but from a forked interpreter
1345 script = """if 1:
1346 from test import support
1347
1348 childpid = os.fork()
1349 if childpid != 0:
1350 # parent process
1351 support.wait_process(childpid, exitcode=0)
1352 sys.exit(0)
1353
1354 # child process
1355 t = threading.Thread(target=joiningfunc,
1356 args=(threading.current_thread(),))
1357 t.start()
1358 print('end of main')
1359 """
1360 self._run_and_join(script)
1361
1362 @skip_unless_reliable_fork
1363 def test_3_join_in_forked_from_thread(self):
1364 # Like the test above, but fork() was called from a worker thread
1365 # In the forked process, the main Thread object must be marked as stopped.
1366
1367 script = """if 1:
1368 from test import support
1369
1370 main_thread = threading.current_thread()
1371 def worker():
1372 childpid = os.fork()
1373 if childpid != 0:
1374 # parent process
1375 support.wait_process(childpid, exitcode=0)
1376 sys.exit(0)
1377
1378 # child process
1379 t = threading.Thread(target=joiningfunc,
1380 args=(main_thread,))
1381 print('end of main')
1382 t.start()
1383 t.join() # Should not block: main_thread is already stopped
1384
1385 w = threading.Thread(target=worker)
1386 w.start()
1387 """
1388 self._run_and_join(script)
1389
1390 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
1391 @support.bigmemtest(size=40, memuse=70*2**20, dry_run=False)
1392 def test_4_daemon_threads(self, size):
1393 # Check that a daemon thread cannot crash the interpreter on shutdown
1394 # by manipulating internal structures that are being disposed of in
1395 # the main thread.
1396 if support.check_sanitizer(thread=True):
1397 # some of the threads running `random_io` below will still be alive
1398 # at process exit
1399 self.skipTest("TSAN would report thread leak")
1400
1401 script = """if True:
1402 import os
1403 import random
1404 import sys
1405 import time
1406 import threading
1407
1408 thread_has_run = set()
1409
1410 def random_io():
1411 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
1412 import test.test_threading as mod
1413 while True:
1414 with open(mod.__file__, 'rb') as in_f:
1415 stuff = in_f.read(200)
1416 with open(os.devnull, 'wb') as null_f:
1417 null_f.write(stuff)
1418 time.sleep(random.random() / 1995)
1419 thread_has_run.add(threading.current_thread())
1420
1421 def main():
1422 count = 0
1423 for _ in range(40):
1424 new_thread = threading.Thread(target=random_io)
1425 new_thread.daemon = True
1426 new_thread.start()
1427 count += 1
1428 while len(thread_has_run) < count:
1429 time.sleep(0.001)
1430 # Trigger process shutdown
1431 sys.exit(0)
1432
1433 main()
1434 """
1435 rc, out, err = assert_python_ok('-c', script)
1436 self.assertFalse(err)
1437
1438 def test_thread_from_thread(self):
1439 script = """if True:
1440 import threading
1441 import time
1442
1443 def thread2():
1444 time.sleep(0.05)
1445 print("OK")
1446
1447 def thread1():
1448 time.sleep(0.05)
1449 t2 = threading.Thread(target=thread2)
1450 t2.start()
1451
1452 t = threading.Thread(target=thread1)
1453 t.start()
1454 # do not join() -- the interpreter waits for non-daemon threads to
1455 # finish.
1456 """
1457 rc, out, err = assert_python_ok('-c', script)
1458 self.assertEqual(err, b"")
1459 self.assertEqual(out.strip(), b"OK")
1460 self.assertEqual(rc, 0)
1461
1462 @skip_unless_reliable_fork
1463 def test_reinit_tls_after_fork(self):
1464 # Issue #13817: fork() would deadlock in a multithreaded program with
1465 # the ad-hoc TLS implementation.
1466
1467 def do_fork_and_wait():
1468 # just fork a child process and wait it
1469 pid = os.fork()
1470 if pid > 0:
1471 support.wait_process(pid, exitcode=50)
1472 else:
1473 os._exit(50)
1474
1475 # Ignore the warning about fork with threads.
1476 with warnings.catch_warnings(category=DeprecationWarning,
1477 action="ignore"):
1478 # start a bunch of threads that will fork() child processes
1479 threads = []
1480 for i in range(16):
1481 t = threading.Thread(target=do_fork_and_wait)
1482 threads.append(t)
1483 t.start()
1484
1485 for t in threads:
1486 t.join()
1487
1488 @skip_unless_reliable_fork
1489 def test_clear_threads_states_after_fork(self):
1490 # Issue #17094: check that threads states are cleared after fork()
1491
1492 # start a bunch of threads
1493 threads = []
1494 for i in range(16):
1495 t = threading.Thread(target=lambda : time.sleep(0.3))
1496 threads.append(t)
1497 t.start()
1498
1499 try:
1500 # Ignore the warning about fork with threads.
1501 with warnings.catch_warnings(category=DeprecationWarning,
1502 action="ignore"):
1503 pid = os.fork()
1504 if pid == 0:
1505 # check that threads states have been cleared
1506 if len(sys._current_frames()) == 1:
1507 os._exit(51)
1508 else:
1509 os._exit(52)
1510 else:
1511 support.wait_process(pid, exitcode=51)
1512 finally:
1513 for t in threads:
1514 t.join()
1515
1516
1517 class SubinterpThreadingTests(BaseTestCase):
1518 def pipe(self):
1519 r, w = os.pipe()
1520 self.addCleanup(os.close, r)
1521 self.addCleanup(os.close, w)
1522 if hasattr(os, 'set_blocking'):
1523 os.set_blocking(r, False)
1524 return (r, w)
1525
1526 def test_threads_join(self):
1527 # Non-daemon threads should be joined at subinterpreter shutdown
1528 # (issue #18808)
1529 r, w = self.pipe()
1530 code = textwrap.dedent(r"""
1531 import os
1532 import random
1533 import threading
1534 import time
1535
1536 def random_sleep():
1537 seconds = random.random() * 0.010
1538 time.sleep(seconds)
1539
1540 def f():
1541 # Sleep a bit so that the thread is still running when
1542 # Py_EndInterpreter is called.
1543 random_sleep()
1544 os.write(%d, b"x")
1545
1546 threading.Thread(target=f).start()
1547 random_sleep()
1548 """ % (w,))
1549 ret = test.support.run_in_subinterp(code)
1550 self.assertEqual(ret, 0)
1551 # The thread was joined properly.
1552 self.assertEqual(os.read(r, 1), b"x")
1553
1554 def test_threads_join_2(self):
1555 # Same as above, but a delay gets introduced after the thread's
1556 # Python code returned but before the thread state is deleted.
1557 # To achieve this, we register a thread-local object which sleeps
1558 # a bit when deallocated.
1559 r, w = self.pipe()
1560 code = textwrap.dedent(r"""
1561 import os
1562 import random
1563 import threading
1564 import time
1565
1566 def random_sleep():
1567 seconds = random.random() * 0.010
1568 time.sleep(seconds)
1569
1570 class Sleeper:
1571 def __del__(self):
1572 random_sleep()
1573
1574 tls = threading.local()
1575
1576 def f():
1577 # Sleep a bit so that the thread is still running when
1578 # Py_EndInterpreter is called.
1579 random_sleep()
1580 tls.x = Sleeper()
1581 os.write(%d, b"x")
1582
1583 threading.Thread(target=f).start()
1584 random_sleep()
1585 """ % (w,))
1586 ret = test.support.run_in_subinterp(code)
1587 self.assertEqual(ret, 0)
1588 # The thread was joined properly.
1589 self.assertEqual(os.read(r, 1), b"x")
1590
1591 @requires_subinterpreters
1592 def test_threads_join_with_no_main(self):
1593 r_interp, w_interp = self.pipe()
1594
1595 INTERP = b'I'
1596 FINI = b'F'
1597 DONE = b'D'
1598
1599 interp = interpreters.create()
1600 interp.exec(f"""if True:
1601 import os
1602 import threading
1603 import time
1604
1605 done = False
1606
1607 def notify_fini():
1608 global done
1609 done = True
1610 os.write({w_interp}, {FINI!r})
1611 t.join()
1612 threading._register_atexit(notify_fini)
1613
1614 def task():
1615 while not done:
1616 time.sleep(0.1)
1617 os.write({w_interp}, {DONE!r})
1618 t = threading.Thread(target=task)
1619 t.start()
1620
1621 os.write({w_interp}, {INTERP!r})
1622 """)
1623 interp.close()
1624
1625 self.assertEqual(os.read(r_interp, 1), INTERP)
1626 self.assertEqual(os.read(r_interp, 1), FINI)
1627 self.assertEqual(os.read(r_interp, 1), DONE)
1628
1629 @cpython_only
1630 def test_daemon_threads_fatal_error(self):
1631 import_module("_testcapi")
1632 subinterp_code = f"""if 1:
1633 import os
1634 import threading
1635 import time
1636
1637 def f():
1638 # Make sure the daemon thread is still running when
1639 # Py_EndInterpreter is called.
1640 time.sleep({test.support.SHORT_TIMEOUT})
1641 threading.Thread(target=f, daemon=True).start()
1642 """
1643 script = r"""if 1:
1644 import _testcapi
1645
1646 _testcapi.run_in_subinterp(%r)
1647 """ % (subinterp_code,)
1648 with test.support.SuppressCrashReport():
1649 rc, out, err = assert_python_failure("-c", script)
1650 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1651 "not the last thread", err.decode())
1652
1653 def _check_allowed(self, before_start='', *,
1654 allowed=True,
1655 daemon_allowed=True,
1656 daemon=False,
1657 ):
1658 import_module("_testinternalcapi")
1659 subinterp_code = textwrap.dedent(f"""
1660 import test.support
1661 import threading
1662 def func():
1663 print('this should not have run!')
1664 t = threading.Thread(target=func, daemon={daemon})
1665 {before_start}
1666 t.start()
1667 """)
1668 check_multi_interp_extensions = bool(support.Py_GIL_DISABLED)
1669 script = textwrap.dedent(f"""
1670 import test.support
1671 test.support.run_in_subinterp_with_config(
1672 {subinterp_code!r},
1673 use_main_obmalloc=True,
1674 allow_fork=True,
1675 allow_exec=True,
1676 allow_threads={allowed},
1677 allow_daemon_threads={daemon_allowed},
1678 check_multi_interp_extensions={check_multi_interp_extensions},
1679 own_gil=False,
1680 )
1681 """)
1682 with test.support.SuppressCrashReport():
1683 _, _, err = assert_python_ok("-c", script)
1684 return err.decode()
1685
1686 @cpython_only
1687 def test_threads_not_allowed(self):
1688 err = self._check_allowed(
1689 allowed=False,
1690 daemon_allowed=False,
1691 daemon=False,
1692 )
1693 self.assertIn('RuntimeError', err)
1694
1695 @cpython_only
1696 def test_daemon_threads_not_allowed(self):
1697 with self.subTest('via Thread()'):
1698 err = self._check_allowed(
1699 allowed=True,
1700 daemon_allowed=False,
1701 daemon=True,
1702 )
1703 self.assertIn('RuntimeError', err)
1704
1705 with self.subTest('via Thread.daemon setter'):
1706 err = self._check_allowed(
1707 't.daemon = True',
1708 allowed=True,
1709 daemon_allowed=False,
1710 daemon=False,
1711 )
1712 self.assertIn('RuntimeError', err)
1713
1714
1715 class ThreadingExceptionTests(BaseTestCase):
1716 # A RuntimeError should be raised if Thread.start() is called
1717 # multiple times.
1718 def test_start_thread_again(self):
1719 thread = threading.Thread()
1720 thread.start()
1721 self.assertRaises(RuntimeError, thread.start)
1722 thread.join()
1723
1724 def test_joining_current_thread(self):
1725 current_thread = threading.current_thread()
1726 self.assertRaises(RuntimeError, current_thread.join);
1727
1728 def test_joining_inactive_thread(self):
1729 thread = threading.Thread()
1730 self.assertRaises(RuntimeError, thread.join)
1731
1732 def test_daemonize_active_thread(self):
1733 thread = threading.Thread()
1734 thread.start()
1735 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
1736 thread.join()
1737
1738 def test_releasing_unacquired_lock(self):
1739 lock = threading.Lock()
1740 self.assertRaises(RuntimeError, lock.release)
1741
1742 @requires_subprocess()
1743 def test_recursion_limit(self):
1744 # Issue 9670
1745 # test that excessive recursion within a non-main thread causes
1746 # an exception rather than crashing the interpreter on platforms
1747 # like Mac OS X or FreeBSD which have small default stack sizes
1748 # for threads
1749 script = """if True:
1750 import threading
1751
1752 def recurse():
1753 return recurse()
1754
1755 def outer():
1756 try:
1757 recurse()
1758 except RecursionError:
1759 pass
1760
1761 w = threading.Thread(target=outer)
1762 w.start()
1763 w.join()
1764 print('end of main thread')
1765 """
1766 expected_output = "end of main thread\n"
1767 p = subprocess.Popen([sys.executable, "-c", script],
1768 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1769 stdout, stderr = p.communicate()
1770 data = stdout.decode().replace('\r', '')
1771 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
1772 self.assertEqual(data, expected_output)
1773
1774 def test_print_exception(self):
1775 script = r"""if True:
1776 import threading
1777 import time
1778
1779 running = False
1780 def run():
1781 global running
1782 running = True
1783 while running:
1784 time.sleep(0.01)
1785 1/0
1786 t = threading.Thread(target=run)
1787 t.start()
1788 while not running:
1789 time.sleep(0.01)
1790 running = False
1791 t.join()
1792 """
1793 rc, out, err = assert_python_ok("-c", script)
1794 self.assertEqual(out, b'')
1795 err = err.decode()
1796 self.assertIn("Exception in thread", err)
1797 self.assertIn("Traceback (most recent call last):", err)
1798 self.assertIn("ZeroDivisionError", err)
1799 self.assertNotIn("Unhandled exception", err)
1800
1801 def test_print_exception_stderr_is_none_1(self):
1802 script = r"""if True:
1803 import sys
1804 import threading
1805 import time
1806
1807 running = False
1808 def run():
1809 global running
1810 running = True
1811 while running:
1812 time.sleep(0.01)
1813 1/0
1814 t = threading.Thread(target=run)
1815 t.start()
1816 while not running:
1817 time.sleep(0.01)
1818 sys.stderr = None
1819 running = False
1820 t.join()
1821 """
1822 rc, out, err = assert_python_ok("-c", script)
1823 self.assertEqual(out, b'')
1824 err = err.decode()
1825 self.assertIn("Exception in thread", err)
1826 self.assertIn("Traceback (most recent call last):", err)
1827 self.assertIn("ZeroDivisionError", err)
1828 self.assertNotIn("Unhandled exception", err)
1829
1830 def test_print_exception_stderr_is_none_2(self):
1831 script = r"""if True:
1832 import sys
1833 import threading
1834 import time
1835
1836 running = False
1837 def run():
1838 global running
1839 running = True
1840 while running:
1841 time.sleep(0.01)
1842 1/0
1843 sys.stderr = None
1844 t = threading.Thread(target=run)
1845 t.start()
1846 while not running:
1847 time.sleep(0.01)
1848 running = False
1849 t.join()
1850 """
1851 rc, out, err = assert_python_ok("-c", script)
1852 self.assertEqual(out, b'')
1853 self.assertNotIn("Unhandled exception", err.decode())
1854
1855 def test_print_exception_gh_102056(self):
1856 # This used to crash. See gh-102056.
1857 script = r"""if True:
1858 import time
1859 import threading
1860 import _thread
1861
1862 def f():
1863 try:
1864 f()
1865 except RecursionError:
1866 f()
1867
1868 def g():
1869 try:
1870 raise ValueError()
1871 except* ValueError:
1872 f()
1873
1874 def h():
1875 time.sleep(1)
1876 _thread.interrupt_main()
1877
1878 t = threading.Thread(target=h)
1879 t.start()
1880 g()
1881 t.join()
1882 """
1883
1884 assert_python_failure("-c", script)
1885
1886 def test_bare_raise_in_brand_new_thread(self):
1887 def bare_raise():
1888 raise
1889
1890 class Issue27558(threading.Thread):
1891 exc = None
1892
1893 def run(self):
1894 try:
1895 bare_raise()
1896 except Exception as exc:
1897 self.exc = exc
1898
1899 thread = Issue27558()
1900 thread.start()
1901 thread.join()
1902 self.assertIsNotNone(thread.exc)
1903 self.assertIsInstance(thread.exc, RuntimeError)
1904 # explicitly break the reference cycle to not leak a dangling thread
1905 thread.exc = None
1906
1907 def test_multithread_modify_file_noerror(self):
1908 # See issue25872
1909 def modify_file():
1910 with open(os_helper.TESTFN, 'w', encoding='utf-8') as fp:
1911 fp.write(' ')
1912 traceback.format_stack()
1913
1914 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1915 threads = [
1916 threading.Thread(target=modify_file)
1917 for i in range(100)
1918 ]
1919 for t in threads:
1920 t.start()
1921 t.join()
1922
1923 def test_dummy_thread_on_interpreter_shutdown(self):
1924 # GH-130522: When `threading` held a reference to itself and then a
1925 # _DummyThread() object was created, destruction of the dummy thread
1926 # would emit an unraisable exception at shutdown, due to a lock being
1927 # destroyed.
1928 code = """if True:
1929 import sys
1930 import threading
1931
1932 threading.x = sys.modules[__name__]
1933 x = threading._DummyThread()
1934 """
1935 rc, out, err = assert_python_ok("-c", code)
1936 self.assertEqual(rc, 0)
1937 self.assertEqual(out, b"")
1938 self.assertEqual(err, b"")
1939
1940
1941 class ThreadRunFail(threading.Thread):
1942 def run(self):
1943 raise ValueError("run failed")
1944
1945
1946 class ExceptHookTests(BaseTestCase):
1947 def setUp(self):
1948 restore_default_excepthook(self)
1949 super().setUp()
1950
1951 @force_not_colorized
1952 def test_excepthook(self):
1953 with support.captured_output("stderr") as stderr:
1954 thread = ThreadRunFail(name="excepthook thread")
1955 thread.start()
1956 thread.join()
1957
1958 stderr = stderr.getvalue().strip()
1959 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1960 self.assertIn('Traceback (most recent call last):\n', stderr)
1961 self.assertIn(' raise ValueError("run failed")', stderr)
1962 self.assertIn('ValueError: run failed', stderr)
1963
1964 @support.cpython_only
1965 @force_not_colorized
1966 def test_excepthook_thread_None(self):
1967 # threading.excepthook called with thread=None: log the thread
1968 # identifier in this case.
1969 with support.captured_output("stderr") as stderr:
1970 try:
1971 raise ValueError("bug")
1972 except Exception as exc:
1973 args = threading.ExceptHookArgs([*sys.exc_info(), None])
1974 try:
1975 threading.excepthook(args)
1976 finally:
1977 # Explicitly break a reference cycle
1978 args = None
1979
1980 stderr = stderr.getvalue().strip()
1981 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1982 self.assertIn('Traceback (most recent call last):\n', stderr)
1983 self.assertIn(' raise ValueError("bug")', stderr)
1984 self.assertIn('ValueError: bug', stderr)
1985
1986 def test_system_exit(self):
1987 class ThreadExit(threading.Thread):
1988 def run(self):
1989 sys.exit(1)
1990
1991 # threading.excepthook() silently ignores SystemExit
1992 with support.captured_output("stderr") as stderr:
1993 thread = ThreadExit()
1994 thread.start()
1995 thread.join()
1996
1997 self.assertEqual(stderr.getvalue(), '')
1998
1999 def test_custom_excepthook(self):
2000 args = None
2001
2002 def hook(hook_args):
2003 nonlocal args
2004 args = hook_args
2005
2006 try:
2007 with support.swap_attr(threading, 'excepthook', hook):
2008 thread = ThreadRunFail()
2009 thread.start()
2010 thread.join()
2011
2012 self.assertEqual(args.exc_type, ValueError)
2013 self.assertEqual(str(args.exc_value), 'run failed')
2014 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
2015 self.assertIs(args.thread, thread)
2016 finally:
2017 # Break reference cycle
2018 args = None
2019
2020 def test_custom_excepthook_fail(self):
2021 def threading_hook(args):
2022 raise ValueError("threading_hook failed")
2023
2024 err_str = None
2025
2026 def sys_hook(exc_type, exc_value, exc_traceback):
2027 nonlocal err_str
2028 err_str = str(exc_value)
2029
2030 with support.swap_attr(threading, 'excepthook', threading_hook), \
2031 support.swap_attr(sys, 'excepthook', sys_hook), \
2032 support.captured_output('stderr') as stderr:
2033 thread = ThreadRunFail()
2034 thread.start()
2035 thread.join()
2036
2037 self.assertEqual(stderr.getvalue(),
2038 'Exception in threading.excepthook:\n')
2039 self.assertEqual(err_str, 'threading_hook failed')
2040
2041 def test_original_excepthook(self):
2042 def run_thread():
2043 with support.captured_output("stderr") as output:
2044 thread = ThreadRunFail(name="excepthook thread")
2045 thread.start()
2046 thread.join()
2047 return output.getvalue()
2048
2049 def threading_hook(args):
2050 print("Running a thread failed", file=sys.stderr)
2051
2052 default_output = run_thread()
2053 with support.swap_attr(threading, 'excepthook', threading_hook):
2054 custom_hook_output = run_thread()
2055 threading.excepthook = threading.__excepthook__
2056 recovered_output = run_thread()
2057
2058 self.assertEqual(default_output, recovered_output)
2059 self.assertNotEqual(default_output, custom_hook_output)
2060 self.assertEqual(custom_hook_output, "Running a thread failed\n")
2061
2062
2063 class TimerTests(BaseTestCase):
2064
2065 def setUp(self):
2066 BaseTestCase.setUp(self)
2067 self.callback_args = []
2068 self.callback_event = threading.Event()
2069
2070 def test_init_immutable_default_args(self):
2071 # Issue 17435: constructor defaults were mutable objects, they could be
2072 # mutated via the object attributes and affect other Timer objects.
2073 timer1 = threading.Timer(0.01, self._callback_spy)
2074 timer1.start()
2075 self.callback_event.wait()
2076 timer1.args.append("blah")
2077 timer1.kwargs["foo"] = "bar"
2078 self.callback_event.clear()
2079 timer2 = threading.Timer(0.01, self._callback_spy)
2080 timer2.start()
2081 self.callback_event.wait()
2082 self.assertEqual(len(self.callback_args), 2)
2083 self.assertEqual(self.callback_args, [((), {}), ((), {})])
2084 timer1.join()
2085 timer2.join()
2086
2087 def _callback_spy(self, *args, **kwargs):
2088 self.callback_args.append((args[:], kwargs.copy()))
2089 self.callback_event.set()
2090
2091 class LockTests(lock_tests.LockTests):
2092 locktype = staticmethod(threading.Lock)
2093
2094 class PyRLockTests(lock_tests.RLockTests):
2095 locktype = staticmethod(threading._PyRLock)
2096
2097 @unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
2098 class CRLockTests(lock_tests.RLockTests):
2099 locktype = staticmethod(threading._CRLock)
2100
2101 def test_signature(self): # gh-102029
2102 with warnings.catch_warnings(record=True) as warnings_log:
2103 threading.RLock()
2104 self.assertEqual(warnings_log, [])
2105
2106 arg_types = [
2107 ((1,), {}),
2108 ((), {'a': 1}),
2109 ((1, 2), {'a': 1}),
2110 ]
2111 for args, kwargs in arg_types:
2112 with self.subTest(args=args, kwargs=kwargs):
2113 with self.assertWarns(DeprecationWarning):
2114 threading.RLock(*args, **kwargs)
2115
2116 # Subtypes with custom `__init__` are allowed (but, not recommended):
2117 class CustomRLock(self.locktype):
2118 def __init__(self, a, *, b) -> None:
2119 super().__init__()
2120
2121 with warnings.catch_warnings(record=True) as warnings_log:
2122 CustomRLock(1, b=2)
2123 self.assertEqual(warnings_log, [])
2124
2125 class EventTests(lock_tests.EventTests):
2126 eventtype = staticmethod(threading.Event)
2127
2128 class ConditionAsRLockTests(lock_tests.RLockTests):
2129 # Condition uses an RLock by default and exports its API.
2130 locktype = staticmethod(threading.Condition)
2131
2132 def test_recursion_count(self):
2133 self.skipTest("Condition does not expose _recursion_count()")
2134
2135 class ConditionTests(lock_tests.ConditionTests):
2136 condtype = staticmethod(threading.Condition)
2137
2138 class SemaphoreTests(lock_tests.SemaphoreTests):
2139 semtype = staticmethod(threading.Semaphore)
2140
2141 class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
2142 semtype = staticmethod(threading.BoundedSemaphore)
2143
2144 class BarrierTests(lock_tests.BarrierTests):
2145 barriertype = staticmethod(threading.Barrier)
2146
2147
2148 class MiscTestCase(unittest.TestCase):
2149 def test__all__(self):
2150 restore_default_excepthook(self)
2151
2152 extra = {"ThreadError"}
2153 not_exported = {'currentThread', 'activeCount'}
2154 support.check__all__(self, threading, ('threading', '_thread'),
2155 extra=extra, not_exported=not_exported)
2156
2157
2158 class InterruptMainTests(unittest.TestCase):
2159 def check_interrupt_main_with_signal_handler(self, signum):
2160 def handler(signum, frame):
2161 1/0
2162
2163 old_handler = signal.signal(signum, handler)
2164 self.addCleanup(signal.signal, signum, old_handler)
2165
2166 with self.assertRaises(ZeroDivisionError):
2167 _thread.interrupt_main()
2168
2169 def check_interrupt_main_noerror(self, signum):
2170 handler = signal.getsignal(signum)
2171 try:
2172 # No exception should arise.
2173 signal.signal(signum, signal.SIG_IGN)
2174 _thread.interrupt_main(signum)
2175
2176 signal.signal(signum, signal.SIG_DFL)
2177 _thread.interrupt_main(signum)
2178 finally:
2179 # Restore original handler
2180 signal.signal(signum, handler)
2181
2182 @requires_gil_enabled("gh-118433: Flaky due to a longstanding bug")
2183 def test_interrupt_main_subthread(self):
2184 # Calling start_new_thread with a function that executes interrupt_main
2185 # should raise KeyboardInterrupt upon completion.
2186 def call_interrupt():
2187 _thread.interrupt_main()
2188 t = threading.Thread(target=call_interrupt)
2189 with self.assertRaises(KeyboardInterrupt):
2190 t.start()
2191 t.join()
2192 t.join()
2193
2194 def test_interrupt_main_mainthread(self):
2195 # Make sure that if interrupt_main is called in main thread that
2196 # KeyboardInterrupt is raised instantly.
2197 with self.assertRaises(KeyboardInterrupt):
2198 _thread.interrupt_main()
2199
2200 def test_interrupt_main_with_signal_handler(self):
2201 self.check_interrupt_main_with_signal_handler(signal.SIGINT)
2202 self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
2203
2204 def test_interrupt_main_noerror(self):
2205 self.check_interrupt_main_noerror(signal.SIGINT)
2206 self.check_interrupt_main_noerror(signal.SIGTERM)
2207
2208 def test_interrupt_main_invalid_signal(self):
2209 self.assertRaises(ValueError, _thread.interrupt_main, -1)
2210 self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
2211 self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
2212
2213 @threading_helper.reap_threads
2214 def test_can_interrupt_tight_loops(self):
2215 cont = [True]
2216 started = [False]
2217 interrupted = [False]
2218
2219 def worker(started, cont, interrupted):
2220 iterations = 100_000_000
2221 started[0] = True
2222 while cont[0]:
2223 if iterations:
2224 iterations -= 1
2225 else:
2226 return
2227 pass
2228 interrupted[0] = True
2229
2230 t = threading.Thread(target=worker,args=(started, cont, interrupted))
2231 t.start()
2232 while not started[0]:
2233 pass
2234 cont[0] = False
2235 t.join()
2236 self.assertTrue(interrupted[0])
2237
2238
2239 class AtexitTests(unittest.TestCase):
2240
2241 def test_atexit_output(self):
2242 rc, out, err = assert_python_ok("-c", """if True:
2243 import threading
2244
2245 def run_last():
2246 print('parrot')
2247
2248 threading._register_atexit(run_last)
2249 """)
2250
2251 self.assertFalse(err)
2252 self.assertEqual(out.strip(), b'parrot')
2253
2254 def test_atexit_called_once(self):
2255 rc, out, err = assert_python_ok("-c", """if True:
2256 import threading
2257 from unittest.mock import Mock
2258
2259 mock = Mock()
2260 threading._register_atexit(mock)
2261 mock.assert_not_called()
2262 # force early shutdown to ensure it was called once
2263 threading._shutdown()
2264 mock.assert_called_once()
2265 """)
2266
2267 self.assertFalse(err)
2268
2269 def test_atexit_after_shutdown(self):
2270 # The only way to do this is by registering an atexit within
2271 # an atexit, which is intended to raise an exception.
2272 rc, out, err = assert_python_ok("-c", """if True:
2273 import threading
2274
2275 def func():
2276 pass
2277
2278 def run_last():
2279 threading._register_atexit(func)
2280
2281 threading._register_atexit(run_last)
2282 """)
2283
2284 self.assertTrue(err)
2285 self.assertIn("RuntimeError: can't register atexit after shutdown",
2286 err.decode())
2287
2288
2289 if __name__ == "__main__":
2290 unittest.main()