Debian Codegraph @

lib-python/3/test/test_threading.py

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