blob: b563797cbd0d39e27d00f3cbdbc58a0264cdbf2b [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()
127 tp = type(lock)
128 self.assertRaises(TypeError, tp)
129
Tim Peters84d54892005-01-08 06:03:17 +0000130 # Create a bunch of threads, let each do some work, wait until all are
131 # done.
132 def test_various_ops(self):
133 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
134 # times about 1 second per clump).
135 NUMTASKS = 10
136
137 # no more than 3 of the 10 can run at once
138 sema = threading.BoundedSemaphore(value=3)
139 mutex = threading.RLock()
140 numrunning = Counter()
141
142 threads = []
143
144 for i in range(NUMTASKS):
145 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
146 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200147 self.assertIsNone(t.ident)
148 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000149 t.start()
150
Jake Teslerb121f632019-05-22 08:43:17 -0700151 if hasattr(threading, 'get_native_id'):
152 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
153 self.assertNotIn(None, native_ids)
154 self.assertEqual(len(native_ids), NUMTASKS + 1)
155
Tim Peters84d54892005-01-08 06:03:17 +0000156 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000157 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000158 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200159 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200160 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000161 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200162 self.assertIsNotNone(t.ident)
163 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000164 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000165 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000166 self.assertEqual(numrunning.get(), 0)
167
Benjamin Petersond23f8222009-04-05 19:13:16 +0000168 def test_ident_of_no_threading_threads(self):
169 # The ident still must work for the main thread and dummy threads.
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700170 self.assertIsNotNone(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000171 def f():
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700172 ident.append(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000173 done.set()
174 done = threading.Event()
175 ident = []
Hai Shie80697d2020-05-28 06:10:27 +0800176 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700177 tid = _thread.start_new_thread(f, ())
178 done.wait()
179 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000180 # Kill the "immortal" _DummyThread
181 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000182
Victor Stinner8c663fd2017-11-08 14:44:44 -0800183 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000184 def test_various_ops_small_stack(self):
185 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800186 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187 try:
188 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000189 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000190 raise unittest.SkipTest(
191 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000192 self.test_various_ops()
193 threading.stack_size(0)
194
Victor Stinner8c663fd2017-11-08 14:44:44 -0800195 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000196 def test_various_ops_large_stack(self):
197 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800198 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000199 try:
200 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000201 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000202 raise unittest.SkipTest(
203 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000204 self.test_various_ops()
205 threading.stack_size(0)
206
Tim Peters711906e2005-01-08 07:30:42 +0000207 def test_foreign_thread(self):
208 # Check that a "foreign" thread can use the threading module.
209 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000210 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000211 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000212 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000213 mutex.release()
214
215 mutex = threading.Lock()
216 mutex.acquire()
Hai Shie80697d2020-05-28 06:10:27 +0800217 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700218 tid = _thread.start_new_thread(f, (mutex,))
219 # Wait for the thread to finish.
220 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000221 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000222 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800223 #Issue 29376
224 self.assertTrue(threading._active[tid].is_alive())
225 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000226 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000227
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000228 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
229 # exposed at the Python level. This test relies on ctypes to get at it.
230 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200231 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232
233 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200234 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000235
236 class AsyncExc(Exception):
237 pass
238
239 exception = ctypes.py_object(AsyncExc)
240
Antoine Pitroube4d8092009-10-18 18:27:17 +0000241 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200242 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200243 self.assertIsInstance(tid, int)
244 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000245
246 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200247 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000248 # The exception is async, so we might have to keep the VM busy until
249 # it notices.
250 while True:
251 pass
252 except AsyncExc:
253 pass
254 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000255 # This code is unreachable but it reflects the intent. If we wanted
256 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000257 self.fail("AsyncExc not raised")
258 try:
259 self.assertEqual(result, 1) # one thread state modified
260 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000261 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000262 pass
263
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000264 # `worker_started` is set by the thread when it's inside a try/except
265 # block waiting to catch the asynchronously set AsyncExc exception.
266 # `worker_saw_exception` is set by the thread upon catching that
267 # exception.
268 worker_started = threading.Event()
269 worker_saw_exception = threading.Event()
270
271 class Worker(threading.Thread):
272 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200273 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000274 self.finished = False
275
276 try:
277 while True:
278 worker_started.set()
279 time.sleep(0.1)
280 except AsyncExc:
281 self.finished = True
282 worker_saw_exception.set()
283
284 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000285 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000286 t.start()
287 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000288 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000289
290 # Try a thread id that doesn't make sense.
291 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000292 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200293 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000294 self.assertEqual(result, 0) # no thread states modified
295
296 # Now raise an exception in the worker thread.
297 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000298 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000299 ret = worker_started.wait()
300 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000301 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000302 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200303 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000304 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000305 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200306 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000307 self.assertEqual(result, 1) # one thread state modified
308 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000309 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100310 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000312 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000313 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000314 if t.finished:
315 t.join()
316 # else the thread is still running, and we have no way to kill it
317
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000318 def test_limbo_cleanup(self):
319 # Issue 7481: Failure to start thread should cleanup the limbo map.
320 def fail_new_thread(*args):
321 raise threading.ThreadError()
322 _start_new_thread = threading._start_new_thread
323 threading._start_new_thread = fail_new_thread
324 try:
325 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000326 self.assertRaises(threading.ThreadError, t.start)
327 self.assertFalse(
328 t in threading._limbo,
329 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000330 finally:
331 threading._start_new_thread = _start_new_thread
332
Min ho Kimc4cacc82019-07-31 08:16:13 +1000333 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000334 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
335 # very late on python exit: on deallocation of a running thread for
336 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200337 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000338
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200339 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000340 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000341
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000342 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000343 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000344 ready.acquire()
345
Christian Heimes7d2ff882007-11-30 14:35:04 +0000346 # Module globals are cleared before __del__ is run
347 # So we save the functions in class dict
348 class C:
349 ensure = ctypes.pythonapi.PyGILState_Ensure
350 release = ctypes.pythonapi.PyGILState_Release
351 def __del__(self):
352 state = self.ensure()
353 self.release(state)
354
355 def waitingThread():
356 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000357 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000358 time.sleep(100)
359
Georg Brandl2067bfd2008-05-25 13:05:15 +0000360 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000361 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000362 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200363 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000364 self.assertEqual(rc, 42)
365
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000366 def test_finalize_with_trace(self):
367 # Issue1733757
368 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200369 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000370 import sys, threading
371
372 # A deadlock-killer, to prevent the
373 # testsuite to hang forever
374 def killer():
375 import os, time
376 time.sleep(2)
377 print('program blocked; aborting')
378 os._exit(2)
379 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000380 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000381 t.start()
382
383 # This is the trace function
384 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000385 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000386 return func
387
388 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200389 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000390
Antoine Pitrou011bd622009-10-20 21:52:47 +0000391 def test_join_nondaemon_on_shutdown(self):
392 # Issue 1722344
393 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200394 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000395 import threading
396 from time import sleep
397
398 def child():
399 sleep(1)
400 # As a non-daemon thread we SHOULD wake up and nothing
401 # should be torn down yet
402 print("Woke up, sleep function is:", sleep)
403
404 threading.Thread(target=child).start()
405 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200406 """)
407 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000408 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200409 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000410
Christian Heimes1af737c2008-01-23 08:24:23 +0000411 def test_enumerate_after_join(self):
412 # Try hard to trigger #1703448: a thread is still returned in
413 # threading.enumerate() after it has been join()ed.
414 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000415 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000416 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000417 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000418 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000419 t = threading.Thread(target=lambda: None)
420 t.start()
421 t.join()
422 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000423 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000424 "#1703448 triggered after %d trials: %s" % (i, l))
425 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000426 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000427
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000428 def test_no_refcycle_through_target(self):
429 class RunSelfFunction(object):
430 def __init__(self, should_raise):
431 # The links in this refcycle from Thread back to self
432 # should be cleaned up when the thread completes.
433 self.should_raise = should_raise
434 self.thread = threading.Thread(target=self._run,
435 args=(self,),
436 kwargs={'yet_another':self})
437 self.thread.start()
438
439 def _run(self, other_ref, yet_another):
440 if self.should_raise:
441 raise SystemExit
442
Victor Stinnerb136b1a2021-04-16 14:33:10 +0200443 restore_default_excepthook(self)
444
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000445 cyclic_object = RunSelfFunction(should_raise=False)
446 weak_cyclic_object = weakref.ref(cyclic_object)
447 cyclic_object.thread.join()
448 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000449 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 msg=('%d references still around' %
451 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000452
453 raising_cyclic_object = RunSelfFunction(should_raise=True)
454 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
455 raising_cyclic_object.thread.join()
456 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000457 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000458 msg=('%d references still around' %
459 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000460
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000461 def test_old_threading_api(self):
462 # Just a quick sanity check to make sure the old method names are
463 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000464 t = threading.Thread()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700465 with self.assertWarnsRegex(DeprecationWarning,
466 r'get the daemon attribute'):
467 t.isDaemon()
468 with self.assertWarnsRegex(DeprecationWarning,
469 r'set the daemon attribute'):
470 t.setDaemon(True)
471 with self.assertWarnsRegex(DeprecationWarning,
472 r'get the name attribute'):
473 t.getName()
474 with self.assertWarnsRegex(DeprecationWarning,
475 r'set the name attribute'):
476 t.setName("name")
477
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000478 e = threading.Event()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700479 with self.assertWarnsRegex(DeprecationWarning, 'use is_set()'):
480 e.isSet()
481
482 cond = threading.Condition()
483 cond.acquire()
484 with self.assertWarnsRegex(DeprecationWarning, 'use notify_all()'):
485 cond.notifyAll()
486
487 with self.assertWarnsRegex(DeprecationWarning, 'use active_count()'):
488 threading.activeCount()
489 with self.assertWarnsRegex(DeprecationWarning, 'use current_thread()'):
490 threading.currentThread()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000491
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000492 def test_repr_daemon(self):
493 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200494 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000495 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200496 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000497
luzpaza5293b42017-11-05 07:37:50 -0600498 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000499 t = threading.Thread()
500 self.assertFalse(t.daemon)
501 t = threading.Thread(daemon=False)
502 self.assertFalse(t.daemon)
503 t = threading.Thread(daemon=True)
504 self.assertTrue(t.daemon)
505
Victor Stinner5909a492020-11-16 15:20:34 +0100506 @unittest.skipUnless(hasattr(os, 'fork'), 'needs os.fork()')
507 def test_fork_at_exit(self):
508 # bpo-42350: Calling os.fork() after threading._shutdown() must
509 # not log an error.
510 code = textwrap.dedent("""
511 import atexit
512 import os
513 import sys
514 from test.support import wait_process
515
516 # Import the threading module to register its "at fork" callback
517 import threading
518
519 def exit_handler():
520 pid = os.fork()
521 if not pid:
522 print("child process ok", file=sys.stderr, flush=True)
523 # child process
Victor Stinner5909a492020-11-16 15:20:34 +0100524 else:
525 wait_process(pid, exitcode=0)
526
527 # exit_handler() will be called after threading._shutdown()
528 atexit.register(exit_handler)
529 """)
530 _, out, err = assert_python_ok("-c", code)
531 self.assertEqual(out, b'')
532 self.assertEqual(err.rstrip(), b'child process ok')
533
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200534 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
535 def test_dummy_thread_after_fork(self):
536 # Issue #14308: a dummy thread in the active list doesn't mess up
537 # the after-fork mechanism.
538 code = """if 1:
539 import _thread, threading, os, time
540
541 def background_thread(evt):
542 # Creates and registers the _DummyThread instance
543 threading.current_thread()
544 evt.set()
545 time.sleep(10)
546
547 evt = threading.Event()
548 _thread.start_new_thread(background_thread, (evt,))
549 evt.wait()
550 assert threading.active_count() == 2, threading.active_count()
551 if os.fork() == 0:
552 assert threading.active_count() == 1, threading.active_count()
553 os._exit(0)
554 else:
555 os.wait()
556 """
557 _, out, err = assert_python_ok("-c", code)
558 self.assertEqual(out, b'')
559 self.assertEqual(err, b'')
560
Charles-François Natali9939cc82013-08-30 23:32:53 +0200561 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
562 def test_is_alive_after_fork(self):
563 # Try hard to trigger #18418: is_alive() could sometimes be True on
564 # threads that vanished after a fork.
565 old_interval = sys.getswitchinterval()
566 self.addCleanup(sys.setswitchinterval, old_interval)
567
568 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100569 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200570
571 for i in range(20):
572 t = threading.Thread(target=lambda: None)
573 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200574 pid = os.fork()
575 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700576 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200577 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700578 t.join()
579
Victor Stinnera9f96872020-03-31 21:49:44 +0200580 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200581
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300582 def test_main_thread(self):
583 main = threading.main_thread()
584 self.assertEqual(main.name, 'MainThread')
585 self.assertEqual(main.ident, threading.current_thread().ident)
586 self.assertEqual(main.ident, threading.get_ident())
587
588 def f():
589 self.assertNotEqual(threading.main_thread().ident,
590 threading.current_thread().ident)
591 th = threading.Thread(target=f)
592 th.start()
593 th.join()
594
595 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
596 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
597 def test_main_thread_after_fork(self):
598 code = """if 1:
599 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200600 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300601
602 pid = os.fork()
603 if pid == 0:
604 main = threading.main_thread()
605 print(main.name)
606 print(main.ident == threading.current_thread().ident)
607 print(main.ident == threading.get_ident())
608 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200609 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300610 """
611 _, out, err = assert_python_ok("-c", code)
612 data = out.decode().replace('\r', '')
613 self.assertEqual(err, b"")
614 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
615
616 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
617 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
618 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
619 def test_main_thread_after_fork_from_nonmain_thread(self):
620 code = """if 1:
621 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200622 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300623
Victor Stinner98c16c92020-09-23 23:21:19 +0200624 def func():
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300625 pid = os.fork()
626 if pid == 0:
627 main = threading.main_thread()
628 print(main.name)
629 print(main.ident == threading.current_thread().ident)
630 print(main.ident == threading.get_ident())
631 # stdout is fully buffered because not a tty,
632 # we have to flush before exit.
633 sys.stdout.flush()
634 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200635 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300636
Victor Stinner98c16c92020-09-23 23:21:19 +0200637 th = threading.Thread(target=func)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300638 th.start()
639 th.join()
640 """
641 _, out, err = assert_python_ok("-c", code)
642 data = out.decode().replace('\r', '')
643 self.assertEqual(err, b"")
Victor Stinner98c16c92020-09-23 23:21:19 +0200644 self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300645
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200646 def test_main_thread_during_shutdown(self):
647 # bpo-31516: current_thread() should still point to the main thread
648 # at shutdown
649 code = """if 1:
650 import gc, threading
651
652 main_thread = threading.current_thread()
653 assert main_thread is threading.main_thread() # sanity check
654
655 class RefCycle:
656 def __init__(self):
657 self.cycle = self
658
659 def __del__(self):
660 print("GC:",
661 threading.current_thread() is main_thread,
662 threading.main_thread() is main_thread,
663 threading.enumerate() == [main_thread])
664
665 RefCycle()
666 gc.collect() # sanity check
667 x = RefCycle()
668 """
669 _, out, err = assert_python_ok("-c", code)
670 data = out.decode()
671 self.assertEqual(err, b"")
672 self.assertEqual(data.splitlines(),
673 ["GC: True True True"] * 2)
674
Victor Stinner468e5fe2019-06-13 01:30:17 +0200675 def test_finalization_shutdown(self):
676 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
677 # until Python thread states of all non-daemon threads get deleted.
678 #
679 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
680 # test the finalization of the main interpreter.
681 code = """if 1:
682 import os
683 import threading
684 import time
685 import random
686
687 def random_sleep():
688 seconds = random.random() * 0.010
689 time.sleep(seconds)
690
691 class Sleeper:
692 def __del__(self):
693 random_sleep()
694
695 tls = threading.local()
696
697 def f():
698 # Sleep a bit so that the thread is still running when
699 # Py_Finalize() is called.
700 random_sleep()
701 tls.x = Sleeper()
702 random_sleep()
703
704 threading.Thread(target=f).start()
705 random_sleep()
706 """
707 rc, out, err = assert_python_ok("-c", code)
708 self.assertEqual(err, b"")
709
Antoine Pitrou7b476992013-09-07 23:38:37 +0200710 def test_tstate_lock(self):
711 # Test an implementation detail of Thread objects.
712 started = _thread.allocate_lock()
713 finish = _thread.allocate_lock()
714 started.acquire()
715 finish.acquire()
716 def f():
717 started.release()
718 finish.acquire()
719 time.sleep(0.01)
720 # The tstate lock is None until the thread is started
721 t = threading.Thread(target=f)
722 self.assertIs(t._tstate_lock, None)
723 t.start()
724 started.acquire()
725 self.assertTrue(t.is_alive())
726 # The tstate lock can't be acquired when the thread is running
727 # (or suspended).
728 tstate_lock = t._tstate_lock
729 self.assertFalse(tstate_lock.acquire(timeout=0), False)
730 finish.release()
731 # When the thread ends, the state_lock can be successfully
732 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100733 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200734 # But is_alive() is still True: we hold _tstate_lock now, which
735 # prevents is_alive() from knowing the thread's end-of-life C code
736 # is done.
737 self.assertTrue(t.is_alive())
738 # Let is_alive() find out the C code is done.
739 tstate_lock.release()
740 self.assertFalse(t.is_alive())
741 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200742 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700743 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200744
Tim Peters72460fa2013-09-09 18:48:24 -0500745 def test_repr_stopped(self):
746 # Verify that "stopped" shows up in repr(Thread) appropriately.
747 started = _thread.allocate_lock()
748 finish = _thread.allocate_lock()
749 started.acquire()
750 finish.acquire()
751 def f():
752 started.release()
753 finish.acquire()
754 t = threading.Thread(target=f)
755 t.start()
756 started.acquire()
757 self.assertIn("started", repr(t))
758 finish.release()
759 # "stopped" should appear in the repr in a reasonable amount of time.
760 # Implementation detail: as of this writing, that's trivially true
761 # if .join() is called, and almost trivially true if .is_alive() is
762 # called. The detail we're testing here is that "stopped" shows up
763 # "all on its own".
764 LOOKING_FOR = "stopped"
765 for i in range(500):
766 if LOOKING_FOR in repr(t):
767 break
768 time.sleep(0.01)
769 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700770 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000771
Tim Peters7634e1c2013-10-08 20:55:51 -0500772 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500773 # BoundedSemaphore should raise ValueError if released too often.
774 for limit in range(1, 10):
775 bs = threading.BoundedSemaphore(limit)
776 threads = [threading.Thread(target=bs.acquire)
777 for _ in range(limit)]
778 for t in threads:
779 t.start()
780 for t in threads:
781 t.join()
782 threads = [threading.Thread(target=bs.release)
783 for _ in range(limit)]
784 for t in threads:
785 t.start()
786 for t in threads:
787 t.join()
788 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500789
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200790 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100791 def test_frame_tstate_tracing(self):
792 # Issue #14432: Crash when a generator is created in a C thread that is
793 # destroyed while the generator is still used. The issue was that a
794 # generator contains a frame, and the frame kept a reference to the
795 # Python state of the destroyed C thread. The crash occurs when a trace
796 # function is setup.
797
798 def noop_trace(frame, event, arg):
799 # no operation
800 return noop_trace
801
802 def generator():
803 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300804 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100805
806 def callback():
807 if callback.gen is None:
808 callback.gen = generator()
809 return next(callback.gen)
810 callback.gen = None
811
812 old_trace = sys.gettrace()
813 sys.settrace(noop_trace)
814 try:
815 # Install a trace function
816 threading.settrace(noop_trace)
817
818 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200819 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100820 _testcapi.call_in_temporary_c_thread(callback)
821
822 # Call the generator in a different Python thread, check that the
823 # generator didn't keep a reference to the destroyed thread state
824 for test in range(3):
825 # The trace function is still called here
826 callback()
827 finally:
828 sys.settrace(old_trace)
829
Mario Corchero0001a1b2020-11-04 10:27:43 +0100830 def test_gettrace(self):
831 def noop_trace(frame, event, arg):
832 # no operation
833 return noop_trace
834 old_trace = threading.gettrace()
835 try:
836 threading.settrace(noop_trace)
837 trace_func = threading.gettrace()
838 self.assertEqual(noop_trace,trace_func)
839 finally:
840 threading.settrace(old_trace)
841
842 def test_getprofile(self):
843 def fn(*args): pass
844 old_profile = threading.getprofile()
845 try:
846 threading.setprofile(fn)
847 self.assertEqual(fn, threading.getprofile())
848 finally:
849 threading.setprofile(old_profile)
850
Victor Stinner6f75c872019-06-13 12:06:24 +0200851 @cpython_only
852 def test_shutdown_locks(self):
853 for daemon in (False, True):
854 with self.subTest(daemon=daemon):
855 event = threading.Event()
856 thread = threading.Thread(target=event.wait, daemon=daemon)
857
858 # Thread.start() must add lock to _shutdown_locks,
859 # but only for non-daemon thread
860 thread.start()
861 tstate_lock = thread._tstate_lock
862 if not daemon:
863 self.assertIn(tstate_lock, threading._shutdown_locks)
864 else:
865 self.assertNotIn(tstate_lock, threading._shutdown_locks)
866
867 # unblock the thread and join it
868 event.set()
869 thread.join()
870
871 # Thread._stop() must remove tstate_lock from _shutdown_locks.
872 # Daemon threads must never add it to _shutdown_locks.
873 self.assertNotIn(tstate_lock, threading._shutdown_locks)
874
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100875 def test_locals_at_exit(self):
876 # bpo-19466: thread locals must not be deleted before destructors
877 # are called
878 rc, out, err = assert_python_ok("-c", """if 1:
879 import threading
880
881 class Atexit:
882 def __del__(self):
883 print("thread_dict.atexit = %r" % thread_dict.atexit)
884
885 thread_dict = threading.local()
886 thread_dict.atexit = "value"
887
888 atexit = Atexit()
889 """)
890 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
891
BarneyStratford01c4fdd2021-02-02 20:24:24 +0000892 def test_boolean_target(self):
893 # bpo-41149: A thread that had a boolean value of False would not
894 # run, regardless of whether it was callable. The correct behaviour
895 # is for a thread to do nothing if its target is None, and to call
896 # the target otherwise.
897 class BooleanTarget(object):
898 def __init__(self):
899 self.ran = False
900 def __bool__(self):
901 return False
902 def __call__(self):
903 self.ran = True
904
905 target = BooleanTarget()
906 thread = threading.Thread(target=target)
907 thread.start()
908 thread.join()
909 self.assertTrue(target.ran)
910
Miss Islington (bot)71dca6e2021-05-15 02:24:44 -0700911 def test_leak_without_join(self):
912 # bpo-37788: Test that a thread which is not joined explicitly
913 # does not leak. Test written for reference leak checks.
914 def noop(): pass
915 with threading_helper.wait_threads_exit():
916 threading.Thread(target=noop).start()
917 # Thread.join() is not called
BarneyStratford01c4fdd2021-02-02 20:24:24 +0000918
Victor Stinner45956b92013-11-12 16:37:55 +0100919
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000920class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000921
922 def _run_and_join(self, script):
923 script = """if 1:
924 import sys, os, time, threading
925
926 # a thread, which waits for the main program to terminate
927 def joiningfunc(mainthread):
928 mainthread.join()
929 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000930 # stdout is fully buffered because not a tty, we have to flush
931 # before exit.
932 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000933 \n""" + script
934
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200935 rc, out, err = assert_python_ok("-c", script)
936 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000937 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000938
939 def test_1_join_on_shutdown(self):
940 # The usual case: on exit, wait for a non-daemon thread
941 script = """if 1:
942 import os
943 t = threading.Thread(target=joiningfunc,
944 args=(threading.current_thread(),))
945 t.start()
946 time.sleep(0.1)
947 print('end of main')
948 """
949 self._run_and_join(script)
950
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000951 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200952 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000953 def test_2_join_in_forked_process(self):
954 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000955 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200956 from test import support
957
Jesse Nollera8513972008-07-17 16:49:17 +0000958 childpid = os.fork()
959 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200960 # parent process
961 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000962 sys.exit(0)
963
Victor Stinnera9f96872020-03-31 21:49:44 +0200964 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000965 t = threading.Thread(target=joiningfunc,
966 args=(threading.current_thread(),))
967 t.start()
968 print('end of main')
969 """
970 self._run_and_join(script)
971
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000972 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200973 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000974 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000975 # Like the test above, but fork() was called from a worker thread
976 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000977
Jesse Nollera8513972008-07-17 16:49:17 +0000978 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200979 from test import support
980
Jesse Nollera8513972008-07-17 16:49:17 +0000981 main_thread = threading.current_thread()
982 def worker():
983 childpid = os.fork()
984 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200985 # parent process
986 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000987 sys.exit(0)
988
Victor Stinnera9f96872020-03-31 21:49:44 +0200989 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000990 t = threading.Thread(target=joiningfunc,
991 args=(main_thread,))
992 print('end of main')
993 t.start()
994 t.join() # Should not block: main_thread is already stopped
995
996 w = threading.Thread(target=worker)
997 w.start()
998 """
999 self._run_and_join(script)
1000
Victor Stinner26d31862011-07-01 14:26:24 +02001001 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -05001002 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001003 # Check that a daemon thread cannot crash the interpreter on shutdown
1004 # by manipulating internal structures that are being disposed of in
1005 # the main thread.
1006 script = """if True:
1007 import os
1008 import random
1009 import sys
1010 import time
1011 import threading
1012
1013 thread_has_run = set()
1014
1015 def random_io():
1016 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001017 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001018 with open(os.__file__, 'rb') as in_f:
1019 stuff = in_f.read(200)
1020 with open(os.devnull, 'wb') as null_f:
1021 null_f.write(stuff)
1022 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001023 thread_has_run.add(threading.current_thread())
1024
1025 def main():
1026 count = 0
1027 for _ in range(40):
1028 new_thread = threading.Thread(target=random_io)
1029 new_thread.daemon = True
1030 new_thread.start()
1031 count += 1
1032 while len(thread_has_run) < count:
1033 time.sleep(0.001)
1034 # Trigger process shutdown
1035 sys.exit(0)
1036
1037 main()
1038 """
1039 rc, out, err = assert_python_ok('-c', script)
1040 self.assertFalse(err)
1041
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001042 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +01001043 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001044 def test_reinit_tls_after_fork(self):
1045 # Issue #13817: fork() would deadlock in a multithreaded program with
1046 # the ad-hoc TLS implementation.
1047
1048 def do_fork_and_wait():
1049 # just fork a child process and wait it
1050 pid = os.fork()
1051 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +02001052 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001053 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001054 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001055
1056 # start a bunch of threads that will fork() child processes
1057 threads = []
1058 for i in range(16):
1059 t = threading.Thread(target=do_fork_and_wait)
1060 threads.append(t)
1061 t.start()
1062
1063 for t in threads:
1064 t.join()
1065
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001066 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
1067 def test_clear_threads_states_after_fork(self):
1068 # Issue #17094: check that threads states are cleared after fork()
1069
1070 # start a bunch of threads
1071 threads = []
1072 for i in range(16):
1073 t = threading.Thread(target=lambda : time.sleep(0.3))
1074 threads.append(t)
1075 t.start()
1076
1077 pid = os.fork()
1078 if pid == 0:
1079 # check that threads states have been cleared
1080 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +02001081 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001082 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001083 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001084 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001085 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001086
1087 for t in threads:
1088 t.join()
1089
Jesse Nollera8513972008-07-17 16:49:17 +00001090
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001091class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001092 def pipe(self):
1093 r, w = os.pipe()
1094 self.addCleanup(os.close, r)
1095 self.addCleanup(os.close, w)
1096 if hasattr(os, 'set_blocking'):
1097 os.set_blocking(r, False)
1098 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001099
1100 def test_threads_join(self):
1101 # Non-daemon threads should be joined at subinterpreter shutdown
1102 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001103 r, w = self.pipe()
1104 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001105 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001106 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001107 import threading
1108 import time
1109
Victor Stinner468e5fe2019-06-13 01:30:17 +02001110 def random_sleep():
1111 seconds = random.random() * 0.010
1112 time.sleep(seconds)
1113
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001114 def f():
1115 # Sleep a bit so that the thread is still running when
1116 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001117 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001118 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001119
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001120 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001121 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001122 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001123 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001124 self.assertEqual(ret, 0)
1125 # The thread was joined properly.
1126 self.assertEqual(os.read(r, 1), b"x")
1127
Antoine Pitrou7b476992013-09-07 23:38:37 +02001128 def test_threads_join_2(self):
1129 # Same as above, but a delay gets introduced after the thread's
1130 # Python code returned but before the thread state is deleted.
1131 # To achieve this, we register a thread-local object which sleeps
1132 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001133 r, w = self.pipe()
1134 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001135 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001136 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001137 import threading
1138 import time
1139
Victor Stinner468e5fe2019-06-13 01:30:17 +02001140 def random_sleep():
1141 seconds = random.random() * 0.010
1142 time.sleep(seconds)
1143
Antoine Pitrou7b476992013-09-07 23:38:37 +02001144 class Sleeper:
1145 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001146 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001147
1148 tls = threading.local()
1149
1150 def f():
1151 # Sleep a bit so that the thread is still running when
1152 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001153 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001154 tls.x = Sleeper()
1155 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001156
Antoine Pitrou7b476992013-09-07 23:38:37 +02001157 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001158 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001159 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001160 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001161 self.assertEqual(ret, 0)
1162 # The thread was joined properly.
1163 self.assertEqual(os.read(r, 1), b"x")
1164
Victor Stinner14d53312020-04-12 23:45:09 +02001165 @cpython_only
1166 def test_daemon_threads_fatal_error(self):
1167 subinterp_code = f"""if 1:
1168 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001169 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001170 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001171
Victor Stinner14d53312020-04-12 23:45:09 +02001172 def f():
1173 # Make sure the daemon thread is still running when
1174 # Py_EndInterpreter is called.
1175 time.sleep({test.support.SHORT_TIMEOUT})
1176 threading.Thread(target=f, daemon=True).start()
1177 """
1178 script = r"""if 1:
1179 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001180
Victor Stinner14d53312020-04-12 23:45:09 +02001181 _testcapi.run_in_subinterp(%r)
1182 """ % (subinterp_code,)
1183 with test.support.SuppressCrashReport():
1184 rc, out, err = assert_python_failure("-c", script)
1185 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1186 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001187
1188
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001189class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001190 # A RuntimeError should be raised if Thread.start() is called
1191 # multiple times.
1192 def test_start_thread_again(self):
1193 thread = threading.Thread()
1194 thread.start()
1195 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001196 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001197
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001198 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001199 current_thread = threading.current_thread()
1200 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001201
1202 def test_joining_inactive_thread(self):
1203 thread = threading.Thread()
1204 self.assertRaises(RuntimeError, thread.join)
1205
1206 def test_daemonize_active_thread(self):
1207 thread = threading.Thread()
1208 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001209 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001210 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001211
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001212 def test_releasing_unacquired_lock(self):
1213 lock = threading.Lock()
1214 self.assertRaises(RuntimeError, lock.release)
1215
Ned Deily9a7c5242011-05-28 00:19:56 -07001216 def test_recursion_limit(self):
1217 # Issue 9670
1218 # test that excessive recursion within a non-main thread causes
1219 # an exception rather than crashing the interpreter on platforms
1220 # like Mac OS X or FreeBSD which have small default stack sizes
1221 # for threads
1222 script = """if True:
1223 import threading
1224
1225 def recurse():
1226 return recurse()
1227
1228 def outer():
1229 try:
1230 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001231 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001232 pass
1233
1234 w = threading.Thread(target=outer)
1235 w.start()
1236 w.join()
1237 print('end of main thread')
1238 """
1239 expected_output = "end of main thread\n"
1240 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001241 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001242 stdout, stderr = p.communicate()
1243 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001244 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001245 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001246
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001247 def test_print_exception(self):
1248 script = r"""if True:
1249 import threading
1250 import time
1251
1252 running = False
1253 def run():
1254 global running
1255 running = True
1256 while running:
1257 time.sleep(0.01)
1258 1/0
1259 t = threading.Thread(target=run)
1260 t.start()
1261 while not running:
1262 time.sleep(0.01)
1263 running = False
1264 t.join()
1265 """
1266 rc, out, err = assert_python_ok("-c", script)
1267 self.assertEqual(out, b'')
1268 err = err.decode()
1269 self.assertIn("Exception in thread", err)
1270 self.assertIn("Traceback (most recent call last):", err)
1271 self.assertIn("ZeroDivisionError", err)
1272 self.assertNotIn("Unhandled exception", err)
1273
1274 def test_print_exception_stderr_is_none_1(self):
1275 script = r"""if True:
1276 import sys
1277 import threading
1278 import time
1279
1280 running = False
1281 def run():
1282 global running
1283 running = True
1284 while running:
1285 time.sleep(0.01)
1286 1/0
1287 t = threading.Thread(target=run)
1288 t.start()
1289 while not running:
1290 time.sleep(0.01)
1291 sys.stderr = None
1292 running = False
1293 t.join()
1294 """
1295 rc, out, err = assert_python_ok("-c", script)
1296 self.assertEqual(out, b'')
1297 err = err.decode()
1298 self.assertIn("Exception in thread", err)
1299 self.assertIn("Traceback (most recent call last):", err)
1300 self.assertIn("ZeroDivisionError", err)
1301 self.assertNotIn("Unhandled exception", err)
1302
1303 def test_print_exception_stderr_is_none_2(self):
1304 script = r"""if True:
1305 import sys
1306 import threading
1307 import time
1308
1309 running = False
1310 def run():
1311 global running
1312 running = True
1313 while running:
1314 time.sleep(0.01)
1315 1/0
1316 sys.stderr = None
1317 t = threading.Thread(target=run)
1318 t.start()
1319 while not running:
1320 time.sleep(0.01)
1321 running = False
1322 t.join()
1323 """
1324 rc, out, err = assert_python_ok("-c", script)
1325 self.assertEqual(out, b'')
1326 self.assertNotIn("Unhandled exception", err.decode())
1327
Victor Stinnereec93312016-08-18 18:13:10 +02001328 def test_bare_raise_in_brand_new_thread(self):
1329 def bare_raise():
1330 raise
1331
1332 class Issue27558(threading.Thread):
1333 exc = None
1334
1335 def run(self):
1336 try:
1337 bare_raise()
1338 except Exception as exc:
1339 self.exc = exc
1340
1341 thread = Issue27558()
1342 thread.start()
1343 thread.join()
1344 self.assertIsNotNone(thread.exc)
1345 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001346 # explicitly break the reference cycle to not leak a dangling thread
1347 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001348
Irit Katriel373741a2021-05-18 14:53:57 +01001349 def test_multithread_modify_file_noerror(self):
1350 # See issue25872
1351 def modify_file():
1352 with open(os_helper.TESTFN, 'w', encoding='utf-8') as fp:
1353 fp.write(' ')
1354 traceback.format_stack()
1355
1356 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1357 threads = [
1358 threading.Thread(target=modify_file)
1359 for i in range(100)
1360 ]
1361 for t in threads:
1362 t.start()
1363 t.join()
1364
Victor Stinnercd590a72019-05-28 00:39:52 +02001365
1366class ThreadRunFail(threading.Thread):
1367 def run(self):
1368 raise ValueError("run failed")
1369
1370
1371class ExceptHookTests(BaseTestCase):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001372 def setUp(self):
1373 restore_default_excepthook(self)
1374 super().setUp()
1375
Victor Stinnercd590a72019-05-28 00:39:52 +02001376 def test_excepthook(self):
1377 with support.captured_output("stderr") as stderr:
1378 thread = ThreadRunFail(name="excepthook thread")
1379 thread.start()
1380 thread.join()
1381
1382 stderr = stderr.getvalue().strip()
1383 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1384 self.assertIn('Traceback (most recent call last):\n', stderr)
1385 self.assertIn(' raise ValueError("run failed")', stderr)
1386 self.assertIn('ValueError: run failed', stderr)
1387
1388 @support.cpython_only
1389 def test_excepthook_thread_None(self):
1390 # threading.excepthook called with thread=None: log the thread
1391 # identifier in this case.
1392 with support.captured_output("stderr") as stderr:
1393 try:
1394 raise ValueError("bug")
1395 except Exception as exc:
1396 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001397 try:
1398 threading.excepthook(args)
1399 finally:
1400 # Explicitly break a reference cycle
1401 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001402
1403 stderr = stderr.getvalue().strip()
1404 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1405 self.assertIn('Traceback (most recent call last):\n', stderr)
1406 self.assertIn(' raise ValueError("bug")', stderr)
1407 self.assertIn('ValueError: bug', stderr)
1408
1409 def test_system_exit(self):
1410 class ThreadExit(threading.Thread):
1411 def run(self):
1412 sys.exit(1)
1413
1414 # threading.excepthook() silently ignores SystemExit
1415 with support.captured_output("stderr") as stderr:
1416 thread = ThreadExit()
1417 thread.start()
1418 thread.join()
1419
1420 self.assertEqual(stderr.getvalue(), '')
1421
1422 def test_custom_excepthook(self):
1423 args = None
1424
1425 def hook(hook_args):
1426 nonlocal args
1427 args = hook_args
1428
1429 try:
1430 with support.swap_attr(threading, 'excepthook', hook):
1431 thread = ThreadRunFail()
1432 thread.start()
1433 thread.join()
1434
1435 self.assertEqual(args.exc_type, ValueError)
1436 self.assertEqual(str(args.exc_value), 'run failed')
1437 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1438 self.assertIs(args.thread, thread)
1439 finally:
1440 # Break reference cycle
1441 args = None
1442
1443 def test_custom_excepthook_fail(self):
1444 def threading_hook(args):
1445 raise ValueError("threading_hook failed")
1446
1447 err_str = None
1448
1449 def sys_hook(exc_type, exc_value, exc_traceback):
1450 nonlocal err_str
1451 err_str = str(exc_value)
1452
1453 with support.swap_attr(threading, 'excepthook', threading_hook), \
1454 support.swap_attr(sys, 'excepthook', sys_hook), \
1455 support.captured_output('stderr') as stderr:
1456 thread = ThreadRunFail()
1457 thread.start()
1458 thread.join()
1459
1460 self.assertEqual(stderr.getvalue(),
1461 'Exception in threading.excepthook:\n')
1462 self.assertEqual(err_str, 'threading_hook failed')
1463
Mario Corchero750c5ab2020-11-12 18:27:44 +01001464 def test_original_excepthook(self):
1465 def run_thread():
1466 with support.captured_output("stderr") as output:
1467 thread = ThreadRunFail(name="excepthook thread")
1468 thread.start()
1469 thread.join()
1470 return output.getvalue()
1471
1472 def threading_hook(args):
1473 print("Running a thread failed", file=sys.stderr)
1474
1475 default_output = run_thread()
1476 with support.swap_attr(threading, 'excepthook', threading_hook):
1477 custom_hook_output = run_thread()
1478 threading.excepthook = threading.__excepthook__
1479 recovered_output = run_thread()
1480
1481 self.assertEqual(default_output, recovered_output)
1482 self.assertNotEqual(default_output, custom_hook_output)
1483 self.assertEqual(custom_hook_output, "Running a thread failed\n")
1484
Victor Stinnercd590a72019-05-28 00:39:52 +02001485
R David Murray19aeb432013-03-30 17:19:38 -04001486class TimerTests(BaseTestCase):
1487
1488 def setUp(self):
1489 BaseTestCase.setUp(self)
1490 self.callback_args = []
1491 self.callback_event = threading.Event()
1492
1493 def test_init_immutable_default_args(self):
1494 # Issue 17435: constructor defaults were mutable objects, they could be
1495 # mutated via the object attributes and affect other Timer objects.
1496 timer1 = threading.Timer(0.01, self._callback_spy)
1497 timer1.start()
1498 self.callback_event.wait()
1499 timer1.args.append("blah")
1500 timer1.kwargs["foo"] = "bar"
1501 self.callback_event.clear()
1502 timer2 = threading.Timer(0.01, self._callback_spy)
1503 timer2.start()
1504 self.callback_event.wait()
1505 self.assertEqual(len(self.callback_args), 2)
1506 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001507 timer1.join()
1508 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001509
1510 def _callback_spy(self, *args, **kwargs):
1511 self.callback_args.append((args[:], kwargs.copy()))
1512 self.callback_event.set()
1513
Antoine Pitrou557934f2009-11-06 22:41:14 +00001514class LockTests(lock_tests.LockTests):
1515 locktype = staticmethod(threading.Lock)
1516
Antoine Pitrou434736a2009-11-10 18:46:01 +00001517class PyRLockTests(lock_tests.RLockTests):
1518 locktype = staticmethod(threading._PyRLock)
1519
Charles-François Natali6b671b22012-01-28 11:36:04 +01001520@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001521class CRLockTests(lock_tests.RLockTests):
1522 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001523
1524class EventTests(lock_tests.EventTests):
1525 eventtype = staticmethod(threading.Event)
1526
1527class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001528 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001529 locktype = staticmethod(threading.Condition)
1530
1531class ConditionTests(lock_tests.ConditionTests):
1532 condtype = staticmethod(threading.Condition)
1533
1534class SemaphoreTests(lock_tests.SemaphoreTests):
1535 semtype = staticmethod(threading.Semaphore)
1536
1537class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1538 semtype = staticmethod(threading.BoundedSemaphore)
1539
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001540class BarrierTests(lock_tests.BarrierTests):
1541 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001542
Matěj Cepl608876b2019-05-23 22:30:00 +02001543
Martin Panter19e69c52015-11-14 12:46:42 +00001544class MiscTestCase(unittest.TestCase):
1545 def test__all__(self):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001546 restore_default_excepthook(self)
1547
Martin Panter19e69c52015-11-14 12:46:42 +00001548 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001549 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001550 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001551 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001552
Matěj Cepl608876b2019-05-23 22:30:00 +02001553
1554class InterruptMainTests(unittest.TestCase):
Antoine Pitrouba251c22021-03-11 23:35:45 +01001555 def check_interrupt_main_with_signal_handler(self, signum):
1556 def handler(signum, frame):
1557 1/0
1558
1559 old_handler = signal.signal(signum, handler)
1560 self.addCleanup(signal.signal, signum, old_handler)
1561
1562 with self.assertRaises(ZeroDivisionError):
1563 _thread.interrupt_main()
1564
1565 def check_interrupt_main_noerror(self, signum):
1566 handler = signal.getsignal(signum)
1567 try:
1568 # No exception should arise.
1569 signal.signal(signum, signal.SIG_IGN)
1570 _thread.interrupt_main(signum)
1571
1572 signal.signal(signum, signal.SIG_DFL)
1573 _thread.interrupt_main(signum)
1574 finally:
1575 # Restore original handler
1576 signal.signal(signum, handler)
1577
Matěj Cepl608876b2019-05-23 22:30:00 +02001578 def test_interrupt_main_subthread(self):
1579 # Calling start_new_thread with a function that executes interrupt_main
1580 # should raise KeyboardInterrupt upon completion.
1581 def call_interrupt():
1582 _thread.interrupt_main()
1583 t = threading.Thread(target=call_interrupt)
1584 with self.assertRaises(KeyboardInterrupt):
1585 t.start()
1586 t.join()
1587 t.join()
1588
1589 def test_interrupt_main_mainthread(self):
1590 # Make sure that if interrupt_main is called in main thread that
1591 # KeyboardInterrupt is raised instantly.
1592 with self.assertRaises(KeyboardInterrupt):
1593 _thread.interrupt_main()
1594
Antoine Pitrouba251c22021-03-11 23:35:45 +01001595 def test_interrupt_main_with_signal_handler(self):
1596 self.check_interrupt_main_with_signal_handler(signal.SIGINT)
1597 self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
Matěj Cepl608876b2019-05-23 22:30:00 +02001598
Antoine Pitrouba251c22021-03-11 23:35:45 +01001599 def test_interrupt_main_noerror(self):
1600 self.check_interrupt_main_noerror(signal.SIGINT)
1601 self.check_interrupt_main_noerror(signal.SIGTERM)
1602
1603 def test_interrupt_main_invalid_signal(self):
1604 self.assertRaises(ValueError, _thread.interrupt_main, -1)
1605 self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
1606 self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
Matěj Cepl608876b2019-05-23 22:30:00 +02001607
1608
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001609class AtexitTests(unittest.TestCase):
1610
1611 def test_atexit_output(self):
1612 rc, out, err = assert_python_ok("-c", """if True:
1613 import threading
1614
1615 def run_last():
1616 print('parrot')
1617
1618 threading._register_atexit(run_last)
1619 """)
1620
1621 self.assertFalse(err)
1622 self.assertEqual(out.strip(), b'parrot')
1623
1624 def test_atexit_called_once(self):
1625 rc, out, err = assert_python_ok("-c", """if True:
1626 import threading
1627 from unittest.mock import Mock
1628
1629 mock = Mock()
1630 threading._register_atexit(mock)
1631 mock.assert_not_called()
1632 # force early shutdown to ensure it was called once
1633 threading._shutdown()
1634 mock.assert_called_once()
1635 """)
1636
1637 self.assertFalse(err)
1638
1639 def test_atexit_after_shutdown(self):
1640 # The only way to do this is by registering an atexit within
1641 # an atexit, which is intended to raise an exception.
1642 rc, out, err = assert_python_ok("-c", """if True:
1643 import threading
1644
1645 def func():
1646 pass
1647
1648 def run_last():
1649 threading._register_atexit(func)
1650
1651 threading._register_atexit(run_last)
1652 """)
1653
1654 self.assertTrue(err)
1655 self.assertIn("RuntimeError: can't register atexit after shutdown",
1656 err.decode())
1657
1658
Tim Peters84d54892005-01-08 06:03:17 +00001659if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001660 unittest.main()