blob: 546773e3329afa1763417260597e569267f14746 [file] [log] [blame]
Antoine Pitrou4c8ce842013-09-01 19:51:49 +02001"""
2Tests for the threading module.
3"""
Skip Montanaro4533f602001-08-20 20:28:48 +00004
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005import test.support
Hai Shie80697d2020-05-28 06:10:27 +08006from test.support import threading_helper
Hai Shia7f5d932020-08-04 00:41:24 +08007from test.support import verbose, cpython_only
8from test.support.import_helper import import_module
Berker Peksagce643912015-05-06 06:33:17 +03009from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +020010
Skip Montanaro4533f602001-08-20 20:28:48 +000011import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000012import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020013import _thread
14import threading
Skip Montanaro4533f602001-08-20 20:28:48 +000015import time
Tim Peters84d54892005-01-08 06:03:17 +000016import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000017import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000018import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000019import subprocess
Matěj Cepl608876b2019-05-23 22:30:00 +020020import signal
Victor Stinner066e5b12019-06-14 18:55:22 +020021import textwrap
Skip Montanaro4533f602001-08-20 20:28:48 +000022
Victor Stinner98c16c92020-09-23 23:21:19 +020023from unittest import mock
Antoine Pitrou557934f2009-11-06 22:41:14 +000024from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000025from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000026
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030027
28# Between fork() and exec(), only async-safe functions are allowed (issues
29# #12316 and #11870), and fork() from a worker thread is known to trigger
30# problems with some operating systems (issue #3863): skip problematic tests
31# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010032platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030033
34
Victor Stinnerb136b1a2021-04-16 14:33:10 +020035def restore_default_excepthook(testcase):
36 testcase.addCleanup(setattr, threading, 'excepthook', threading.excepthook)
37 threading.excepthook = threading.__excepthook__
38
39
Tim Peters84d54892005-01-08 06:03:17 +000040# A trivial mutable counter.
41class Counter(object):
42 def __init__(self):
43 self.value = 0
44 def inc(self):
45 self.value += 1
46 def dec(self):
47 self.value -= 1
48 def get(self):
49 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000050
51class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000052 def __init__(self, name, testcase, sema, mutex, nrunning):
53 threading.Thread.__init__(self, name=name)
54 self.testcase = testcase
55 self.sema = sema
56 self.mutex = mutex
57 self.nrunning = nrunning
58
Skip Montanaro4533f602001-08-20 20:28:48 +000059 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000060 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000061 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000062 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000063 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000064
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 with self.sema:
66 with self.mutex:
67 self.nrunning.inc()
68 if verbose:
69 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020070 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000071
Christian Heimes4fbc72b2008-03-22 00:47:35 +000072 time.sleep(delay)
73 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000074 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000075
Christian Heimes4fbc72b2008-03-22 00:47:35 +000076 with self.mutex:
77 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020078 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000079 if verbose:
80 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000081 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000082
Skip Montanaro4533f602001-08-20 20:28:48 +000083
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000084class BaseTestCase(unittest.TestCase):
85 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080086 self._threads = threading_helper.threading_setup()
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000087
88 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +080089 threading_helper.threading_cleanup(*self._threads)
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000090 test.support.reap_children()
91
92
93class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000094
Victor Stinner98c16c92020-09-23 23:21:19 +020095 @cpython_only
96 def test_name(self):
97 def func(): pass
98
99 thread = threading.Thread(name="myname1")
100 self.assertEqual(thread.name, "myname1")
101
102 # Convert int name to str
103 thread = threading.Thread(name=123)
104 self.assertEqual(thread.name, "123")
105
106 # target name is ignored if name is specified
107 thread = threading.Thread(target=func, name="myname2")
108 self.assertEqual(thread.name, "myname2")
109
110 with mock.patch.object(threading, '_counter', return_value=2):
111 thread = threading.Thread(name="")
112 self.assertEqual(thread.name, "Thread-2")
113
114 with mock.patch.object(threading, '_counter', return_value=3):
115 thread = threading.Thread()
116 self.assertEqual(thread.name, "Thread-3")
117
118 with mock.patch.object(threading, '_counter', return_value=5):
119 thread = threading.Thread(target=func)
120 self.assertEqual(thread.name, "Thread-5 (func)")
121
Erlend Egeberg Aasland9746cda2021-04-30 16:04:57 +0200122 @cpython_only
123 def test_disallow_instantiation(self):
124 # Ensure that the type disallows instantiation (bpo-43916)
125 lock = threading.Lock()
126 tp = type(lock)
127 self.assertRaises(TypeError, tp)
128
Tim Peters84d54892005-01-08 06:03:17 +0000129 # Create a bunch of threads, let each do some work, wait until all are
130 # done.
131 def test_various_ops(self):
132 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
133 # times about 1 second per clump).
134 NUMTASKS = 10
135
136 # no more than 3 of the 10 can run at once
137 sema = threading.BoundedSemaphore(value=3)
138 mutex = threading.RLock()
139 numrunning = Counter()
140
141 threads = []
142
143 for i in range(NUMTASKS):
144 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
145 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200146 self.assertIsNone(t.ident)
147 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000148 t.start()
149
Jake Teslerb121f632019-05-22 08:43:17 -0700150 if hasattr(threading, 'get_native_id'):
151 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
152 self.assertNotIn(None, native_ids)
153 self.assertEqual(len(native_ids), NUMTASKS + 1)
154
Tim Peters84d54892005-01-08 06:03:17 +0000155 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000156 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000157 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200158 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200159 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000160 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200161 self.assertIsNotNone(t.ident)
162 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000163 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000164 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000165 self.assertEqual(numrunning.get(), 0)
166
Benjamin Petersond23f8222009-04-05 19:13:16 +0000167 def test_ident_of_no_threading_threads(self):
168 # The ident still must work for the main thread and dummy threads.
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700169 self.assertIsNotNone(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000170 def f():
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700171 ident.append(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000172 done.set()
173 done = threading.Event()
174 ident = []
Hai Shie80697d2020-05-28 06:10:27 +0800175 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700176 tid = _thread.start_new_thread(f, ())
177 done.wait()
178 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000179 # Kill the "immortal" _DummyThread
180 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000181
Victor Stinner8c663fd2017-11-08 14:44:44 -0800182 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000183 def test_various_ops_small_stack(self):
184 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800185 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000186 try:
187 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000188 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000189 raise unittest.SkipTest(
190 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 self.test_various_ops()
192 threading.stack_size(0)
193
Victor Stinner8c663fd2017-11-08 14:44:44 -0800194 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000195 def test_various_ops_large_stack(self):
196 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800197 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000198 try:
199 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000200 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000201 raise unittest.SkipTest(
202 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000203 self.test_various_ops()
204 threading.stack_size(0)
205
Tim Peters711906e2005-01-08 07:30:42 +0000206 def test_foreign_thread(self):
207 # Check that a "foreign" thread can use the threading module.
208 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000209 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000210 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000211 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000212 mutex.release()
213
214 mutex = threading.Lock()
215 mutex.acquire()
Hai Shie80697d2020-05-28 06:10:27 +0800216 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700217 tid = _thread.start_new_thread(f, (mutex,))
218 # Wait for the thread to finish.
219 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000220 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000221 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800222 #Issue 29376
223 self.assertTrue(threading._active[tid].is_alive())
224 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000225 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000226
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000227 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
228 # exposed at the Python level. This test relies on ctypes to get at it.
229 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200230 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000231
232 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200233 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000234
235 class AsyncExc(Exception):
236 pass
237
238 exception = ctypes.py_object(AsyncExc)
239
Antoine Pitroube4d8092009-10-18 18:27:17 +0000240 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200241 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200242 self.assertIsInstance(tid, int)
243 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000244
245 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200246 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000247 # The exception is async, so we might have to keep the VM busy until
248 # it notices.
249 while True:
250 pass
251 except AsyncExc:
252 pass
253 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000254 # This code is unreachable but it reflects the intent. If we wanted
255 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000256 self.fail("AsyncExc not raised")
257 try:
258 self.assertEqual(result, 1) # one thread state modified
259 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000260 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000261 pass
262
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000263 # `worker_started` is set by the thread when it's inside a try/except
264 # block waiting to catch the asynchronously set AsyncExc exception.
265 # `worker_saw_exception` is set by the thread upon catching that
266 # exception.
267 worker_started = threading.Event()
268 worker_saw_exception = threading.Event()
269
270 class Worker(threading.Thread):
271 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200272 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000273 self.finished = False
274
275 try:
276 while True:
277 worker_started.set()
278 time.sleep(0.1)
279 except AsyncExc:
280 self.finished = True
281 worker_saw_exception.set()
282
283 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000284 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000285 t.start()
286 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000287 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000288
289 # Try a thread id that doesn't make sense.
290 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000291 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200292 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000293 self.assertEqual(result, 0) # no thread states modified
294
295 # Now raise an exception in the worker thread.
296 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000297 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000298 ret = worker_started.wait()
299 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000300 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000301 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200302 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000303 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000304 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200305 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000306 self.assertEqual(result, 1) # one thread state modified
307 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000308 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100309 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000311 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000312 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000313 if t.finished:
314 t.join()
315 # else the thread is still running, and we have no way to kill it
316
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000317 def test_limbo_cleanup(self):
318 # Issue 7481: Failure to start thread should cleanup the limbo map.
319 def fail_new_thread(*args):
320 raise threading.ThreadError()
321 _start_new_thread = threading._start_new_thread
322 threading._start_new_thread = fail_new_thread
323 try:
324 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000325 self.assertRaises(threading.ThreadError, t.start)
326 self.assertFalse(
327 t in threading._limbo,
328 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000329 finally:
330 threading._start_new_thread = _start_new_thread
331
Min ho Kimc4cacc82019-07-31 08:16:13 +1000332 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000333 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
334 # very late on python exit: on deallocation of a running thread for
335 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200336 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000337
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200338 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000339 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000340
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000341 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000342 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000343 ready.acquire()
344
Christian Heimes7d2ff882007-11-30 14:35:04 +0000345 # Module globals are cleared before __del__ is run
346 # So we save the functions in class dict
347 class C:
348 ensure = ctypes.pythonapi.PyGILState_Ensure
349 release = ctypes.pythonapi.PyGILState_Release
350 def __del__(self):
351 state = self.ensure()
352 self.release(state)
353
354 def waitingThread():
355 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000356 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000357 time.sleep(100)
358
Georg Brandl2067bfd2008-05-25 13:05:15 +0000359 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000360 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000361 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200362 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000363 self.assertEqual(rc, 42)
364
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000365 def test_finalize_with_trace(self):
366 # Issue1733757
367 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200368 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000369 import sys, threading
370
371 # A deadlock-killer, to prevent the
372 # testsuite to hang forever
373 def killer():
374 import os, time
375 time.sleep(2)
376 print('program blocked; aborting')
377 os._exit(2)
378 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000379 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000380 t.start()
381
382 # This is the trace function
383 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000384 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000385 return func
386
387 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200388 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000389
Antoine Pitrou011bd622009-10-20 21:52:47 +0000390 def test_join_nondaemon_on_shutdown(self):
391 # Issue 1722344
392 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200393 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000394 import threading
395 from time import sleep
396
397 def child():
398 sleep(1)
399 # As a non-daemon thread we SHOULD wake up and nothing
400 # should be torn down yet
401 print("Woke up, sleep function is:", sleep)
402
403 threading.Thread(target=child).start()
404 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200405 """)
406 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000407 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200408 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000409
Christian Heimes1af737c2008-01-23 08:24:23 +0000410 def test_enumerate_after_join(self):
411 # Try hard to trigger #1703448: a thread is still returned in
412 # threading.enumerate() after it has been join()ed.
413 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000414 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000415 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000416 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000417 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000418 t = threading.Thread(target=lambda: None)
419 t.start()
420 t.join()
421 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000422 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000423 "#1703448 triggered after %d trials: %s" % (i, l))
424 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000425 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000426
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000427 def test_no_refcycle_through_target(self):
428 class RunSelfFunction(object):
429 def __init__(self, should_raise):
430 # The links in this refcycle from Thread back to self
431 # should be cleaned up when the thread completes.
432 self.should_raise = should_raise
433 self.thread = threading.Thread(target=self._run,
434 args=(self,),
435 kwargs={'yet_another':self})
436 self.thread.start()
437
438 def _run(self, other_ref, yet_another):
439 if self.should_raise:
440 raise SystemExit
441
Victor Stinnerb136b1a2021-04-16 14:33:10 +0200442 restore_default_excepthook(self)
443
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000444 cyclic_object = RunSelfFunction(should_raise=False)
445 weak_cyclic_object = weakref.ref(cyclic_object)
446 cyclic_object.thread.join()
447 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000448 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000449 msg=('%d references still around' %
450 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000451
452 raising_cyclic_object = RunSelfFunction(should_raise=True)
453 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
454 raising_cyclic_object.thread.join()
455 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000456 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000457 msg=('%d references still around' %
458 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000459
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000460 def test_old_threading_api(self):
461 # Just a quick sanity check to make sure the old method names are
462 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000463 t = threading.Thread()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700464 with self.assertWarnsRegex(DeprecationWarning,
465 r'get the daemon attribute'):
466 t.isDaemon()
467 with self.assertWarnsRegex(DeprecationWarning,
468 r'set the daemon attribute'):
469 t.setDaemon(True)
470 with self.assertWarnsRegex(DeprecationWarning,
471 r'get the name attribute'):
472 t.getName()
473 with self.assertWarnsRegex(DeprecationWarning,
474 r'set the name attribute'):
475 t.setName("name")
476
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000477 e = threading.Event()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700478 with self.assertWarnsRegex(DeprecationWarning, 'use is_set()'):
479 e.isSet()
480
481 cond = threading.Condition()
482 cond.acquire()
483 with self.assertWarnsRegex(DeprecationWarning, 'use notify_all()'):
484 cond.notifyAll()
485
486 with self.assertWarnsRegex(DeprecationWarning, 'use active_count()'):
487 threading.activeCount()
488 with self.assertWarnsRegex(DeprecationWarning, 'use current_thread()'):
489 threading.currentThread()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000490
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000491 def test_repr_daemon(self):
492 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200493 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000494 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200495 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000496
luzpaza5293b42017-11-05 07:37:50 -0600497 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000498 t = threading.Thread()
499 self.assertFalse(t.daemon)
500 t = threading.Thread(daemon=False)
501 self.assertFalse(t.daemon)
502 t = threading.Thread(daemon=True)
503 self.assertTrue(t.daemon)
504
Victor Stinner5909a492020-11-16 15:20:34 +0100505 @unittest.skipUnless(hasattr(os, 'fork'), 'needs os.fork()')
506 def test_fork_at_exit(self):
507 # bpo-42350: Calling os.fork() after threading._shutdown() must
508 # not log an error.
509 code = textwrap.dedent("""
510 import atexit
511 import os
512 import sys
513 from test.support import wait_process
514
515 # Import the threading module to register its "at fork" callback
516 import threading
517
518 def exit_handler():
519 pid = os.fork()
520 if not pid:
521 print("child process ok", file=sys.stderr, flush=True)
522 # child process
Victor Stinner5909a492020-11-16 15:20:34 +0100523 else:
524 wait_process(pid, exitcode=0)
525
526 # exit_handler() will be called after threading._shutdown()
527 atexit.register(exit_handler)
528 """)
529 _, out, err = assert_python_ok("-c", code)
530 self.assertEqual(out, b'')
531 self.assertEqual(err.rstrip(), b'child process ok')
532
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200533 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
534 def test_dummy_thread_after_fork(self):
535 # Issue #14308: a dummy thread in the active list doesn't mess up
536 # the after-fork mechanism.
537 code = """if 1:
538 import _thread, threading, os, time
539
540 def background_thread(evt):
541 # Creates and registers the _DummyThread instance
542 threading.current_thread()
543 evt.set()
544 time.sleep(10)
545
546 evt = threading.Event()
547 _thread.start_new_thread(background_thread, (evt,))
548 evt.wait()
549 assert threading.active_count() == 2, threading.active_count()
550 if os.fork() == 0:
551 assert threading.active_count() == 1, threading.active_count()
552 os._exit(0)
553 else:
554 os.wait()
555 """
556 _, out, err = assert_python_ok("-c", code)
557 self.assertEqual(out, b'')
558 self.assertEqual(err, b'')
559
Charles-François Natali9939cc82013-08-30 23:32:53 +0200560 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
561 def test_is_alive_after_fork(self):
562 # Try hard to trigger #18418: is_alive() could sometimes be True on
563 # threads that vanished after a fork.
564 old_interval = sys.getswitchinterval()
565 self.addCleanup(sys.setswitchinterval, old_interval)
566
567 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100568 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200569
570 for i in range(20):
571 t = threading.Thread(target=lambda: None)
572 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200573 pid = os.fork()
574 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700575 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200576 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700577 t.join()
578
Victor Stinnera9f96872020-03-31 21:49:44 +0200579 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200580
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300581 def test_main_thread(self):
582 main = threading.main_thread()
583 self.assertEqual(main.name, 'MainThread')
584 self.assertEqual(main.ident, threading.current_thread().ident)
585 self.assertEqual(main.ident, threading.get_ident())
586
587 def f():
588 self.assertNotEqual(threading.main_thread().ident,
589 threading.current_thread().ident)
590 th = threading.Thread(target=f)
591 th.start()
592 th.join()
593
594 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
595 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
596 def test_main_thread_after_fork(self):
597 code = """if 1:
598 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200599 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300600
601 pid = os.fork()
602 if pid == 0:
603 main = threading.main_thread()
604 print(main.name)
605 print(main.ident == threading.current_thread().ident)
606 print(main.ident == threading.get_ident())
607 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200608 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300609 """
610 _, out, err = assert_python_ok("-c", code)
611 data = out.decode().replace('\r', '')
612 self.assertEqual(err, b"")
613 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
614
615 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
616 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
617 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
618 def test_main_thread_after_fork_from_nonmain_thread(self):
619 code = """if 1:
620 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200621 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300622
Victor Stinner98c16c92020-09-23 23:21:19 +0200623 def func():
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300624 pid = os.fork()
625 if pid == 0:
626 main = threading.main_thread()
627 print(main.name)
628 print(main.ident == threading.current_thread().ident)
629 print(main.ident == threading.get_ident())
630 # stdout is fully buffered because not a tty,
631 # we have to flush before exit.
632 sys.stdout.flush()
633 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200634 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300635
Victor Stinner98c16c92020-09-23 23:21:19 +0200636 th = threading.Thread(target=func)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300637 th.start()
638 th.join()
639 """
640 _, out, err = assert_python_ok("-c", code)
641 data = out.decode().replace('\r', '')
642 self.assertEqual(err, b"")
Victor Stinner98c16c92020-09-23 23:21:19 +0200643 self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300644
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200645 def test_main_thread_during_shutdown(self):
646 # bpo-31516: current_thread() should still point to the main thread
647 # at shutdown
648 code = """if 1:
649 import gc, threading
650
651 main_thread = threading.current_thread()
652 assert main_thread is threading.main_thread() # sanity check
653
654 class RefCycle:
655 def __init__(self):
656 self.cycle = self
657
658 def __del__(self):
659 print("GC:",
660 threading.current_thread() is main_thread,
661 threading.main_thread() is main_thread,
662 threading.enumerate() == [main_thread])
663
664 RefCycle()
665 gc.collect() # sanity check
666 x = RefCycle()
667 """
668 _, out, err = assert_python_ok("-c", code)
669 data = out.decode()
670 self.assertEqual(err, b"")
671 self.assertEqual(data.splitlines(),
672 ["GC: True True True"] * 2)
673
Victor Stinner468e5fe2019-06-13 01:30:17 +0200674 def test_finalization_shutdown(self):
675 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
676 # until Python thread states of all non-daemon threads get deleted.
677 #
678 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
679 # test the finalization of the main interpreter.
680 code = """if 1:
681 import os
682 import threading
683 import time
684 import random
685
686 def random_sleep():
687 seconds = random.random() * 0.010
688 time.sleep(seconds)
689
690 class Sleeper:
691 def __del__(self):
692 random_sleep()
693
694 tls = threading.local()
695
696 def f():
697 # Sleep a bit so that the thread is still running when
698 # Py_Finalize() is called.
699 random_sleep()
700 tls.x = Sleeper()
701 random_sleep()
702
703 threading.Thread(target=f).start()
704 random_sleep()
705 """
706 rc, out, err = assert_python_ok("-c", code)
707 self.assertEqual(err, b"")
708
Antoine Pitrou7b476992013-09-07 23:38:37 +0200709 def test_tstate_lock(self):
710 # Test an implementation detail of Thread objects.
711 started = _thread.allocate_lock()
712 finish = _thread.allocate_lock()
713 started.acquire()
714 finish.acquire()
715 def f():
716 started.release()
717 finish.acquire()
718 time.sleep(0.01)
719 # The tstate lock is None until the thread is started
720 t = threading.Thread(target=f)
721 self.assertIs(t._tstate_lock, None)
722 t.start()
723 started.acquire()
724 self.assertTrue(t.is_alive())
725 # The tstate lock can't be acquired when the thread is running
726 # (or suspended).
727 tstate_lock = t._tstate_lock
728 self.assertFalse(tstate_lock.acquire(timeout=0), False)
729 finish.release()
730 # When the thread ends, the state_lock can be successfully
731 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100732 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200733 # But is_alive() is still True: we hold _tstate_lock now, which
734 # prevents is_alive() from knowing the thread's end-of-life C code
735 # is done.
736 self.assertTrue(t.is_alive())
737 # Let is_alive() find out the C code is done.
738 tstate_lock.release()
739 self.assertFalse(t.is_alive())
740 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200741 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700742 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200743
Tim Peters72460fa2013-09-09 18:48:24 -0500744 def test_repr_stopped(self):
745 # Verify that "stopped" shows up in repr(Thread) appropriately.
746 started = _thread.allocate_lock()
747 finish = _thread.allocate_lock()
748 started.acquire()
749 finish.acquire()
750 def f():
751 started.release()
752 finish.acquire()
753 t = threading.Thread(target=f)
754 t.start()
755 started.acquire()
756 self.assertIn("started", repr(t))
757 finish.release()
758 # "stopped" should appear in the repr in a reasonable amount of time.
759 # Implementation detail: as of this writing, that's trivially true
760 # if .join() is called, and almost trivially true if .is_alive() is
761 # called. The detail we're testing here is that "stopped" shows up
762 # "all on its own".
763 LOOKING_FOR = "stopped"
764 for i in range(500):
765 if LOOKING_FOR in repr(t):
766 break
767 time.sleep(0.01)
768 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700769 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000770
Tim Peters7634e1c2013-10-08 20:55:51 -0500771 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500772 # BoundedSemaphore should raise ValueError if released too often.
773 for limit in range(1, 10):
774 bs = threading.BoundedSemaphore(limit)
775 threads = [threading.Thread(target=bs.acquire)
776 for _ in range(limit)]
777 for t in threads:
778 t.start()
779 for t in threads:
780 t.join()
781 threads = [threading.Thread(target=bs.release)
782 for _ in range(limit)]
783 for t in threads:
784 t.start()
785 for t in threads:
786 t.join()
787 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500788
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200789 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100790 def test_frame_tstate_tracing(self):
791 # Issue #14432: Crash when a generator is created in a C thread that is
792 # destroyed while the generator is still used. The issue was that a
793 # generator contains a frame, and the frame kept a reference to the
794 # Python state of the destroyed C thread. The crash occurs when a trace
795 # function is setup.
796
797 def noop_trace(frame, event, arg):
798 # no operation
799 return noop_trace
800
801 def generator():
802 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300803 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100804
805 def callback():
806 if callback.gen is None:
807 callback.gen = generator()
808 return next(callback.gen)
809 callback.gen = None
810
811 old_trace = sys.gettrace()
812 sys.settrace(noop_trace)
813 try:
814 # Install a trace function
815 threading.settrace(noop_trace)
816
817 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200818 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100819 _testcapi.call_in_temporary_c_thread(callback)
820
821 # Call the generator in a different Python thread, check that the
822 # generator didn't keep a reference to the destroyed thread state
823 for test in range(3):
824 # The trace function is still called here
825 callback()
826 finally:
827 sys.settrace(old_trace)
828
Mario Corchero0001a1b2020-11-04 10:27:43 +0100829 def test_gettrace(self):
830 def noop_trace(frame, event, arg):
831 # no operation
832 return noop_trace
833 old_trace = threading.gettrace()
834 try:
835 threading.settrace(noop_trace)
836 trace_func = threading.gettrace()
837 self.assertEqual(noop_trace,trace_func)
838 finally:
839 threading.settrace(old_trace)
840
841 def test_getprofile(self):
842 def fn(*args): pass
843 old_profile = threading.getprofile()
844 try:
845 threading.setprofile(fn)
846 self.assertEqual(fn, threading.getprofile())
847 finally:
848 threading.setprofile(old_profile)
849
Victor Stinner6f75c872019-06-13 12:06:24 +0200850 @cpython_only
851 def test_shutdown_locks(self):
852 for daemon in (False, True):
853 with self.subTest(daemon=daemon):
854 event = threading.Event()
855 thread = threading.Thread(target=event.wait, daemon=daemon)
856
857 # Thread.start() must add lock to _shutdown_locks,
858 # but only for non-daemon thread
859 thread.start()
860 tstate_lock = thread._tstate_lock
861 if not daemon:
862 self.assertIn(tstate_lock, threading._shutdown_locks)
863 else:
864 self.assertNotIn(tstate_lock, threading._shutdown_locks)
865
866 # unblock the thread and join it
867 event.set()
868 thread.join()
869
870 # Thread._stop() must remove tstate_lock from _shutdown_locks.
871 # Daemon threads must never add it to _shutdown_locks.
872 self.assertNotIn(tstate_lock, threading._shutdown_locks)
873
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100874 def test_locals_at_exit(self):
875 # bpo-19466: thread locals must not be deleted before destructors
876 # are called
877 rc, out, err = assert_python_ok("-c", """if 1:
878 import threading
879
880 class Atexit:
881 def __del__(self):
882 print("thread_dict.atexit = %r" % thread_dict.atexit)
883
884 thread_dict = threading.local()
885 thread_dict.atexit = "value"
886
887 atexit = Atexit()
888 """)
889 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
890
BarneyStratford01c4fdd2021-02-02 20:24:24 +0000891 def test_boolean_target(self):
892 # bpo-41149: A thread that had a boolean value of False would not
893 # run, regardless of whether it was callable. The correct behaviour
894 # is for a thread to do nothing if its target is None, and to call
895 # the target otherwise.
896 class BooleanTarget(object):
897 def __init__(self):
898 self.ran = False
899 def __bool__(self):
900 return False
901 def __call__(self):
902 self.ran = True
903
904 target = BooleanTarget()
905 thread = threading.Thread(target=target)
906 thread.start()
907 thread.join()
908 self.assertTrue(target.ran)
909
910
Victor Stinner45956b92013-11-12 16:37:55 +0100911
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000912class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000913
914 def _run_and_join(self, script):
915 script = """if 1:
916 import sys, os, time, threading
917
918 # a thread, which waits for the main program to terminate
919 def joiningfunc(mainthread):
920 mainthread.join()
921 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000922 # stdout is fully buffered because not a tty, we have to flush
923 # before exit.
924 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000925 \n""" + script
926
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200927 rc, out, err = assert_python_ok("-c", script)
928 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000929 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000930
931 def test_1_join_on_shutdown(self):
932 # The usual case: on exit, wait for a non-daemon thread
933 script = """if 1:
934 import os
935 t = threading.Thread(target=joiningfunc,
936 args=(threading.current_thread(),))
937 t.start()
938 time.sleep(0.1)
939 print('end of main')
940 """
941 self._run_and_join(script)
942
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000943 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200944 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000945 def test_2_join_in_forked_process(self):
946 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000947 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200948 from test import support
949
Jesse Nollera8513972008-07-17 16:49:17 +0000950 childpid = os.fork()
951 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200952 # parent process
953 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000954 sys.exit(0)
955
Victor Stinnera9f96872020-03-31 21:49:44 +0200956 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000957 t = threading.Thread(target=joiningfunc,
958 args=(threading.current_thread(),))
959 t.start()
960 print('end of main')
961 """
962 self._run_and_join(script)
963
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000964 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200965 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000966 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000967 # Like the test above, but fork() was called from a worker thread
968 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000969
Jesse Nollera8513972008-07-17 16:49:17 +0000970 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200971 from test import support
972
Jesse Nollera8513972008-07-17 16:49:17 +0000973 main_thread = threading.current_thread()
974 def worker():
975 childpid = os.fork()
976 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200977 # parent process
978 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000979 sys.exit(0)
980
Victor Stinnera9f96872020-03-31 21:49:44 +0200981 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000982 t = threading.Thread(target=joiningfunc,
983 args=(main_thread,))
984 print('end of main')
985 t.start()
986 t.join() # Should not block: main_thread is already stopped
987
988 w = threading.Thread(target=worker)
989 w.start()
990 """
991 self._run_and_join(script)
992
Victor Stinner26d31862011-07-01 14:26:24 +0200993 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500994 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200995 # Check that a daemon thread cannot crash the interpreter on shutdown
996 # by manipulating internal structures that are being disposed of in
997 # the main thread.
998 script = """if True:
999 import os
1000 import random
1001 import sys
1002 import time
1003 import threading
1004
1005 thread_has_run = set()
1006
1007 def random_io():
1008 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001009 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001010 with open(os.__file__, 'rb') as in_f:
1011 stuff = in_f.read(200)
1012 with open(os.devnull, 'wb') as null_f:
1013 null_f.write(stuff)
1014 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001015 thread_has_run.add(threading.current_thread())
1016
1017 def main():
1018 count = 0
1019 for _ in range(40):
1020 new_thread = threading.Thread(target=random_io)
1021 new_thread.daemon = True
1022 new_thread.start()
1023 count += 1
1024 while len(thread_has_run) < count:
1025 time.sleep(0.001)
1026 # Trigger process shutdown
1027 sys.exit(0)
1028
1029 main()
1030 """
1031 rc, out, err = assert_python_ok('-c', script)
1032 self.assertFalse(err)
1033
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001034 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +01001035 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001036 def test_reinit_tls_after_fork(self):
1037 # Issue #13817: fork() would deadlock in a multithreaded program with
1038 # the ad-hoc TLS implementation.
1039
1040 def do_fork_and_wait():
1041 # just fork a child process and wait it
1042 pid = os.fork()
1043 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +02001044 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001045 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001046 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001047
1048 # start a bunch of threads that will fork() child processes
1049 threads = []
1050 for i in range(16):
1051 t = threading.Thread(target=do_fork_and_wait)
1052 threads.append(t)
1053 t.start()
1054
1055 for t in threads:
1056 t.join()
1057
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001058 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
1059 def test_clear_threads_states_after_fork(self):
1060 # Issue #17094: check that threads states are cleared after fork()
1061
1062 # start a bunch of threads
1063 threads = []
1064 for i in range(16):
1065 t = threading.Thread(target=lambda : time.sleep(0.3))
1066 threads.append(t)
1067 t.start()
1068
1069 pid = os.fork()
1070 if pid == 0:
1071 # check that threads states have been cleared
1072 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +02001073 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001074 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001075 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001076 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001077 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001078
1079 for t in threads:
1080 t.join()
1081
Jesse Nollera8513972008-07-17 16:49:17 +00001082
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001083class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001084 def pipe(self):
1085 r, w = os.pipe()
1086 self.addCleanup(os.close, r)
1087 self.addCleanup(os.close, w)
1088 if hasattr(os, 'set_blocking'):
1089 os.set_blocking(r, False)
1090 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001091
1092 def test_threads_join(self):
1093 # Non-daemon threads should be joined at subinterpreter shutdown
1094 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001095 r, w = self.pipe()
1096 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001097 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001098 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001099 import threading
1100 import time
1101
Victor Stinner468e5fe2019-06-13 01:30:17 +02001102 def random_sleep():
1103 seconds = random.random() * 0.010
1104 time.sleep(seconds)
1105
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001106 def f():
1107 # Sleep a bit so that the thread is still running when
1108 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001109 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001110 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001111
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001112 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001113 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001114 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001115 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001116 self.assertEqual(ret, 0)
1117 # The thread was joined properly.
1118 self.assertEqual(os.read(r, 1), b"x")
1119
Antoine Pitrou7b476992013-09-07 23:38:37 +02001120 def test_threads_join_2(self):
1121 # Same as above, but a delay gets introduced after the thread's
1122 # Python code returned but before the thread state is deleted.
1123 # To achieve this, we register a thread-local object which sleeps
1124 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001125 r, w = self.pipe()
1126 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001127 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001128 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001129 import threading
1130 import time
1131
Victor Stinner468e5fe2019-06-13 01:30:17 +02001132 def random_sleep():
1133 seconds = random.random() * 0.010
1134 time.sleep(seconds)
1135
Antoine Pitrou7b476992013-09-07 23:38:37 +02001136 class Sleeper:
1137 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001138 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001139
1140 tls = threading.local()
1141
1142 def f():
1143 # Sleep a bit so that the thread is still running when
1144 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001145 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001146 tls.x = Sleeper()
1147 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001148
Antoine Pitrou7b476992013-09-07 23:38:37 +02001149 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001150 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001151 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001152 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001153 self.assertEqual(ret, 0)
1154 # The thread was joined properly.
1155 self.assertEqual(os.read(r, 1), b"x")
1156
Victor Stinner14d53312020-04-12 23:45:09 +02001157 @cpython_only
1158 def test_daemon_threads_fatal_error(self):
1159 subinterp_code = f"""if 1:
1160 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001161 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001162 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001163
Victor Stinner14d53312020-04-12 23:45:09 +02001164 def f():
1165 # Make sure the daemon thread is still running when
1166 # Py_EndInterpreter is called.
1167 time.sleep({test.support.SHORT_TIMEOUT})
1168 threading.Thread(target=f, daemon=True).start()
1169 """
1170 script = r"""if 1:
1171 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001172
Victor Stinner14d53312020-04-12 23:45:09 +02001173 _testcapi.run_in_subinterp(%r)
1174 """ % (subinterp_code,)
1175 with test.support.SuppressCrashReport():
1176 rc, out, err = assert_python_failure("-c", script)
1177 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1178 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001179
1180
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001181class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001182 # A RuntimeError should be raised if Thread.start() is called
1183 # multiple times.
1184 def test_start_thread_again(self):
1185 thread = threading.Thread()
1186 thread.start()
1187 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001188 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001189
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001190 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001191 current_thread = threading.current_thread()
1192 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001193
1194 def test_joining_inactive_thread(self):
1195 thread = threading.Thread()
1196 self.assertRaises(RuntimeError, thread.join)
1197
1198 def test_daemonize_active_thread(self):
1199 thread = threading.Thread()
1200 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001201 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001202 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001203
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001204 def test_releasing_unacquired_lock(self):
1205 lock = threading.Lock()
1206 self.assertRaises(RuntimeError, lock.release)
1207
Ned Deily9a7c5242011-05-28 00:19:56 -07001208 def test_recursion_limit(self):
1209 # Issue 9670
1210 # test that excessive recursion within a non-main thread causes
1211 # an exception rather than crashing the interpreter on platforms
1212 # like Mac OS X or FreeBSD which have small default stack sizes
1213 # for threads
1214 script = """if True:
1215 import threading
1216
1217 def recurse():
1218 return recurse()
1219
1220 def outer():
1221 try:
1222 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001223 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001224 pass
1225
1226 w = threading.Thread(target=outer)
1227 w.start()
1228 w.join()
1229 print('end of main thread')
1230 """
1231 expected_output = "end of main thread\n"
1232 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001233 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001234 stdout, stderr = p.communicate()
1235 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001236 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001237 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001238
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001239 def test_print_exception(self):
1240 script = r"""if True:
1241 import threading
1242 import time
1243
1244 running = False
1245 def run():
1246 global running
1247 running = True
1248 while running:
1249 time.sleep(0.01)
1250 1/0
1251 t = threading.Thread(target=run)
1252 t.start()
1253 while not running:
1254 time.sleep(0.01)
1255 running = False
1256 t.join()
1257 """
1258 rc, out, err = assert_python_ok("-c", script)
1259 self.assertEqual(out, b'')
1260 err = err.decode()
1261 self.assertIn("Exception in thread", err)
1262 self.assertIn("Traceback (most recent call last):", err)
1263 self.assertIn("ZeroDivisionError", err)
1264 self.assertNotIn("Unhandled exception", err)
1265
1266 def test_print_exception_stderr_is_none_1(self):
1267 script = r"""if True:
1268 import sys
1269 import threading
1270 import time
1271
1272 running = False
1273 def run():
1274 global running
1275 running = True
1276 while running:
1277 time.sleep(0.01)
1278 1/0
1279 t = threading.Thread(target=run)
1280 t.start()
1281 while not running:
1282 time.sleep(0.01)
1283 sys.stderr = None
1284 running = False
1285 t.join()
1286 """
1287 rc, out, err = assert_python_ok("-c", script)
1288 self.assertEqual(out, b'')
1289 err = err.decode()
1290 self.assertIn("Exception in thread", err)
1291 self.assertIn("Traceback (most recent call last):", err)
1292 self.assertIn("ZeroDivisionError", err)
1293 self.assertNotIn("Unhandled exception", err)
1294
1295 def test_print_exception_stderr_is_none_2(self):
1296 script = r"""if True:
1297 import sys
1298 import threading
1299 import time
1300
1301 running = False
1302 def run():
1303 global running
1304 running = True
1305 while running:
1306 time.sleep(0.01)
1307 1/0
1308 sys.stderr = None
1309 t = threading.Thread(target=run)
1310 t.start()
1311 while not running:
1312 time.sleep(0.01)
1313 running = False
1314 t.join()
1315 """
1316 rc, out, err = assert_python_ok("-c", script)
1317 self.assertEqual(out, b'')
1318 self.assertNotIn("Unhandled exception", err.decode())
1319
Victor Stinnereec93312016-08-18 18:13:10 +02001320 def test_bare_raise_in_brand_new_thread(self):
1321 def bare_raise():
1322 raise
1323
1324 class Issue27558(threading.Thread):
1325 exc = None
1326
1327 def run(self):
1328 try:
1329 bare_raise()
1330 except Exception as exc:
1331 self.exc = exc
1332
1333 thread = Issue27558()
1334 thread.start()
1335 thread.join()
1336 self.assertIsNotNone(thread.exc)
1337 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001338 # explicitly break the reference cycle to not leak a dangling thread
1339 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001340
Victor Stinnercd590a72019-05-28 00:39:52 +02001341
1342class ThreadRunFail(threading.Thread):
1343 def run(self):
1344 raise ValueError("run failed")
1345
1346
1347class ExceptHookTests(BaseTestCase):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001348 def setUp(self):
1349 restore_default_excepthook(self)
1350 super().setUp()
1351
Victor Stinnercd590a72019-05-28 00:39:52 +02001352 def test_excepthook(self):
1353 with support.captured_output("stderr") as stderr:
1354 thread = ThreadRunFail(name="excepthook thread")
1355 thread.start()
1356 thread.join()
1357
1358 stderr = stderr.getvalue().strip()
1359 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1360 self.assertIn('Traceback (most recent call last):\n', stderr)
1361 self.assertIn(' raise ValueError("run failed")', stderr)
1362 self.assertIn('ValueError: run failed', stderr)
1363
1364 @support.cpython_only
1365 def test_excepthook_thread_None(self):
1366 # threading.excepthook called with thread=None: log the thread
1367 # identifier in this case.
1368 with support.captured_output("stderr") as stderr:
1369 try:
1370 raise ValueError("bug")
1371 except Exception as exc:
1372 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001373 try:
1374 threading.excepthook(args)
1375 finally:
1376 # Explicitly break a reference cycle
1377 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001378
1379 stderr = stderr.getvalue().strip()
1380 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1381 self.assertIn('Traceback (most recent call last):\n', stderr)
1382 self.assertIn(' raise ValueError("bug")', stderr)
1383 self.assertIn('ValueError: bug', stderr)
1384
1385 def test_system_exit(self):
1386 class ThreadExit(threading.Thread):
1387 def run(self):
1388 sys.exit(1)
1389
1390 # threading.excepthook() silently ignores SystemExit
1391 with support.captured_output("stderr") as stderr:
1392 thread = ThreadExit()
1393 thread.start()
1394 thread.join()
1395
1396 self.assertEqual(stderr.getvalue(), '')
1397
1398 def test_custom_excepthook(self):
1399 args = None
1400
1401 def hook(hook_args):
1402 nonlocal args
1403 args = hook_args
1404
1405 try:
1406 with support.swap_attr(threading, 'excepthook', hook):
1407 thread = ThreadRunFail()
1408 thread.start()
1409 thread.join()
1410
1411 self.assertEqual(args.exc_type, ValueError)
1412 self.assertEqual(str(args.exc_value), 'run failed')
1413 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1414 self.assertIs(args.thread, thread)
1415 finally:
1416 # Break reference cycle
1417 args = None
1418
1419 def test_custom_excepthook_fail(self):
1420 def threading_hook(args):
1421 raise ValueError("threading_hook failed")
1422
1423 err_str = None
1424
1425 def sys_hook(exc_type, exc_value, exc_traceback):
1426 nonlocal err_str
1427 err_str = str(exc_value)
1428
1429 with support.swap_attr(threading, 'excepthook', threading_hook), \
1430 support.swap_attr(sys, 'excepthook', sys_hook), \
1431 support.captured_output('stderr') as stderr:
1432 thread = ThreadRunFail()
1433 thread.start()
1434 thread.join()
1435
1436 self.assertEqual(stderr.getvalue(),
1437 'Exception in threading.excepthook:\n')
1438 self.assertEqual(err_str, 'threading_hook failed')
1439
Mario Corchero750c5ab2020-11-12 18:27:44 +01001440 def test_original_excepthook(self):
1441 def run_thread():
1442 with support.captured_output("stderr") as output:
1443 thread = ThreadRunFail(name="excepthook thread")
1444 thread.start()
1445 thread.join()
1446 return output.getvalue()
1447
1448 def threading_hook(args):
1449 print("Running a thread failed", file=sys.stderr)
1450
1451 default_output = run_thread()
1452 with support.swap_attr(threading, 'excepthook', threading_hook):
1453 custom_hook_output = run_thread()
1454 threading.excepthook = threading.__excepthook__
1455 recovered_output = run_thread()
1456
1457 self.assertEqual(default_output, recovered_output)
1458 self.assertNotEqual(default_output, custom_hook_output)
1459 self.assertEqual(custom_hook_output, "Running a thread failed\n")
1460
Victor Stinnercd590a72019-05-28 00:39:52 +02001461
R David Murray19aeb432013-03-30 17:19:38 -04001462class TimerTests(BaseTestCase):
1463
1464 def setUp(self):
1465 BaseTestCase.setUp(self)
1466 self.callback_args = []
1467 self.callback_event = threading.Event()
1468
1469 def test_init_immutable_default_args(self):
1470 # Issue 17435: constructor defaults were mutable objects, they could be
1471 # mutated via the object attributes and affect other Timer objects.
1472 timer1 = threading.Timer(0.01, self._callback_spy)
1473 timer1.start()
1474 self.callback_event.wait()
1475 timer1.args.append("blah")
1476 timer1.kwargs["foo"] = "bar"
1477 self.callback_event.clear()
1478 timer2 = threading.Timer(0.01, self._callback_spy)
1479 timer2.start()
1480 self.callback_event.wait()
1481 self.assertEqual(len(self.callback_args), 2)
1482 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001483 timer1.join()
1484 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001485
1486 def _callback_spy(self, *args, **kwargs):
1487 self.callback_args.append((args[:], kwargs.copy()))
1488 self.callback_event.set()
1489
Antoine Pitrou557934f2009-11-06 22:41:14 +00001490class LockTests(lock_tests.LockTests):
1491 locktype = staticmethod(threading.Lock)
1492
Antoine Pitrou434736a2009-11-10 18:46:01 +00001493class PyRLockTests(lock_tests.RLockTests):
1494 locktype = staticmethod(threading._PyRLock)
1495
Charles-François Natali6b671b22012-01-28 11:36:04 +01001496@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001497class CRLockTests(lock_tests.RLockTests):
1498 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001499
1500class EventTests(lock_tests.EventTests):
1501 eventtype = staticmethod(threading.Event)
1502
1503class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001504 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001505 locktype = staticmethod(threading.Condition)
1506
1507class ConditionTests(lock_tests.ConditionTests):
1508 condtype = staticmethod(threading.Condition)
1509
1510class SemaphoreTests(lock_tests.SemaphoreTests):
1511 semtype = staticmethod(threading.Semaphore)
1512
1513class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1514 semtype = staticmethod(threading.BoundedSemaphore)
1515
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001516class BarrierTests(lock_tests.BarrierTests):
1517 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001518
Matěj Cepl608876b2019-05-23 22:30:00 +02001519
Martin Panter19e69c52015-11-14 12:46:42 +00001520class MiscTestCase(unittest.TestCase):
1521 def test__all__(self):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001522 restore_default_excepthook(self)
1523
Martin Panter19e69c52015-11-14 12:46:42 +00001524 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001525 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001526 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001527 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001528
Matěj Cepl608876b2019-05-23 22:30:00 +02001529
1530class InterruptMainTests(unittest.TestCase):
Antoine Pitrouba251c22021-03-11 23:35:45 +01001531 def check_interrupt_main_with_signal_handler(self, signum):
1532 def handler(signum, frame):
1533 1/0
1534
1535 old_handler = signal.signal(signum, handler)
1536 self.addCleanup(signal.signal, signum, old_handler)
1537
1538 with self.assertRaises(ZeroDivisionError):
1539 _thread.interrupt_main()
1540
1541 def check_interrupt_main_noerror(self, signum):
1542 handler = signal.getsignal(signum)
1543 try:
1544 # No exception should arise.
1545 signal.signal(signum, signal.SIG_IGN)
1546 _thread.interrupt_main(signum)
1547
1548 signal.signal(signum, signal.SIG_DFL)
1549 _thread.interrupt_main(signum)
1550 finally:
1551 # Restore original handler
1552 signal.signal(signum, handler)
1553
Matěj Cepl608876b2019-05-23 22:30:00 +02001554 def test_interrupt_main_subthread(self):
1555 # Calling start_new_thread with a function that executes interrupt_main
1556 # should raise KeyboardInterrupt upon completion.
1557 def call_interrupt():
1558 _thread.interrupt_main()
1559 t = threading.Thread(target=call_interrupt)
1560 with self.assertRaises(KeyboardInterrupt):
1561 t.start()
1562 t.join()
1563 t.join()
1564
1565 def test_interrupt_main_mainthread(self):
1566 # Make sure that if interrupt_main is called in main thread that
1567 # KeyboardInterrupt is raised instantly.
1568 with self.assertRaises(KeyboardInterrupt):
1569 _thread.interrupt_main()
1570
Antoine Pitrouba251c22021-03-11 23:35:45 +01001571 def test_interrupt_main_with_signal_handler(self):
1572 self.check_interrupt_main_with_signal_handler(signal.SIGINT)
1573 self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
Matěj Cepl608876b2019-05-23 22:30:00 +02001574
Antoine Pitrouba251c22021-03-11 23:35:45 +01001575 def test_interrupt_main_noerror(self):
1576 self.check_interrupt_main_noerror(signal.SIGINT)
1577 self.check_interrupt_main_noerror(signal.SIGTERM)
1578
1579 def test_interrupt_main_invalid_signal(self):
1580 self.assertRaises(ValueError, _thread.interrupt_main, -1)
1581 self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
1582 self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
Matěj Cepl608876b2019-05-23 22:30:00 +02001583
1584
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001585class AtexitTests(unittest.TestCase):
1586
1587 def test_atexit_output(self):
1588 rc, out, err = assert_python_ok("-c", """if True:
1589 import threading
1590
1591 def run_last():
1592 print('parrot')
1593
1594 threading._register_atexit(run_last)
1595 """)
1596
1597 self.assertFalse(err)
1598 self.assertEqual(out.strip(), b'parrot')
1599
1600 def test_atexit_called_once(self):
1601 rc, out, err = assert_python_ok("-c", """if True:
1602 import threading
1603 from unittest.mock import Mock
1604
1605 mock = Mock()
1606 threading._register_atexit(mock)
1607 mock.assert_not_called()
1608 # force early shutdown to ensure it was called once
1609 threading._shutdown()
1610 mock.assert_called_once()
1611 """)
1612
1613 self.assertFalse(err)
1614
1615 def test_atexit_after_shutdown(self):
1616 # The only way to do this is by registering an atexit within
1617 # an atexit, which is intended to raise an exception.
1618 rc, out, err = assert_python_ok("-c", """if True:
1619 import threading
1620
1621 def func():
1622 pass
1623
1624 def run_last():
1625 threading._register_atexit(func)
1626
1627 threading._register_atexit(run_last)
1628 """)
1629
1630 self.assertTrue(err)
1631 self.assertIn("RuntimeError: can't register atexit after shutdown",
1632 err.decode())
1633
1634
Tim Peters84d54892005-01-08 06:03:17 +00001635if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001636 unittest.main()