blob: f44f17f2978f7b48f72bf98568b1a4b2c866cccb [file] [log] [blame]
Antoine Pitrou4c8ce842013-09-01 19:51:49 +02001"""
2Tests for the threading module.
3"""
Skip Montanaro4533f602001-08-20 20:28:48 +00004
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005import test.support
Hai Shie80697d2020-05-28 06:10:27 +08006from test.support import threading_helper
Hai Shia7f5d932020-08-04 00:41:24 +08007from test.support import verbose, cpython_only
8from test.support.import_helper import import_module
Berker Peksagce643912015-05-06 06:33:17 +03009from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +020010
Skip Montanaro4533f602001-08-20 20:28:48 +000011import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000012import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020013import _thread
14import threading
Skip Montanaro4533f602001-08-20 20:28:48 +000015import time
Tim Peters84d54892005-01-08 06:03:17 +000016import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000017import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000018import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000019import subprocess
Matěj Cepl608876b2019-05-23 22:30:00 +020020import signal
Victor Stinner066e5b12019-06-14 18:55:22 +020021import textwrap
Skip Montanaro4533f602001-08-20 20:28:48 +000022
Victor Stinner98c16c92020-09-23 23:21:19 +020023from unittest import mock
Antoine Pitrou557934f2009-11-06 22:41:14 +000024from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000025from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000026
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030027
28# Between fork() and exec(), only async-safe functions are allowed (issues
29# #12316 and #11870), and fork() from a worker thread is known to trigger
30# problems with some operating systems (issue #3863): skip problematic tests
31# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010032platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030033
34
Victor Stinnerb136b1a2021-04-16 14:33:10 +020035def restore_default_excepthook(testcase):
36 testcase.addCleanup(setattr, threading, 'excepthook', threading.excepthook)
37 threading.excepthook = threading.__excepthook__
38
39
Tim Peters84d54892005-01-08 06:03:17 +000040# A trivial mutable counter.
41class Counter(object):
42 def __init__(self):
43 self.value = 0
44 def inc(self):
45 self.value += 1
46 def dec(self):
47 self.value -= 1
48 def get(self):
49 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000050
51class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000052 def __init__(self, name, testcase, sema, mutex, nrunning):
53 threading.Thread.__init__(self, name=name)
54 self.testcase = testcase
55 self.sema = sema
56 self.mutex = mutex
57 self.nrunning = nrunning
58
Skip Montanaro4533f602001-08-20 20:28:48 +000059 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000060 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000061 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000062 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000063 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000064
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 with self.sema:
66 with self.mutex:
67 self.nrunning.inc()
68 if verbose:
69 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020070 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000071
Christian Heimes4fbc72b2008-03-22 00:47:35 +000072 time.sleep(delay)
73 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000074 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000075
Christian Heimes4fbc72b2008-03-22 00:47:35 +000076 with self.mutex:
77 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020078 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000079 if verbose:
80 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000081 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000082
Skip Montanaro4533f602001-08-20 20:28:48 +000083
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000084class BaseTestCase(unittest.TestCase):
85 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080086 self._threads = threading_helper.threading_setup()
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000087
88 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +080089 threading_helper.threading_cleanup(*self._threads)
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000090 test.support.reap_children()
91
92
93class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000094
Victor Stinner98c16c92020-09-23 23:21:19 +020095 @cpython_only
96 def test_name(self):
97 def func(): pass
98
99 thread = threading.Thread(name="myname1")
100 self.assertEqual(thread.name, "myname1")
101
102 # Convert int name to str
103 thread = threading.Thread(name=123)
104 self.assertEqual(thread.name, "123")
105
106 # target name is ignored if name is specified
107 thread = threading.Thread(target=func, name="myname2")
108 self.assertEqual(thread.name, "myname2")
109
110 with mock.patch.object(threading, '_counter', return_value=2):
111 thread = threading.Thread(name="")
112 self.assertEqual(thread.name, "Thread-2")
113
114 with mock.patch.object(threading, '_counter', return_value=3):
115 thread = threading.Thread()
116 self.assertEqual(thread.name, "Thread-3")
117
118 with mock.patch.object(threading, '_counter', return_value=5):
119 thread = threading.Thread(target=func)
120 self.assertEqual(thread.name, "Thread-5 (func)")
121
Tim Peters84d54892005-01-08 06:03:17 +0000122 # Create a bunch of threads, let each do some work, wait until all are
123 # done.
124 def test_various_ops(self):
125 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
126 # times about 1 second per clump).
127 NUMTASKS = 10
128
129 # no more than 3 of the 10 can run at once
130 sema = threading.BoundedSemaphore(value=3)
131 mutex = threading.RLock()
132 numrunning = Counter()
133
134 threads = []
135
136 for i in range(NUMTASKS):
137 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
138 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200139 self.assertIsNone(t.ident)
140 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000141 t.start()
142
Jake Teslerb121f632019-05-22 08:43:17 -0700143 if hasattr(threading, 'get_native_id'):
144 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
145 self.assertNotIn(None, native_ids)
146 self.assertEqual(len(native_ids), NUMTASKS + 1)
147
Tim Peters84d54892005-01-08 06:03:17 +0000148 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000150 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200151 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200152 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000153 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200154 self.assertIsNotNone(t.ident)
155 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000156 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000157 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000158 self.assertEqual(numrunning.get(), 0)
159
Benjamin Petersond23f8222009-04-05 19:13:16 +0000160 def test_ident_of_no_threading_threads(self):
161 # The ident still must work for the main thread and dummy threads.
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700162 self.assertIsNotNone(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000163 def f():
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700164 ident.append(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000165 done.set()
166 done = threading.Event()
167 ident = []
Hai Shie80697d2020-05-28 06:10:27 +0800168 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700169 tid = _thread.start_new_thread(f, ())
170 done.wait()
171 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000172 # Kill the "immortal" _DummyThread
173 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000174
Victor Stinner8c663fd2017-11-08 14:44:44 -0800175 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000176 def test_various_ops_small_stack(self):
177 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800178 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000179 try:
180 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000181 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000182 raise unittest.SkipTest(
183 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000184 self.test_various_ops()
185 threading.stack_size(0)
186
Victor Stinner8c663fd2017-11-08 14:44:44 -0800187 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000188 def test_various_ops_large_stack(self):
189 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800190 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 try:
192 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000193 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000194 raise unittest.SkipTest(
195 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000196 self.test_various_ops()
197 threading.stack_size(0)
198
Tim Peters711906e2005-01-08 07:30:42 +0000199 def test_foreign_thread(self):
200 # Check that a "foreign" thread can use the threading module.
201 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000202 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000203 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000204 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000205 mutex.release()
206
207 mutex = threading.Lock()
208 mutex.acquire()
Hai Shie80697d2020-05-28 06:10:27 +0800209 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700210 tid = _thread.start_new_thread(f, (mutex,))
211 # Wait for the thread to finish.
212 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000213 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000214 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800215 #Issue 29376
216 self.assertTrue(threading._active[tid].is_alive())
217 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000218 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000219
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
221 # exposed at the Python level. This test relies on ctypes to get at it.
222 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200223 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000224
225 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200226 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000227
228 class AsyncExc(Exception):
229 pass
230
231 exception = ctypes.py_object(AsyncExc)
232
Antoine Pitroube4d8092009-10-18 18:27:17 +0000233 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200234 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200235 self.assertIsInstance(tid, int)
236 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000237
238 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200239 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000240 # The exception is async, so we might have to keep the VM busy until
241 # it notices.
242 while True:
243 pass
244 except AsyncExc:
245 pass
246 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000247 # This code is unreachable but it reflects the intent. If we wanted
248 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000249 self.fail("AsyncExc not raised")
250 try:
251 self.assertEqual(result, 1) # one thread state modified
252 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000253 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000254 pass
255
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000256 # `worker_started` is set by the thread when it's inside a try/except
257 # block waiting to catch the asynchronously set AsyncExc exception.
258 # `worker_saw_exception` is set by the thread upon catching that
259 # exception.
260 worker_started = threading.Event()
261 worker_saw_exception = threading.Event()
262
263 class Worker(threading.Thread):
264 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200265 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000266 self.finished = False
267
268 try:
269 while True:
270 worker_started.set()
271 time.sleep(0.1)
272 except AsyncExc:
273 self.finished = True
274 worker_saw_exception.set()
275
276 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000277 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000278 t.start()
279 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000280 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000281
282 # Try a thread id that doesn't make sense.
283 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000284 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200285 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000286 self.assertEqual(result, 0) # no thread states modified
287
288 # Now raise an exception in the worker thread.
289 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000290 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000291 ret = worker_started.wait()
292 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000293 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000294 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200295 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000296 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000297 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200298 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000299 self.assertEqual(result, 1) # one thread state modified
300 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000301 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100302 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000303 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000304 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000305 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000306 if t.finished:
307 t.join()
308 # else the thread is still running, and we have no way to kill it
309
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000310 def test_limbo_cleanup(self):
311 # Issue 7481: Failure to start thread should cleanup the limbo map.
312 def fail_new_thread(*args):
313 raise threading.ThreadError()
314 _start_new_thread = threading._start_new_thread
315 threading._start_new_thread = fail_new_thread
316 try:
317 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000318 self.assertRaises(threading.ThreadError, t.start)
319 self.assertFalse(
320 t in threading._limbo,
321 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000322 finally:
323 threading._start_new_thread = _start_new_thread
324
Min ho Kimc4cacc82019-07-31 08:16:13 +1000325 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000326 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
327 # very late on python exit: on deallocation of a running thread for
328 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200329 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000330
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200331 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000332 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000333
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000334 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000335 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000336 ready.acquire()
337
Christian Heimes7d2ff882007-11-30 14:35:04 +0000338 # Module globals are cleared before __del__ is run
339 # So we save the functions in class dict
340 class C:
341 ensure = ctypes.pythonapi.PyGILState_Ensure
342 release = ctypes.pythonapi.PyGILState_Release
343 def __del__(self):
344 state = self.ensure()
345 self.release(state)
346
347 def waitingThread():
348 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000349 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000350 time.sleep(100)
351
Georg Brandl2067bfd2008-05-25 13:05:15 +0000352 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000353 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000354 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200355 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000356 self.assertEqual(rc, 42)
357
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000358 def test_finalize_with_trace(self):
359 # Issue1733757
360 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200361 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000362 import sys, threading
363
364 # A deadlock-killer, to prevent the
365 # testsuite to hang forever
366 def killer():
367 import os, time
368 time.sleep(2)
369 print('program blocked; aborting')
370 os._exit(2)
371 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000372 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000373 t.start()
374
375 # This is the trace function
376 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000377 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000378 return func
379
380 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200381 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000382
Antoine Pitrou011bd622009-10-20 21:52:47 +0000383 def test_join_nondaemon_on_shutdown(self):
384 # Issue 1722344
385 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200386 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000387 import threading
388 from time import sleep
389
390 def child():
391 sleep(1)
392 # As a non-daemon thread we SHOULD wake up and nothing
393 # should be torn down yet
394 print("Woke up, sleep function is:", sleep)
395
396 threading.Thread(target=child).start()
397 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200398 """)
399 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000400 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200401 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000402
Christian Heimes1af737c2008-01-23 08:24:23 +0000403 def test_enumerate_after_join(self):
404 # Try hard to trigger #1703448: a thread is still returned in
405 # threading.enumerate() after it has been join()ed.
406 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000407 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000408 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000409 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000410 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000411 t = threading.Thread(target=lambda: None)
412 t.start()
413 t.join()
414 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000415 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000416 "#1703448 triggered after %d trials: %s" % (i, l))
417 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000418 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000419
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000420 def test_no_refcycle_through_target(self):
421 class RunSelfFunction(object):
422 def __init__(self, should_raise):
423 # The links in this refcycle from Thread back to self
424 # should be cleaned up when the thread completes.
425 self.should_raise = should_raise
426 self.thread = threading.Thread(target=self._run,
427 args=(self,),
428 kwargs={'yet_another':self})
429 self.thread.start()
430
431 def _run(self, other_ref, yet_another):
432 if self.should_raise:
433 raise SystemExit
434
Victor Stinnerb136b1a2021-04-16 14:33:10 +0200435 restore_default_excepthook(self)
436
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000437 cyclic_object = RunSelfFunction(should_raise=False)
438 weak_cyclic_object = weakref.ref(cyclic_object)
439 cyclic_object.thread.join()
440 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000441 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000442 msg=('%d references still around' %
443 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000444
445 raising_cyclic_object = RunSelfFunction(should_raise=True)
446 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
447 raising_cyclic_object.thread.join()
448 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000449 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 msg=('%d references still around' %
451 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000452
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000453 def test_old_threading_api(self):
454 # Just a quick sanity check to make sure the old method names are
455 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000456 t = threading.Thread()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700457 with self.assertWarnsRegex(DeprecationWarning,
458 r'get the daemon attribute'):
459 t.isDaemon()
460 with self.assertWarnsRegex(DeprecationWarning,
461 r'set the daemon attribute'):
462 t.setDaemon(True)
463 with self.assertWarnsRegex(DeprecationWarning,
464 r'get the name attribute'):
465 t.getName()
466 with self.assertWarnsRegex(DeprecationWarning,
467 r'set the name attribute'):
468 t.setName("name")
469
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000470 e = threading.Event()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700471 with self.assertWarnsRegex(DeprecationWarning, 'use is_set()'):
472 e.isSet()
473
474 cond = threading.Condition()
475 cond.acquire()
476 with self.assertWarnsRegex(DeprecationWarning, 'use notify_all()'):
477 cond.notifyAll()
478
479 with self.assertWarnsRegex(DeprecationWarning, 'use active_count()'):
480 threading.activeCount()
481 with self.assertWarnsRegex(DeprecationWarning, 'use current_thread()'):
482 threading.currentThread()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000483
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000484 def test_repr_daemon(self):
485 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200486 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000487 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200488 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000489
luzpaza5293b42017-11-05 07:37:50 -0600490 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000491 t = threading.Thread()
492 self.assertFalse(t.daemon)
493 t = threading.Thread(daemon=False)
494 self.assertFalse(t.daemon)
495 t = threading.Thread(daemon=True)
496 self.assertTrue(t.daemon)
497
Victor Stinner5909a492020-11-16 15:20:34 +0100498 @unittest.skipUnless(hasattr(os, 'fork'), 'needs os.fork()')
499 def test_fork_at_exit(self):
500 # bpo-42350: Calling os.fork() after threading._shutdown() must
501 # not log an error.
502 code = textwrap.dedent("""
503 import atexit
504 import os
505 import sys
506 from test.support import wait_process
507
508 # Import the threading module to register its "at fork" callback
509 import threading
510
511 def exit_handler():
512 pid = os.fork()
513 if not pid:
514 print("child process ok", file=sys.stderr, flush=True)
515 # child process
Victor Stinner5909a492020-11-16 15:20:34 +0100516 else:
517 wait_process(pid, exitcode=0)
518
519 # exit_handler() will be called after threading._shutdown()
520 atexit.register(exit_handler)
521 """)
522 _, out, err = assert_python_ok("-c", code)
523 self.assertEqual(out, b'')
524 self.assertEqual(err.rstrip(), b'child process ok')
525
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200526 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
527 def test_dummy_thread_after_fork(self):
528 # Issue #14308: a dummy thread in the active list doesn't mess up
529 # the after-fork mechanism.
530 code = """if 1:
531 import _thread, threading, os, time
532
533 def background_thread(evt):
534 # Creates and registers the _DummyThread instance
535 threading.current_thread()
536 evt.set()
537 time.sleep(10)
538
539 evt = threading.Event()
540 _thread.start_new_thread(background_thread, (evt,))
541 evt.wait()
542 assert threading.active_count() == 2, threading.active_count()
543 if os.fork() == 0:
544 assert threading.active_count() == 1, threading.active_count()
545 os._exit(0)
546 else:
547 os.wait()
548 """
549 _, out, err = assert_python_ok("-c", code)
550 self.assertEqual(out, b'')
551 self.assertEqual(err, b'')
552
Charles-François Natali9939cc82013-08-30 23:32:53 +0200553 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
554 def test_is_alive_after_fork(self):
555 # Try hard to trigger #18418: is_alive() could sometimes be True on
556 # threads that vanished after a fork.
557 old_interval = sys.getswitchinterval()
558 self.addCleanup(sys.setswitchinterval, old_interval)
559
560 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100561 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200562
563 for i in range(20):
564 t = threading.Thread(target=lambda: None)
565 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200566 pid = os.fork()
567 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700568 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200569 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700570 t.join()
571
Victor Stinnera9f96872020-03-31 21:49:44 +0200572 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200573
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300574 def test_main_thread(self):
575 main = threading.main_thread()
576 self.assertEqual(main.name, 'MainThread')
577 self.assertEqual(main.ident, threading.current_thread().ident)
578 self.assertEqual(main.ident, threading.get_ident())
579
580 def f():
581 self.assertNotEqual(threading.main_thread().ident,
582 threading.current_thread().ident)
583 th = threading.Thread(target=f)
584 th.start()
585 th.join()
586
587 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
588 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
589 def test_main_thread_after_fork(self):
590 code = """if 1:
591 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200592 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300593
594 pid = os.fork()
595 if pid == 0:
596 main = threading.main_thread()
597 print(main.name)
598 print(main.ident == threading.current_thread().ident)
599 print(main.ident == threading.get_ident())
600 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200601 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300602 """
603 _, out, err = assert_python_ok("-c", code)
604 data = out.decode().replace('\r', '')
605 self.assertEqual(err, b"")
606 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
607
608 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
609 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
610 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
611 def test_main_thread_after_fork_from_nonmain_thread(self):
612 code = """if 1:
613 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200614 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300615
Victor Stinner98c16c92020-09-23 23:21:19 +0200616 def func():
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300617 pid = os.fork()
618 if pid == 0:
619 main = threading.main_thread()
620 print(main.name)
621 print(main.ident == threading.current_thread().ident)
622 print(main.ident == threading.get_ident())
623 # stdout is fully buffered because not a tty,
624 # we have to flush before exit.
625 sys.stdout.flush()
626 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200627 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300628
Victor Stinner98c16c92020-09-23 23:21:19 +0200629 th = threading.Thread(target=func)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300630 th.start()
631 th.join()
632 """
633 _, out, err = assert_python_ok("-c", code)
634 data = out.decode().replace('\r', '')
635 self.assertEqual(err, b"")
Victor Stinner98c16c92020-09-23 23:21:19 +0200636 self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300637
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200638 def test_main_thread_during_shutdown(self):
639 # bpo-31516: current_thread() should still point to the main thread
640 # at shutdown
641 code = """if 1:
642 import gc, threading
643
644 main_thread = threading.current_thread()
645 assert main_thread is threading.main_thread() # sanity check
646
647 class RefCycle:
648 def __init__(self):
649 self.cycle = self
650
651 def __del__(self):
652 print("GC:",
653 threading.current_thread() is main_thread,
654 threading.main_thread() is main_thread,
655 threading.enumerate() == [main_thread])
656
657 RefCycle()
658 gc.collect() # sanity check
659 x = RefCycle()
660 """
661 _, out, err = assert_python_ok("-c", code)
662 data = out.decode()
663 self.assertEqual(err, b"")
664 self.assertEqual(data.splitlines(),
665 ["GC: True True True"] * 2)
666
Victor Stinner468e5fe2019-06-13 01:30:17 +0200667 def test_finalization_shutdown(self):
668 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
669 # until Python thread states of all non-daemon threads get deleted.
670 #
671 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
672 # test the finalization of the main interpreter.
673 code = """if 1:
674 import os
675 import threading
676 import time
677 import random
678
679 def random_sleep():
680 seconds = random.random() * 0.010
681 time.sleep(seconds)
682
683 class Sleeper:
684 def __del__(self):
685 random_sleep()
686
687 tls = threading.local()
688
689 def f():
690 # Sleep a bit so that the thread is still running when
691 # Py_Finalize() is called.
692 random_sleep()
693 tls.x = Sleeper()
694 random_sleep()
695
696 threading.Thread(target=f).start()
697 random_sleep()
698 """
699 rc, out, err = assert_python_ok("-c", code)
700 self.assertEqual(err, b"")
701
Antoine Pitrou7b476992013-09-07 23:38:37 +0200702 def test_tstate_lock(self):
703 # Test an implementation detail of Thread objects.
704 started = _thread.allocate_lock()
705 finish = _thread.allocate_lock()
706 started.acquire()
707 finish.acquire()
708 def f():
709 started.release()
710 finish.acquire()
711 time.sleep(0.01)
712 # The tstate lock is None until the thread is started
713 t = threading.Thread(target=f)
714 self.assertIs(t._tstate_lock, None)
715 t.start()
716 started.acquire()
717 self.assertTrue(t.is_alive())
718 # The tstate lock can't be acquired when the thread is running
719 # (or suspended).
720 tstate_lock = t._tstate_lock
721 self.assertFalse(tstate_lock.acquire(timeout=0), False)
722 finish.release()
723 # When the thread ends, the state_lock can be successfully
724 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100725 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200726 # But is_alive() is still True: we hold _tstate_lock now, which
727 # prevents is_alive() from knowing the thread's end-of-life C code
728 # is done.
729 self.assertTrue(t.is_alive())
730 # Let is_alive() find out the C code is done.
731 tstate_lock.release()
732 self.assertFalse(t.is_alive())
733 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200734 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700735 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200736
Tim Peters72460fa2013-09-09 18:48:24 -0500737 def test_repr_stopped(self):
738 # Verify that "stopped" shows up in repr(Thread) appropriately.
739 started = _thread.allocate_lock()
740 finish = _thread.allocate_lock()
741 started.acquire()
742 finish.acquire()
743 def f():
744 started.release()
745 finish.acquire()
746 t = threading.Thread(target=f)
747 t.start()
748 started.acquire()
749 self.assertIn("started", repr(t))
750 finish.release()
751 # "stopped" should appear in the repr in a reasonable amount of time.
752 # Implementation detail: as of this writing, that's trivially true
753 # if .join() is called, and almost trivially true if .is_alive() is
754 # called. The detail we're testing here is that "stopped" shows up
755 # "all on its own".
756 LOOKING_FOR = "stopped"
757 for i in range(500):
758 if LOOKING_FOR in repr(t):
759 break
760 time.sleep(0.01)
761 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700762 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000763
Tim Peters7634e1c2013-10-08 20:55:51 -0500764 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500765 # BoundedSemaphore should raise ValueError if released too often.
766 for limit in range(1, 10):
767 bs = threading.BoundedSemaphore(limit)
768 threads = [threading.Thread(target=bs.acquire)
769 for _ in range(limit)]
770 for t in threads:
771 t.start()
772 for t in threads:
773 t.join()
774 threads = [threading.Thread(target=bs.release)
775 for _ in range(limit)]
776 for t in threads:
777 t.start()
778 for t in threads:
779 t.join()
780 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500781
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200782 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100783 def test_frame_tstate_tracing(self):
784 # Issue #14432: Crash when a generator is created in a C thread that is
785 # destroyed while the generator is still used. The issue was that a
786 # generator contains a frame, and the frame kept a reference to the
787 # Python state of the destroyed C thread. The crash occurs when a trace
788 # function is setup.
789
790 def noop_trace(frame, event, arg):
791 # no operation
792 return noop_trace
793
794 def generator():
795 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300796 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100797
798 def callback():
799 if callback.gen is None:
800 callback.gen = generator()
801 return next(callback.gen)
802 callback.gen = None
803
804 old_trace = sys.gettrace()
805 sys.settrace(noop_trace)
806 try:
807 # Install a trace function
808 threading.settrace(noop_trace)
809
810 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200811 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100812 _testcapi.call_in_temporary_c_thread(callback)
813
814 # Call the generator in a different Python thread, check that the
815 # generator didn't keep a reference to the destroyed thread state
816 for test in range(3):
817 # The trace function is still called here
818 callback()
819 finally:
820 sys.settrace(old_trace)
821
Mario Corchero0001a1b2020-11-04 10:27:43 +0100822 def test_gettrace(self):
823 def noop_trace(frame, event, arg):
824 # no operation
825 return noop_trace
826 old_trace = threading.gettrace()
827 try:
828 threading.settrace(noop_trace)
829 trace_func = threading.gettrace()
830 self.assertEqual(noop_trace,trace_func)
831 finally:
832 threading.settrace(old_trace)
833
834 def test_getprofile(self):
835 def fn(*args): pass
836 old_profile = threading.getprofile()
837 try:
838 threading.setprofile(fn)
839 self.assertEqual(fn, threading.getprofile())
840 finally:
841 threading.setprofile(old_profile)
842
Victor Stinner6f75c872019-06-13 12:06:24 +0200843 @cpython_only
844 def test_shutdown_locks(self):
845 for daemon in (False, True):
846 with self.subTest(daemon=daemon):
847 event = threading.Event()
848 thread = threading.Thread(target=event.wait, daemon=daemon)
849
850 # Thread.start() must add lock to _shutdown_locks,
851 # but only for non-daemon thread
852 thread.start()
853 tstate_lock = thread._tstate_lock
854 if not daemon:
855 self.assertIn(tstate_lock, threading._shutdown_locks)
856 else:
857 self.assertNotIn(tstate_lock, threading._shutdown_locks)
858
859 # unblock the thread and join it
860 event.set()
861 thread.join()
862
863 # Thread._stop() must remove tstate_lock from _shutdown_locks.
864 # Daemon threads must never add it to _shutdown_locks.
865 self.assertNotIn(tstate_lock, threading._shutdown_locks)
866
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100867 def test_locals_at_exit(self):
868 # bpo-19466: thread locals must not be deleted before destructors
869 # are called
870 rc, out, err = assert_python_ok("-c", """if 1:
871 import threading
872
873 class Atexit:
874 def __del__(self):
875 print("thread_dict.atexit = %r" % thread_dict.atexit)
876
877 thread_dict = threading.local()
878 thread_dict.atexit = "value"
879
880 atexit = Atexit()
881 """)
882 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
883
BarneyStratford01c4fdd2021-02-02 20:24:24 +0000884 def test_boolean_target(self):
885 # bpo-41149: A thread that had a boolean value of False would not
886 # run, regardless of whether it was callable. The correct behaviour
887 # is for a thread to do nothing if its target is None, and to call
888 # the target otherwise.
889 class BooleanTarget(object):
890 def __init__(self):
891 self.ran = False
892 def __bool__(self):
893 return False
894 def __call__(self):
895 self.ran = True
896
897 target = BooleanTarget()
898 thread = threading.Thread(target=target)
899 thread.start()
900 thread.join()
901 self.assertTrue(target.ran)
902
903
Victor Stinner45956b92013-11-12 16:37:55 +0100904
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000905class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000906
907 def _run_and_join(self, script):
908 script = """if 1:
909 import sys, os, time, threading
910
911 # a thread, which waits for the main program to terminate
912 def joiningfunc(mainthread):
913 mainthread.join()
914 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000915 # stdout is fully buffered because not a tty, we have to flush
916 # before exit.
917 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000918 \n""" + script
919
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200920 rc, out, err = assert_python_ok("-c", script)
921 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000922 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000923
924 def test_1_join_on_shutdown(self):
925 # The usual case: on exit, wait for a non-daemon thread
926 script = """if 1:
927 import os
928 t = threading.Thread(target=joiningfunc,
929 args=(threading.current_thread(),))
930 t.start()
931 time.sleep(0.1)
932 print('end of main')
933 """
934 self._run_and_join(script)
935
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000936 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200937 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000938 def test_2_join_in_forked_process(self):
939 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000940 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200941 from test import support
942
Jesse Nollera8513972008-07-17 16:49:17 +0000943 childpid = os.fork()
944 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200945 # parent process
946 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000947 sys.exit(0)
948
Victor Stinnera9f96872020-03-31 21:49:44 +0200949 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000950 t = threading.Thread(target=joiningfunc,
951 args=(threading.current_thread(),))
952 t.start()
953 print('end of main')
954 """
955 self._run_and_join(script)
956
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000957 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200958 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000959 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000960 # Like the test above, but fork() was called from a worker thread
961 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000962
Jesse Nollera8513972008-07-17 16:49:17 +0000963 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200964 from test import support
965
Jesse Nollera8513972008-07-17 16:49:17 +0000966 main_thread = threading.current_thread()
967 def worker():
968 childpid = os.fork()
969 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200970 # parent process
971 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000972 sys.exit(0)
973
Victor Stinnera9f96872020-03-31 21:49:44 +0200974 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000975 t = threading.Thread(target=joiningfunc,
976 args=(main_thread,))
977 print('end of main')
978 t.start()
979 t.join() # Should not block: main_thread is already stopped
980
981 w = threading.Thread(target=worker)
982 w.start()
983 """
984 self._run_and_join(script)
985
Victor Stinner26d31862011-07-01 14:26:24 +0200986 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500987 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200988 # Check that a daemon thread cannot crash the interpreter on shutdown
989 # by manipulating internal structures that are being disposed of in
990 # the main thread.
991 script = """if True:
992 import os
993 import random
994 import sys
995 import time
996 import threading
997
998 thread_has_run = set()
999
1000 def random_io():
1001 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001002 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001003 with open(os.__file__, 'rb') as in_f:
1004 stuff = in_f.read(200)
1005 with open(os.devnull, 'wb') as null_f:
1006 null_f.write(stuff)
1007 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001008 thread_has_run.add(threading.current_thread())
1009
1010 def main():
1011 count = 0
1012 for _ in range(40):
1013 new_thread = threading.Thread(target=random_io)
1014 new_thread.daemon = True
1015 new_thread.start()
1016 count += 1
1017 while len(thread_has_run) < count:
1018 time.sleep(0.001)
1019 # Trigger process shutdown
1020 sys.exit(0)
1021
1022 main()
1023 """
1024 rc, out, err = assert_python_ok('-c', script)
1025 self.assertFalse(err)
1026
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001027 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +01001028 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001029 def test_reinit_tls_after_fork(self):
1030 # Issue #13817: fork() would deadlock in a multithreaded program with
1031 # the ad-hoc TLS implementation.
1032
1033 def do_fork_and_wait():
1034 # just fork a child process and wait it
1035 pid = os.fork()
1036 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +02001037 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001038 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001039 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001040
1041 # start a bunch of threads that will fork() child processes
1042 threads = []
1043 for i in range(16):
1044 t = threading.Thread(target=do_fork_and_wait)
1045 threads.append(t)
1046 t.start()
1047
1048 for t in threads:
1049 t.join()
1050
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001051 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
1052 def test_clear_threads_states_after_fork(self):
1053 # Issue #17094: check that threads states are cleared after fork()
1054
1055 # start a bunch of threads
1056 threads = []
1057 for i in range(16):
1058 t = threading.Thread(target=lambda : time.sleep(0.3))
1059 threads.append(t)
1060 t.start()
1061
1062 pid = os.fork()
1063 if pid == 0:
1064 # check that threads states have been cleared
1065 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +02001066 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001067 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001068 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001069 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001070 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001071
1072 for t in threads:
1073 t.join()
1074
Jesse Nollera8513972008-07-17 16:49:17 +00001075
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001076class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001077 def pipe(self):
1078 r, w = os.pipe()
1079 self.addCleanup(os.close, r)
1080 self.addCleanup(os.close, w)
1081 if hasattr(os, 'set_blocking'):
1082 os.set_blocking(r, False)
1083 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001084
1085 def test_threads_join(self):
1086 # Non-daemon threads should be joined at subinterpreter shutdown
1087 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001088 r, w = self.pipe()
1089 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001090 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001091 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001092 import threading
1093 import time
1094
Victor Stinner468e5fe2019-06-13 01:30:17 +02001095 def random_sleep():
1096 seconds = random.random() * 0.010
1097 time.sleep(seconds)
1098
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001099 def f():
1100 # Sleep a bit so that the thread is still running when
1101 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001102 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001103 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001104
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001105 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001106 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001107 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001108 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001109 self.assertEqual(ret, 0)
1110 # The thread was joined properly.
1111 self.assertEqual(os.read(r, 1), b"x")
1112
Antoine Pitrou7b476992013-09-07 23:38:37 +02001113 def test_threads_join_2(self):
1114 # Same as above, but a delay gets introduced after the thread's
1115 # Python code returned but before the thread state is deleted.
1116 # To achieve this, we register a thread-local object which sleeps
1117 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001118 r, w = self.pipe()
1119 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001120 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001121 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001122 import threading
1123 import time
1124
Victor Stinner468e5fe2019-06-13 01:30:17 +02001125 def random_sleep():
1126 seconds = random.random() * 0.010
1127 time.sleep(seconds)
1128
Antoine Pitrou7b476992013-09-07 23:38:37 +02001129 class Sleeper:
1130 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001131 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001132
1133 tls = threading.local()
1134
1135 def f():
1136 # Sleep a bit so that the thread is still running when
1137 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001138 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001139 tls.x = Sleeper()
1140 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001141
Antoine Pitrou7b476992013-09-07 23:38:37 +02001142 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001143 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001144 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001145 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001146 self.assertEqual(ret, 0)
1147 # The thread was joined properly.
1148 self.assertEqual(os.read(r, 1), b"x")
1149
Victor Stinner14d53312020-04-12 23:45:09 +02001150 @cpython_only
1151 def test_daemon_threads_fatal_error(self):
1152 subinterp_code = f"""if 1:
1153 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001154 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001155 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001156
Victor Stinner14d53312020-04-12 23:45:09 +02001157 def f():
1158 # Make sure the daemon thread is still running when
1159 # Py_EndInterpreter is called.
1160 time.sleep({test.support.SHORT_TIMEOUT})
1161 threading.Thread(target=f, daemon=True).start()
1162 """
1163 script = r"""if 1:
1164 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001165
Victor Stinner14d53312020-04-12 23:45:09 +02001166 _testcapi.run_in_subinterp(%r)
1167 """ % (subinterp_code,)
1168 with test.support.SuppressCrashReport():
1169 rc, out, err = assert_python_failure("-c", script)
1170 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1171 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001172
1173
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001174class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001175 # A RuntimeError should be raised if Thread.start() is called
1176 # multiple times.
1177 def test_start_thread_again(self):
1178 thread = threading.Thread()
1179 thread.start()
1180 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001181 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001182
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001183 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001184 current_thread = threading.current_thread()
1185 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001186
1187 def test_joining_inactive_thread(self):
1188 thread = threading.Thread()
1189 self.assertRaises(RuntimeError, thread.join)
1190
1191 def test_daemonize_active_thread(self):
1192 thread = threading.Thread()
1193 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001194 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001195 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001196
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001197 def test_releasing_unacquired_lock(self):
1198 lock = threading.Lock()
1199 self.assertRaises(RuntimeError, lock.release)
1200
Ned Deily9a7c5242011-05-28 00:19:56 -07001201 def test_recursion_limit(self):
1202 # Issue 9670
1203 # test that excessive recursion within a non-main thread causes
1204 # an exception rather than crashing the interpreter on platforms
1205 # like Mac OS X or FreeBSD which have small default stack sizes
1206 # for threads
1207 script = """if True:
1208 import threading
1209
1210 def recurse():
1211 return recurse()
1212
1213 def outer():
1214 try:
1215 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001216 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001217 pass
1218
1219 w = threading.Thread(target=outer)
1220 w.start()
1221 w.join()
1222 print('end of main thread')
1223 """
1224 expected_output = "end of main thread\n"
1225 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001226 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001227 stdout, stderr = p.communicate()
1228 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001229 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001230 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001231
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001232 def test_print_exception(self):
1233 script = r"""if True:
1234 import threading
1235 import time
1236
1237 running = False
1238 def run():
1239 global running
1240 running = True
1241 while running:
1242 time.sleep(0.01)
1243 1/0
1244 t = threading.Thread(target=run)
1245 t.start()
1246 while not running:
1247 time.sleep(0.01)
1248 running = False
1249 t.join()
1250 """
1251 rc, out, err = assert_python_ok("-c", script)
1252 self.assertEqual(out, b'')
1253 err = err.decode()
1254 self.assertIn("Exception in thread", err)
1255 self.assertIn("Traceback (most recent call last):", err)
1256 self.assertIn("ZeroDivisionError", err)
1257 self.assertNotIn("Unhandled exception", err)
1258
1259 def test_print_exception_stderr_is_none_1(self):
1260 script = r"""if True:
1261 import sys
1262 import threading
1263 import time
1264
1265 running = False
1266 def run():
1267 global running
1268 running = True
1269 while running:
1270 time.sleep(0.01)
1271 1/0
1272 t = threading.Thread(target=run)
1273 t.start()
1274 while not running:
1275 time.sleep(0.01)
1276 sys.stderr = None
1277 running = False
1278 t.join()
1279 """
1280 rc, out, err = assert_python_ok("-c", script)
1281 self.assertEqual(out, b'')
1282 err = err.decode()
1283 self.assertIn("Exception in thread", err)
1284 self.assertIn("Traceback (most recent call last):", err)
1285 self.assertIn("ZeroDivisionError", err)
1286 self.assertNotIn("Unhandled exception", err)
1287
1288 def test_print_exception_stderr_is_none_2(self):
1289 script = r"""if True:
1290 import sys
1291 import threading
1292 import time
1293
1294 running = False
1295 def run():
1296 global running
1297 running = True
1298 while running:
1299 time.sleep(0.01)
1300 1/0
1301 sys.stderr = None
1302 t = threading.Thread(target=run)
1303 t.start()
1304 while not running:
1305 time.sleep(0.01)
1306 running = False
1307 t.join()
1308 """
1309 rc, out, err = assert_python_ok("-c", script)
1310 self.assertEqual(out, b'')
1311 self.assertNotIn("Unhandled exception", err.decode())
1312
Victor Stinnereec93312016-08-18 18:13:10 +02001313 def test_bare_raise_in_brand_new_thread(self):
1314 def bare_raise():
1315 raise
1316
1317 class Issue27558(threading.Thread):
1318 exc = None
1319
1320 def run(self):
1321 try:
1322 bare_raise()
1323 except Exception as exc:
1324 self.exc = exc
1325
1326 thread = Issue27558()
1327 thread.start()
1328 thread.join()
1329 self.assertIsNotNone(thread.exc)
1330 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001331 # explicitly break the reference cycle to not leak a dangling thread
1332 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001333
Victor Stinnercd590a72019-05-28 00:39:52 +02001334
1335class ThreadRunFail(threading.Thread):
1336 def run(self):
1337 raise ValueError("run failed")
1338
1339
1340class ExceptHookTests(BaseTestCase):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001341 def setUp(self):
1342 restore_default_excepthook(self)
1343 super().setUp()
1344
Victor Stinnercd590a72019-05-28 00:39:52 +02001345 def test_excepthook(self):
1346 with support.captured_output("stderr") as stderr:
1347 thread = ThreadRunFail(name="excepthook thread")
1348 thread.start()
1349 thread.join()
1350
1351 stderr = stderr.getvalue().strip()
1352 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1353 self.assertIn('Traceback (most recent call last):\n', stderr)
1354 self.assertIn(' raise ValueError("run failed")', stderr)
1355 self.assertIn('ValueError: run failed', stderr)
1356
1357 @support.cpython_only
1358 def test_excepthook_thread_None(self):
1359 # threading.excepthook called with thread=None: log the thread
1360 # identifier in this case.
1361 with support.captured_output("stderr") as stderr:
1362 try:
1363 raise ValueError("bug")
1364 except Exception as exc:
1365 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001366 try:
1367 threading.excepthook(args)
1368 finally:
1369 # Explicitly break a reference cycle
1370 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001371
1372 stderr = stderr.getvalue().strip()
1373 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1374 self.assertIn('Traceback (most recent call last):\n', stderr)
1375 self.assertIn(' raise ValueError("bug")', stderr)
1376 self.assertIn('ValueError: bug', stderr)
1377
1378 def test_system_exit(self):
1379 class ThreadExit(threading.Thread):
1380 def run(self):
1381 sys.exit(1)
1382
1383 # threading.excepthook() silently ignores SystemExit
1384 with support.captured_output("stderr") as stderr:
1385 thread = ThreadExit()
1386 thread.start()
1387 thread.join()
1388
1389 self.assertEqual(stderr.getvalue(), '')
1390
1391 def test_custom_excepthook(self):
1392 args = None
1393
1394 def hook(hook_args):
1395 nonlocal args
1396 args = hook_args
1397
1398 try:
1399 with support.swap_attr(threading, 'excepthook', hook):
1400 thread = ThreadRunFail()
1401 thread.start()
1402 thread.join()
1403
1404 self.assertEqual(args.exc_type, ValueError)
1405 self.assertEqual(str(args.exc_value), 'run failed')
1406 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1407 self.assertIs(args.thread, thread)
1408 finally:
1409 # Break reference cycle
1410 args = None
1411
1412 def test_custom_excepthook_fail(self):
1413 def threading_hook(args):
1414 raise ValueError("threading_hook failed")
1415
1416 err_str = None
1417
1418 def sys_hook(exc_type, exc_value, exc_traceback):
1419 nonlocal err_str
1420 err_str = str(exc_value)
1421
1422 with support.swap_attr(threading, 'excepthook', threading_hook), \
1423 support.swap_attr(sys, 'excepthook', sys_hook), \
1424 support.captured_output('stderr') as stderr:
1425 thread = ThreadRunFail()
1426 thread.start()
1427 thread.join()
1428
1429 self.assertEqual(stderr.getvalue(),
1430 'Exception in threading.excepthook:\n')
1431 self.assertEqual(err_str, 'threading_hook failed')
1432
Mario Corchero750c5ab2020-11-12 18:27:44 +01001433 def test_original_excepthook(self):
1434 def run_thread():
1435 with support.captured_output("stderr") as output:
1436 thread = ThreadRunFail(name="excepthook thread")
1437 thread.start()
1438 thread.join()
1439 return output.getvalue()
1440
1441 def threading_hook(args):
1442 print("Running a thread failed", file=sys.stderr)
1443
1444 default_output = run_thread()
1445 with support.swap_attr(threading, 'excepthook', threading_hook):
1446 custom_hook_output = run_thread()
1447 threading.excepthook = threading.__excepthook__
1448 recovered_output = run_thread()
1449
1450 self.assertEqual(default_output, recovered_output)
1451 self.assertNotEqual(default_output, custom_hook_output)
1452 self.assertEqual(custom_hook_output, "Running a thread failed\n")
1453
Victor Stinnercd590a72019-05-28 00:39:52 +02001454
R David Murray19aeb432013-03-30 17:19:38 -04001455class TimerTests(BaseTestCase):
1456
1457 def setUp(self):
1458 BaseTestCase.setUp(self)
1459 self.callback_args = []
1460 self.callback_event = threading.Event()
1461
1462 def test_init_immutable_default_args(self):
1463 # Issue 17435: constructor defaults were mutable objects, they could be
1464 # mutated via the object attributes and affect other Timer objects.
1465 timer1 = threading.Timer(0.01, self._callback_spy)
1466 timer1.start()
1467 self.callback_event.wait()
1468 timer1.args.append("blah")
1469 timer1.kwargs["foo"] = "bar"
1470 self.callback_event.clear()
1471 timer2 = threading.Timer(0.01, self._callback_spy)
1472 timer2.start()
1473 self.callback_event.wait()
1474 self.assertEqual(len(self.callback_args), 2)
1475 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001476 timer1.join()
1477 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001478
1479 def _callback_spy(self, *args, **kwargs):
1480 self.callback_args.append((args[:], kwargs.copy()))
1481 self.callback_event.set()
1482
Antoine Pitrou557934f2009-11-06 22:41:14 +00001483class LockTests(lock_tests.LockTests):
1484 locktype = staticmethod(threading.Lock)
1485
Antoine Pitrou434736a2009-11-10 18:46:01 +00001486class PyRLockTests(lock_tests.RLockTests):
1487 locktype = staticmethod(threading._PyRLock)
1488
Charles-François Natali6b671b22012-01-28 11:36:04 +01001489@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001490class CRLockTests(lock_tests.RLockTests):
1491 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001492
1493class EventTests(lock_tests.EventTests):
1494 eventtype = staticmethod(threading.Event)
1495
1496class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001497 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001498 locktype = staticmethod(threading.Condition)
1499
1500class ConditionTests(lock_tests.ConditionTests):
1501 condtype = staticmethod(threading.Condition)
1502
1503class SemaphoreTests(lock_tests.SemaphoreTests):
1504 semtype = staticmethod(threading.Semaphore)
1505
1506class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1507 semtype = staticmethod(threading.BoundedSemaphore)
1508
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001509class BarrierTests(lock_tests.BarrierTests):
1510 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001511
Matěj Cepl608876b2019-05-23 22:30:00 +02001512
Martin Panter19e69c52015-11-14 12:46:42 +00001513class MiscTestCase(unittest.TestCase):
1514 def test__all__(self):
Victor Stinnerb136b1a2021-04-16 14:33:10 +02001515 restore_default_excepthook(self)
1516
Martin Panter19e69c52015-11-14 12:46:42 +00001517 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001518 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001519 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001520 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001521
Matěj Cepl608876b2019-05-23 22:30:00 +02001522
1523class InterruptMainTests(unittest.TestCase):
Antoine Pitrouba251c22021-03-11 23:35:45 +01001524 def check_interrupt_main_with_signal_handler(self, signum):
1525 def handler(signum, frame):
1526 1/0
1527
1528 old_handler = signal.signal(signum, handler)
1529 self.addCleanup(signal.signal, signum, old_handler)
1530
1531 with self.assertRaises(ZeroDivisionError):
1532 _thread.interrupt_main()
1533
1534 def check_interrupt_main_noerror(self, signum):
1535 handler = signal.getsignal(signum)
1536 try:
1537 # No exception should arise.
1538 signal.signal(signum, signal.SIG_IGN)
1539 _thread.interrupt_main(signum)
1540
1541 signal.signal(signum, signal.SIG_DFL)
1542 _thread.interrupt_main(signum)
1543 finally:
1544 # Restore original handler
1545 signal.signal(signum, handler)
1546
Matěj Cepl608876b2019-05-23 22:30:00 +02001547 def test_interrupt_main_subthread(self):
1548 # Calling start_new_thread with a function that executes interrupt_main
1549 # should raise KeyboardInterrupt upon completion.
1550 def call_interrupt():
1551 _thread.interrupt_main()
1552 t = threading.Thread(target=call_interrupt)
1553 with self.assertRaises(KeyboardInterrupt):
1554 t.start()
1555 t.join()
1556 t.join()
1557
1558 def test_interrupt_main_mainthread(self):
1559 # Make sure that if interrupt_main is called in main thread that
1560 # KeyboardInterrupt is raised instantly.
1561 with self.assertRaises(KeyboardInterrupt):
1562 _thread.interrupt_main()
1563
Antoine Pitrouba251c22021-03-11 23:35:45 +01001564 def test_interrupt_main_with_signal_handler(self):
1565 self.check_interrupt_main_with_signal_handler(signal.SIGINT)
1566 self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
Matěj Cepl608876b2019-05-23 22:30:00 +02001567
Antoine Pitrouba251c22021-03-11 23:35:45 +01001568 def test_interrupt_main_noerror(self):
1569 self.check_interrupt_main_noerror(signal.SIGINT)
1570 self.check_interrupt_main_noerror(signal.SIGTERM)
1571
1572 def test_interrupt_main_invalid_signal(self):
1573 self.assertRaises(ValueError, _thread.interrupt_main, -1)
1574 self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
1575 self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
Matěj Cepl608876b2019-05-23 22:30:00 +02001576
1577
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001578class AtexitTests(unittest.TestCase):
1579
1580 def test_atexit_output(self):
1581 rc, out, err = assert_python_ok("-c", """if True:
1582 import threading
1583
1584 def run_last():
1585 print('parrot')
1586
1587 threading._register_atexit(run_last)
1588 """)
1589
1590 self.assertFalse(err)
1591 self.assertEqual(out.strip(), b'parrot')
1592
1593 def test_atexit_called_once(self):
1594 rc, out, err = assert_python_ok("-c", """if True:
1595 import threading
1596 from unittest.mock import Mock
1597
1598 mock = Mock()
1599 threading._register_atexit(mock)
1600 mock.assert_not_called()
1601 # force early shutdown to ensure it was called once
1602 threading._shutdown()
1603 mock.assert_called_once()
1604 """)
1605
1606 self.assertFalse(err)
1607
1608 def test_atexit_after_shutdown(self):
1609 # The only way to do this is by registering an atexit within
1610 # an atexit, which is intended to raise an exception.
1611 rc, out, err = assert_python_ok("-c", """if True:
1612 import threading
1613
1614 def func():
1615 pass
1616
1617 def run_last():
1618 threading._register_atexit(func)
1619
1620 threading._register_atexit(run_last)
1621 """)
1622
1623 self.assertTrue(err)
1624 self.assertIn("RuntimeError: can't register atexit after shutdown",
1625 err.decode())
1626
1627
Tim Peters84d54892005-01-08 06:03:17 +00001628if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001629 unittest.main()