blob: 23fe2d3f4d32e2ae2043ba12fa8aad7df53648c8 [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
Irit Katriel373741a2021-05-18 14:53:57 +01007from test.support import verbose, cpython_only, os_helper
Hai Shia7f5d932020-08-04 00:41:24 +08008from 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
Irit Katriel373741a2021-05-18 14:53:57 +010022import traceback
Skip Montanaro4533f602001-08-20 20:28:48 +000023
Victor Stinner98c16c92020-09-23 23:21:19 +020024from unittest import mock
Antoine Pitrou557934f2009-11-06 22:41:14 +000025from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000026from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000027
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030028
29# Between fork() and exec(), only async-safe functions are allowed (issues
30# #12316 and #11870), and fork() from a worker thread is known to trigger
31# problems with some operating systems (issue #3863): skip problematic tests
32# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010033platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030034
35
Victor Stinnerb136b1a2021-04-16 14:33:10 +020036def restore_default_excepthook(testcase):
37 testcase.addCleanup(setattr, threading, 'excepthook', threading.excepthook)
38 threading.excepthook = threading.__excepthook__
39
40
Tim Peters84d54892005-01-08 06:03:17 +000041# A trivial mutable counter.
42class Counter(object):
43 def __init__(self):
44 self.value = 0
45 def inc(self):
46 self.value += 1
47 def dec(self):
48 self.value -= 1
49 def get(self):
50 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000051
52class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000053 def __init__(self, name, testcase, sema, mutex, nrunning):
54 threading.Thread.__init__(self, name=name)
55 self.testcase = testcase
56 self.sema = sema
57 self.mutex = mutex
58 self.nrunning = nrunning
59
Skip Montanaro4533f602001-08-20 20:28:48 +000060 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000061 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000062 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000063 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000064 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000065
Christian Heimes4fbc72b2008-03-22 00:47:35 +000066 with self.sema:
67 with self.mutex:
68 self.nrunning.inc()
69 if verbose:
70 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020071 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000072
Christian Heimes4fbc72b2008-03-22 00:47:35 +000073 time.sleep(delay)
74 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000075 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000076
Christian Heimes4fbc72b2008-03-22 00:47:35 +000077 with self.mutex:
78 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020079 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000080 if verbose:
81 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000082 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000083
Skip Montanaro4533f602001-08-20 20:28:48 +000084
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000085class BaseTestCase(unittest.TestCase):
86 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080087 self._threads = threading_helper.threading_setup()
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000088
89 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +080090 threading_helper.threading_cleanup(*self._threads)
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000091 test.support.reap_children()
92
93
94class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000095
Victor Stinner98c16c92020-09-23 23:21:19 +020096 @cpython_only
97 def test_name(self):
98 def func(): pass
99
100 thread = threading.Thread(name="myname1")
101 self.assertEqual(thread.name, "myname1")
102
103 # Convert int name to str
104 thread = threading.Thread(name=123)
105 self.assertEqual(thread.name, "123")
106
107 # target name is ignored if name is specified
108 thread = threading.Thread(target=func, name="myname2")
109 self.assertEqual(thread.name, "myname2")
110
111 with mock.patch.object(threading, '_counter', return_value=2):
112 thread = threading.Thread(name="")
113 self.assertEqual(thread.name, "Thread-2")
114
115 with mock.patch.object(threading, '_counter', return_value=3):
116 thread = threading.Thread()
117 self.assertEqual(thread.name, "Thread-3")
118
119 with mock.patch.object(threading, '_counter', return_value=5):
120 thread = threading.Thread(target=func)
121 self.assertEqual(thread.name, "Thread-5 (func)")
122
Erlend Egeberg Aasland9746cda2021-04-30 16:04:57 +0200123 @cpython_only
124 def test_disallow_instantiation(self):
125 # Ensure that the type disallows instantiation (bpo-43916)
126 lock = threading.Lock()
Erlend Egeberg Aasland0a3452e2021-06-24 01:46:25 +0200127 test.support.check_disallow_instantiation(self, type(lock))
Erlend Egeberg Aasland9746cda2021-04-30 16:04:57 +0200128
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
Miss Islington (bot)71dca6e2021-05-15 02:24:44 -0700910 def test_leak_without_join(self):
911 # bpo-37788: Test that a thread which is not joined explicitly
912 # does not leak. Test written for reference leak checks.
913 def noop(): pass
914 with threading_helper.wait_threads_exit():
915 threading.Thread(target=noop).start()
916 # Thread.join() is not called
BarneyStratford01c4fdd2021-02-02 20:24:24 +0000917
Victor Stinner45956b92013-11-12 16:37:55 +0100918
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000919class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000920
921 def _run_and_join(self, script):
922 script = """if 1:
923 import sys, os, time, threading
924
925 # a thread, which waits for the main program to terminate
926 def joiningfunc(mainthread):
927 mainthread.join()
928 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000929 # stdout is fully buffered because not a tty, we have to flush
930 # before exit.
931 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000932 \n""" + script
933
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200934 rc, out, err = assert_python_ok("-c", script)
935 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000936 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000937
938 def test_1_join_on_shutdown(self):
939 # The usual case: on exit, wait for a non-daemon thread
940 script = """if 1:
941 import os
942 t = threading.Thread(target=joiningfunc,
943 args=(threading.current_thread(),))
944 t.start()
945 time.sleep(0.1)
946 print('end of main')
947 """
948 self._run_and_join(script)
949
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000950 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200951 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000952 def test_2_join_in_forked_process(self):
953 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000954 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200955 from test import support
956
Jesse Nollera8513972008-07-17 16:49:17 +0000957 childpid = os.fork()
958 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200959 # parent process
960 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000961 sys.exit(0)
962
Victor Stinnera9f96872020-03-31 21:49:44 +0200963 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000964 t = threading.Thread(target=joiningfunc,
965 args=(threading.current_thread(),))
966 t.start()
967 print('end of main')
968 """
969 self._run_and_join(script)
970
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000971 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200972 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000973 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000974 # Like the test above, but fork() was called from a worker thread
975 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000976
Jesse Nollera8513972008-07-17 16:49:17 +0000977 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200978 from test import support
979
Jesse Nollera8513972008-07-17 16:49:17 +0000980 main_thread = threading.current_thread()
981 def worker():
982 childpid = os.fork()
983 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200984 # parent process
985 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000986 sys.exit(0)
987
Victor Stinnera9f96872020-03-31 21:49:44 +0200988 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000989 t = threading.Thread(target=joiningfunc,
990 args=(main_thread,))
991 print('end of main')
992 t.start()
993 t.join() # Should not block: main_thread is already stopped
994
995 w = threading.Thread(target=worker)
996 w.start()
997 """
998 self._run_and_join(script)
999
Victor Stinner26d31862011-07-01 14:26:24 +02001000 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -05001001 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001002 # Check that a daemon thread cannot crash the interpreter on shutdown
1003 # by manipulating internal structures that are being disposed of in
1004 # the main thread.
1005 script = """if True:
1006 import os
1007 import random
1008 import sys
1009 import time
1010 import threading
1011
1012 thread_has_run = set()
1013
1014 def random_io():
1015 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001016 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001017 with open(os.__file__, 'rb') as in_f:
1018 stuff = in_f.read(200)
1019 with open(os.devnull, 'wb') as null_f:
1020 null_f.write(stuff)
1021 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001022 thread_has_run.add(threading.current_thread())
1023
1024 def main():
1025 count = 0
1026 for _ in range(40):
1027 new_thread = threading.Thread(target=random_io)
1028 new_thread.daemon = True
1029 new_thread.start()
1030 count += 1
1031 while len(thread_has_run) < count:
1032 time.sleep(0.001)
1033 # Trigger process shutdown
1034 sys.exit(0)
1035
1036 main()
1037 """
1038 rc, out, err = assert_python_ok('-c', script)
1039 self.assertFalse(err)
1040
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001041 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +01001042 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001043 def test_reinit_tls_after_fork(self):
1044 # Issue #13817: fork() would deadlock in a multithreaded program with
1045 # the ad-hoc TLS implementation.
1046
1047 def do_fork_and_wait():
1048 # just fork a child process and wait it
1049 pid = os.fork()
1050 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +02001051 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001052 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001053 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001054
1055 # start a bunch of threads that will fork() child processes
1056 threads = []
1057 for i in range(16):
1058 t = threading.Thread(target=do_fork_and_wait)
1059 threads.append(t)
1060 t.start()
1061
1062 for t in threads:
1063 t.join()
1064
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001065 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
1066 def test_clear_threads_states_after_fork(self):
1067 # Issue #17094: check that threads states are cleared after fork()
1068
1069 # start a bunch of threads
1070 threads = []
1071 for i in range(16):
1072 t = threading.Thread(target=lambda : time.sleep(0.3))
1073 threads.append(t)
1074 t.start()
1075
1076 pid = os.fork()
1077 if pid == 0:
1078 # check that threads states have been cleared
1079 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +02001080 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001081 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001082 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001083 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001084 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001085
1086 for t in threads:
1087 t.join()
1088
Jesse Nollera8513972008-07-17 16:49:17 +00001089
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001090class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001091 def pipe(self):
1092 r, w = os.pipe()
1093 self.addCleanup(os.close, r)
1094 self.addCleanup(os.close, w)
1095 if hasattr(os, 'set_blocking'):
1096 os.set_blocking(r, False)
1097 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001098
1099 def test_threads_join(self):
1100 # Non-daemon threads should be joined at subinterpreter shutdown
1101 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001102 r, w = self.pipe()
1103 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001104 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001105 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001106 import threading
1107 import time
1108
Victor Stinner468e5fe2019-06-13 01:30:17 +02001109 def random_sleep():
1110 seconds = random.random() * 0.010
1111 time.sleep(seconds)
1112
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001113 def f():
1114 # Sleep a bit so that the thread is still running when
1115 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001116 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001117 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001118
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001119 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001120 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001121 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001122 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001123 self.assertEqual(ret, 0)
1124 # The thread was joined properly.
1125 self.assertEqual(os.read(r, 1), b"x")
1126
Antoine Pitrou7b476992013-09-07 23:38:37 +02001127 def test_threads_join_2(self):
1128 # Same as above, but a delay gets introduced after the thread's
1129 # Python code returned but before the thread state is deleted.
1130 # To achieve this, we register a thread-local object which sleeps
1131 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001132 r, w = self.pipe()
1133 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001134 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001135 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001136 import threading
1137 import time
1138
Victor Stinner468e5fe2019-06-13 01:30:17 +02001139 def random_sleep():
1140 seconds = random.random() * 0.010
1141 time.sleep(seconds)
1142
Antoine Pitrou7b476992013-09-07 23:38:37 +02001143 class Sleeper:
1144 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001145 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001146
1147 tls = threading.local()
1148
1149 def f():
1150 # Sleep a bit so that the thread is still running when
1151 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001152 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001153 tls.x = Sleeper()
1154 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001155
Antoine Pitrou7b476992013-09-07 23:38:37 +02001156 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001157 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001158 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001159 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001160 self.assertEqual(ret, 0)
1161 # The thread was joined properly.
1162 self.assertEqual(os.read(r, 1), b"x")
1163
Victor Stinner14d53312020-04-12 23:45:09 +02001164 @cpython_only
1165 def test_daemon_threads_fatal_error(self):
1166 subinterp_code = f"""if 1:
1167 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001168 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001169 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001170
Victor Stinner14d53312020-04-12 23:45:09 +02001171 def f():
1172 # Make sure the daemon thread is still running when
1173 # Py_EndInterpreter is called.
1174 time.sleep({test.support.SHORT_TIMEOUT})
1175 threading.Thread(target=f, daemon=True).start()
1176 """
1177 script = r"""if 1:
1178 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001179
Victor Stinner14d53312020-04-12 23:45:09 +02001180 _testcapi.run_in_subinterp(%r)
1181 """ % (subinterp_code,)
1182 with test.support.SuppressCrashReport():
1183 rc, out, err = assert_python_failure("-c", script)
1184 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1185 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001186
1187
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001188class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001189 # A RuntimeError should be raised if Thread.start() is called
1190 # multiple times.
1191 def test_start_thread_again(self):
1192 thread = threading.Thread()
1193 thread.start()
1194 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001195 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001196
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001197 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001198 current_thread = threading.current_thread()
1199 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001200
1201 def test_joining_inactive_thread(self):
1202 thread = threading.Thread()
1203 self.assertRaises(RuntimeError, thread.join)
1204
1205 def test_daemonize_active_thread(self):
1206 thread = threading.Thread()
1207 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001208 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001209 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001210
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001211 def test_releasing_unacquired_lock(self):
1212 lock = threading.Lock()
1213 self.assertRaises(RuntimeError, lock.release)
1214
Ned Deily9a7c5242011-05-28 00:19:56 -07001215 def test_recursion_limit(self):
1216 # Issue 9670
1217 # test that excessive recursion within a non-main thread causes
1218 # an exception rather than crashing the interpreter on platforms
1219 # like Mac OS X or FreeBSD which have small default stack sizes
1220 # for threads
1221 script = """if True:
1222 import threading
1223
1224 def recurse():
1225 return recurse()
1226
1227 def outer():
1228 try:
1229 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001230 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001231 pass
1232
1233 w = threading.Thread(target=outer)
1234 w.start()
1235 w.join()
1236 print('end of main thread')
1237 """
1238 expected_output = "end of main thread\n"
1239 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001240 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001241 stdout, stderr = p.communicate()
1242 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001243 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001244 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001245
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001246 def test_print_exception(self):
1247 script = r"""if True:
1248 import threading
1249 import time
1250
1251 running = False
1252 def run():
1253 global running
1254 running = True
1255 while running:
1256 time.sleep(0.01)
1257 1/0
1258 t = threading.Thread(target=run)
1259 t.start()
1260 while not running:
1261 time.sleep(0.01)
1262 running = False
1263 t.join()
1264 """
1265 rc, out, err = assert_python_ok("-c", script)
1266 self.assertEqual(out, b'')
1267 err = err.decode()
1268 self.assertIn("Exception in thread", err)
1269 self.assertIn("Traceback (most recent call last):", err)
1270 self.assertIn("ZeroDivisionError", err)
1271 self.assertNotIn("Unhandled exception", err)
1272
1273 def test_print_exception_stderr_is_none_1(self):
1274 script = r"""if True:
1275 import sys
1276 import threading
1277 import time
1278
1279 running = False
1280 def run():
1281 global running
1282 running = True
1283 while running:
1284 time.sleep(0.01)
1285 1/0
1286 t = threading.Thread(target=run)
1287 t.start()
1288 while not running:
1289 time.sleep(0.01)
1290 sys.stderr = None
1291 running = False
1292 t.join()
1293 """
1294 rc, out, err = assert_python_ok("-c", script)
1295 self.assertEqual(out, b'')
1296 err = err.decode()
1297 self.assertIn("Exception in thread", err)
1298 self.assertIn("Traceback (most recent call last):", err)
1299 self.assertIn("ZeroDivisionError", err)
1300 self.assertNotIn("Unhandled exception", err)
1301
1302 def test_print_exception_stderr_is_none_2(self):
1303 script = r"""if True:
1304 import sys
1305 import threading
1306 import time
1307
1308 running = False
1309 def run():
1310 global running
1311 running = True
1312 while running:
1313 time.sleep(0.01)
1314 1/0
1315 sys.stderr = None
1316 t = threading.Thread(target=run)
1317 t.start()
1318 while not running:
1319 time.sleep(0.01)
1320 running = False
1321 t.join()
1322 """
1323 rc, out, err = assert_python_ok("-c", script)
1324 self.assertEqual(out, b'')
1325 self.assertNotIn("Unhandled exception", err.decode())
1326
Victor Stinnereec93312016-08-18 18:13:10 +02001327 def test_bare_raise_in_brand_new_thread(self):
1328 def bare_raise():
1329 raise
1330
1331 class Issue27558(threading.Thread):
1332 exc = None
1333
1334 def run(self):
1335 try:
1336 bare_raise()
1337 except Exception as exc:
1338 self.exc = exc
1339
1340 thread = Issue27558()
1341 thread.start()
1342 thread.join()
1343 self.assertIsNotNone(thread.exc)
1344 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001345 # explicitly break the reference cycle to not leak a dangling thread
1346 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001347
Irit Katriel373741a2021-05-18 14:53:57 +01001348 def test_multithread_modify_file_noerror(self):
1349 # See issue25872
1350 def modify_file():
1351 with open(os_helper.TESTFN, 'w', encoding='utf-8') as fp:
1352 fp.write(' ')
1353 traceback.format_stack()
1354
1355 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1356 threads = [
1357 threading.Thread(target=modify_file)
1358 for i in range(100)
1359 ]
1360 for t in threads:
1361 t.start()
1362 t.join()
1363
Victor Stinnercd590a72019-05-28 00:39:52 +02001364
1365class ThreadRunFail(threading.Thread):
1366 def run(self):
1367 raise ValueError("run failed")
1368
1369
1370class ExceptHookTests(BaseTestCase):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001371 def setUp(self):
1372 restore_default_excepthook(self)
1373 super().setUp()
1374
Victor Stinnercd590a72019-05-28 00:39:52 +02001375 def test_excepthook(self):
1376 with support.captured_output("stderr") as stderr:
1377 thread = ThreadRunFail(name="excepthook thread")
1378 thread.start()
1379 thread.join()
1380
1381 stderr = stderr.getvalue().strip()
1382 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1383 self.assertIn('Traceback (most recent call last):\n', stderr)
1384 self.assertIn(' raise ValueError("run failed")', stderr)
1385 self.assertIn('ValueError: run failed', stderr)
1386
1387 @support.cpython_only
1388 def test_excepthook_thread_None(self):
1389 # threading.excepthook called with thread=None: log the thread
1390 # identifier in this case.
1391 with support.captured_output("stderr") as stderr:
1392 try:
1393 raise ValueError("bug")
1394 except Exception as exc:
1395 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001396 try:
1397 threading.excepthook(args)
1398 finally:
1399 # Explicitly break a reference cycle
1400 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001401
1402 stderr = stderr.getvalue().strip()
1403 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1404 self.assertIn('Traceback (most recent call last):\n', stderr)
1405 self.assertIn(' raise ValueError("bug")', stderr)
1406 self.assertIn('ValueError: bug', stderr)
1407
1408 def test_system_exit(self):
1409 class ThreadExit(threading.Thread):
1410 def run(self):
1411 sys.exit(1)
1412
1413 # threading.excepthook() silently ignores SystemExit
1414 with support.captured_output("stderr") as stderr:
1415 thread = ThreadExit()
1416 thread.start()
1417 thread.join()
1418
1419 self.assertEqual(stderr.getvalue(), '')
1420
1421 def test_custom_excepthook(self):
1422 args = None
1423
1424 def hook(hook_args):
1425 nonlocal args
1426 args = hook_args
1427
1428 try:
1429 with support.swap_attr(threading, 'excepthook', hook):
1430 thread = ThreadRunFail()
1431 thread.start()
1432 thread.join()
1433
1434 self.assertEqual(args.exc_type, ValueError)
1435 self.assertEqual(str(args.exc_value), 'run failed')
1436 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1437 self.assertIs(args.thread, thread)
1438 finally:
1439 # Break reference cycle
1440 args = None
1441
1442 def test_custom_excepthook_fail(self):
1443 def threading_hook(args):
1444 raise ValueError("threading_hook failed")
1445
1446 err_str = None
1447
1448 def sys_hook(exc_type, exc_value, exc_traceback):
1449 nonlocal err_str
1450 err_str = str(exc_value)
1451
1452 with support.swap_attr(threading, 'excepthook', threading_hook), \
1453 support.swap_attr(sys, 'excepthook', sys_hook), \
1454 support.captured_output('stderr') as stderr:
1455 thread = ThreadRunFail()
1456 thread.start()
1457 thread.join()
1458
1459 self.assertEqual(stderr.getvalue(),
1460 'Exception in threading.excepthook:\n')
1461 self.assertEqual(err_str, 'threading_hook failed')
1462
Mario Corchero750c5ab2020-11-12 18:27:44 +01001463 def test_original_excepthook(self):
1464 def run_thread():
1465 with support.captured_output("stderr") as output:
1466 thread = ThreadRunFail(name="excepthook thread")
1467 thread.start()
1468 thread.join()
1469 return output.getvalue()
1470
1471 def threading_hook(args):
1472 print("Running a thread failed", file=sys.stderr)
1473
1474 default_output = run_thread()
1475 with support.swap_attr(threading, 'excepthook', threading_hook):
1476 custom_hook_output = run_thread()
1477 threading.excepthook = threading.__excepthook__
1478 recovered_output = run_thread()
1479
1480 self.assertEqual(default_output, recovered_output)
1481 self.assertNotEqual(default_output, custom_hook_output)
1482 self.assertEqual(custom_hook_output, "Running a thread failed\n")
1483
Victor Stinnercd590a72019-05-28 00:39:52 +02001484
R David Murray19aeb432013-03-30 17:19:38 -04001485class TimerTests(BaseTestCase):
1486
1487 def setUp(self):
1488 BaseTestCase.setUp(self)
1489 self.callback_args = []
1490 self.callback_event = threading.Event()
1491
1492 def test_init_immutable_default_args(self):
1493 # Issue 17435: constructor defaults were mutable objects, they could be
1494 # mutated via the object attributes and affect other Timer objects.
1495 timer1 = threading.Timer(0.01, self._callback_spy)
1496 timer1.start()
1497 self.callback_event.wait()
1498 timer1.args.append("blah")
1499 timer1.kwargs["foo"] = "bar"
1500 self.callback_event.clear()
1501 timer2 = threading.Timer(0.01, self._callback_spy)
1502 timer2.start()
1503 self.callback_event.wait()
1504 self.assertEqual(len(self.callback_args), 2)
1505 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001506 timer1.join()
1507 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001508
1509 def _callback_spy(self, *args, **kwargs):
1510 self.callback_args.append((args[:], kwargs.copy()))
1511 self.callback_event.set()
1512
Antoine Pitrou557934f2009-11-06 22:41:14 +00001513class LockTests(lock_tests.LockTests):
1514 locktype = staticmethod(threading.Lock)
1515
Antoine Pitrou434736a2009-11-10 18:46:01 +00001516class PyRLockTests(lock_tests.RLockTests):
1517 locktype = staticmethod(threading._PyRLock)
1518
Charles-François Natali6b671b22012-01-28 11:36:04 +01001519@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001520class CRLockTests(lock_tests.RLockTests):
1521 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001522
1523class EventTests(lock_tests.EventTests):
1524 eventtype = staticmethod(threading.Event)
1525
1526class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001527 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001528 locktype = staticmethod(threading.Condition)
1529
1530class ConditionTests(lock_tests.ConditionTests):
1531 condtype = staticmethod(threading.Condition)
1532
1533class SemaphoreTests(lock_tests.SemaphoreTests):
1534 semtype = staticmethod(threading.Semaphore)
1535
1536class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1537 semtype = staticmethod(threading.BoundedSemaphore)
1538
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001539class BarrierTests(lock_tests.BarrierTests):
1540 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001541
Matěj Cepl608876b2019-05-23 22:30:00 +02001542
Martin Panter19e69c52015-11-14 12:46:42 +00001543class MiscTestCase(unittest.TestCase):
1544 def test__all__(self):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001545 restore_default_excepthook(self)
1546
Martin Panter19e69c52015-11-14 12:46:42 +00001547 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001548 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001549 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001550 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001551
Matěj Cepl608876b2019-05-23 22:30:00 +02001552
1553class InterruptMainTests(unittest.TestCase):
Antoine Pitrouba251c22021-03-11 23:35:45 +01001554 def check_interrupt_main_with_signal_handler(self, signum):
1555 def handler(signum, frame):
1556 1/0
1557
1558 old_handler = signal.signal(signum, handler)
1559 self.addCleanup(signal.signal, signum, old_handler)
1560
1561 with self.assertRaises(ZeroDivisionError):
1562 _thread.interrupt_main()
1563
1564 def check_interrupt_main_noerror(self, signum):
1565 handler = signal.getsignal(signum)
1566 try:
1567 # No exception should arise.
1568 signal.signal(signum, signal.SIG_IGN)
1569 _thread.interrupt_main(signum)
1570
1571 signal.signal(signum, signal.SIG_DFL)
1572 _thread.interrupt_main(signum)
1573 finally:
1574 # Restore original handler
1575 signal.signal(signum, handler)
1576
Matěj Cepl608876b2019-05-23 22:30:00 +02001577 def test_interrupt_main_subthread(self):
1578 # Calling start_new_thread with a function that executes interrupt_main
1579 # should raise KeyboardInterrupt upon completion.
1580 def call_interrupt():
1581 _thread.interrupt_main()
1582 t = threading.Thread(target=call_interrupt)
1583 with self.assertRaises(KeyboardInterrupt):
1584 t.start()
1585 t.join()
1586 t.join()
1587
1588 def test_interrupt_main_mainthread(self):
1589 # Make sure that if interrupt_main is called in main thread that
1590 # KeyboardInterrupt is raised instantly.
1591 with self.assertRaises(KeyboardInterrupt):
1592 _thread.interrupt_main()
1593
Antoine Pitrouba251c22021-03-11 23:35:45 +01001594 def test_interrupt_main_with_signal_handler(self):
1595 self.check_interrupt_main_with_signal_handler(signal.SIGINT)
1596 self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
Matěj Cepl608876b2019-05-23 22:30:00 +02001597
Antoine Pitrouba251c22021-03-11 23:35:45 +01001598 def test_interrupt_main_noerror(self):
1599 self.check_interrupt_main_noerror(signal.SIGINT)
1600 self.check_interrupt_main_noerror(signal.SIGTERM)
1601
1602 def test_interrupt_main_invalid_signal(self):
1603 self.assertRaises(ValueError, _thread.interrupt_main, -1)
1604 self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
1605 self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
Matěj Cepl608876b2019-05-23 22:30:00 +02001606
Miss Islington (bot)37bdd222021-07-19 04:15:58 -07001607 @threading_helper.reap_threads
1608 def test_can_interrupt_tight_loops(self):
1609 cont = [True]
1610 started = [False]
1611 interrupted = [False]
1612
1613 def worker(started, cont, interrupted):
1614 iterations = 100_000_000
1615 started[0] = True
1616 while cont[0]:
1617 if iterations:
1618 iterations -= 1
1619 else:
1620 return
1621 pass
1622 interrupted[0] = True
1623
1624 t = threading.Thread(target=worker,args=(started, cont, interrupted))
1625 t.start()
1626 while not started[0]:
1627 pass
1628 cont[0] = False
1629 t.join()
1630 self.assertTrue(interrupted[0])
1631
Matěj Cepl608876b2019-05-23 22:30:00 +02001632
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001633class AtexitTests(unittest.TestCase):
1634
1635 def test_atexit_output(self):
1636 rc, out, err = assert_python_ok("-c", """if True:
1637 import threading
1638
1639 def run_last():
1640 print('parrot')
1641
1642 threading._register_atexit(run_last)
1643 """)
1644
1645 self.assertFalse(err)
1646 self.assertEqual(out.strip(), b'parrot')
1647
1648 def test_atexit_called_once(self):
1649 rc, out, err = assert_python_ok("-c", """if True:
1650 import threading
1651 from unittest.mock import Mock
1652
1653 mock = Mock()
1654 threading._register_atexit(mock)
1655 mock.assert_not_called()
1656 # force early shutdown to ensure it was called once
1657 threading._shutdown()
1658 mock.assert_called_once()
1659 """)
1660
1661 self.assertFalse(err)
1662
1663 def test_atexit_after_shutdown(self):
1664 # The only way to do this is by registering an atexit within
1665 # an atexit, which is intended to raise an exception.
1666 rc, out, err = assert_python_ok("-c", """if True:
1667 import threading
1668
1669 def func():
1670 pass
1671
1672 def run_last():
1673 threading._register_atexit(func)
1674
1675 threading._register_atexit(run_last)
1676 """)
1677
1678 self.assertTrue(err)
1679 self.assertIn("RuntimeError: can't register atexit after shutdown",
1680 err.decode())
1681
1682
Tim Peters84d54892005-01-08 06:03:17 +00001683if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001684 unittest.main()