blob: 47e131ae27a148f5171ada66a33a1245136daae5 [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
Antoine Pitrou557934f2009-11-06 22:41:14 +000023from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000024from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000025
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030026
27# Between fork() and exec(), only async-safe functions are allowed (issues
28# #12316 and #11870), and fork() from a worker thread is known to trigger
29# problems with some operating systems (issue #3863): skip problematic tests
30# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010031platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030032
33
Tim Peters84d54892005-01-08 06:03:17 +000034# A trivial mutable counter.
35class Counter(object):
36 def __init__(self):
37 self.value = 0
38 def inc(self):
39 self.value += 1
40 def dec(self):
41 self.value -= 1
42 def get(self):
43 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000044
45class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000046 def __init__(self, name, testcase, sema, mutex, nrunning):
47 threading.Thread.__init__(self, name=name)
48 self.testcase = testcase
49 self.sema = sema
50 self.mutex = mutex
51 self.nrunning = nrunning
52
Skip Montanaro4533f602001-08-20 20:28:48 +000053 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000054 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000055 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000056 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000057 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000058
Christian Heimes4fbc72b2008-03-22 00:47:35 +000059 with self.sema:
60 with self.mutex:
61 self.nrunning.inc()
62 if verbose:
63 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020064 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000065
Christian Heimes4fbc72b2008-03-22 00:47:35 +000066 time.sleep(delay)
67 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000068 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000069
Christian Heimes4fbc72b2008-03-22 00:47:35 +000070 with self.mutex:
71 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020072 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000073 if verbose:
74 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000075 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000076
Skip Montanaro4533f602001-08-20 20:28:48 +000077
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000078class BaseTestCase(unittest.TestCase):
79 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080080 self._threads = threading_helper.threading_setup()
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000081
82 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +080083 threading_helper.threading_cleanup(*self._threads)
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000084 test.support.reap_children()
85
86
87class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000088
Tim Peters84d54892005-01-08 06:03:17 +000089 # Create a bunch of threads, let each do some work, wait until all are
90 # done.
91 def test_various_ops(self):
92 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
93 # times about 1 second per clump).
94 NUMTASKS = 10
95
96 # no more than 3 of the 10 can run at once
97 sema = threading.BoundedSemaphore(value=3)
98 mutex = threading.RLock()
99 numrunning = Counter()
100
101 threads = []
102
103 for i in range(NUMTASKS):
104 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
105 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200106 self.assertIsNone(t.ident)
107 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000108 t.start()
109
Jake Teslerb121f632019-05-22 08:43:17 -0700110 if hasattr(threading, 'get_native_id'):
111 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
112 self.assertNotIn(None, native_ids)
113 self.assertEqual(len(native_ids), NUMTASKS + 1)
114
Tim Peters84d54892005-01-08 06:03:17 +0000115 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000116 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000117 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200118 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200119 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000120 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200121 self.assertIsNotNone(t.ident)
122 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000123 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000124 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000125 self.assertEqual(numrunning.get(), 0)
126
Benjamin Petersond23f8222009-04-05 19:13:16 +0000127 def test_ident_of_no_threading_threads(self):
128 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200129 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000130 def f():
131 ident.append(threading.currentThread().ident)
132 done.set()
133 done = threading.Event()
134 ident = []
Hai Shie80697d2020-05-28 06:10:27 +0800135 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700136 tid = _thread.start_new_thread(f, ())
137 done.wait()
138 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000139 # Kill the "immortal" _DummyThread
140 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000141
Victor Stinner8c663fd2017-11-08 14:44:44 -0800142 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 def test_various_ops_small_stack(self):
144 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800145 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 try:
147 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000148 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000149 raise unittest.SkipTest(
150 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151 self.test_various_ops()
152 threading.stack_size(0)
153
Victor Stinner8c663fd2017-11-08 14:44:44 -0800154 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 def test_various_ops_large_stack(self):
156 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800157 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158 try:
159 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000160 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000161 raise unittest.SkipTest(
162 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000163 self.test_various_ops()
164 threading.stack_size(0)
165
Tim Peters711906e2005-01-08 07:30:42 +0000166 def test_foreign_thread(self):
167 # Check that a "foreign" thread can use the threading module.
168 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000169 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000170 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000171 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000172 mutex.release()
173
174 mutex = threading.Lock()
175 mutex.acquire()
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, (mutex,))
178 # Wait for the thread to finish.
179 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000180 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000181 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800182 #Issue 29376
183 self.assertTrue(threading._active[tid].is_alive())
184 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000185 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000186
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000187 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
188 # exposed at the Python level. This test relies on ctypes to get at it.
189 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200190 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191
192 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000194
195 class AsyncExc(Exception):
196 pass
197
198 exception = ctypes.py_object(AsyncExc)
199
Antoine Pitroube4d8092009-10-18 18:27:17 +0000200 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200201 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200202 self.assertIsInstance(tid, int)
203 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000204
205 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200206 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000207 # The exception is async, so we might have to keep the VM busy until
208 # it notices.
209 while True:
210 pass
211 except AsyncExc:
212 pass
213 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000214 # This code is unreachable but it reflects the intent. If we wanted
215 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000216 self.fail("AsyncExc not raised")
217 try:
218 self.assertEqual(result, 1) # one thread state modified
219 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000220 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000221 pass
222
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000223 # `worker_started` is set by the thread when it's inside a try/except
224 # block waiting to catch the asynchronously set AsyncExc exception.
225 # `worker_saw_exception` is set by the thread upon catching that
226 # exception.
227 worker_started = threading.Event()
228 worker_saw_exception = threading.Event()
229
230 class Worker(threading.Thread):
231 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200232 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 self.finished = False
234
235 try:
236 while True:
237 worker_started.set()
238 time.sleep(0.1)
239 except AsyncExc:
240 self.finished = True
241 worker_saw_exception.set()
242
243 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000244 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 t.start()
246 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000248
249 # Try a thread id that doesn't make sense.
250 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000251 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200252 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000253 self.assertEqual(result, 0) # no thread states modified
254
255 # Now raise an exception in the worker thread.
256 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000257 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000258 ret = worker_started.wait()
259 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000260 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000261 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200262 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000263 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000264 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200265 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000266 self.assertEqual(result, 1) # one thread state modified
267 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000268 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100269 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000270 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000271 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000272 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000273 if t.finished:
274 t.join()
275 # else the thread is still running, and we have no way to kill it
276
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000277 def test_limbo_cleanup(self):
278 # Issue 7481: Failure to start thread should cleanup the limbo map.
279 def fail_new_thread(*args):
280 raise threading.ThreadError()
281 _start_new_thread = threading._start_new_thread
282 threading._start_new_thread = fail_new_thread
283 try:
284 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000285 self.assertRaises(threading.ThreadError, t.start)
286 self.assertFalse(
287 t in threading._limbo,
288 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000289 finally:
290 threading._start_new_thread = _start_new_thread
291
Min ho Kimc4cacc82019-07-31 08:16:13 +1000292 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000293 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
294 # very late on python exit: on deallocation of a running thread for
295 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200296 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000297
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200298 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000299 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000300
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000301 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000302 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000303 ready.acquire()
304
Christian Heimes7d2ff882007-11-30 14:35:04 +0000305 # Module globals are cleared before __del__ is run
306 # So we save the functions in class dict
307 class C:
308 ensure = ctypes.pythonapi.PyGILState_Ensure
309 release = ctypes.pythonapi.PyGILState_Release
310 def __del__(self):
311 state = self.ensure()
312 self.release(state)
313
314 def waitingThread():
315 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000316 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000317 time.sleep(100)
318
Georg Brandl2067bfd2008-05-25 13:05:15 +0000319 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000320 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000321 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200322 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000323 self.assertEqual(rc, 42)
324
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000325 def test_finalize_with_trace(self):
326 # Issue1733757
327 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200328 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000329 import sys, threading
330
331 # A deadlock-killer, to prevent the
332 # testsuite to hang forever
333 def killer():
334 import os, time
335 time.sleep(2)
336 print('program blocked; aborting')
337 os._exit(2)
338 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000339 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000340 t.start()
341
342 # This is the trace function
343 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000344 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000345 return func
346
347 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200348 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000349
Antoine Pitrou011bd622009-10-20 21:52:47 +0000350 def test_join_nondaemon_on_shutdown(self):
351 # Issue 1722344
352 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200353 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000354 import threading
355 from time import sleep
356
357 def child():
358 sleep(1)
359 # As a non-daemon thread we SHOULD wake up and nothing
360 # should be torn down yet
361 print("Woke up, sleep function is:", sleep)
362
363 threading.Thread(target=child).start()
364 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200365 """)
366 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000367 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200368 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000369
Christian Heimes1af737c2008-01-23 08:24:23 +0000370 def test_enumerate_after_join(self):
371 # Try hard to trigger #1703448: a thread is still returned in
372 # threading.enumerate() after it has been join()ed.
373 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000374 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000375 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000376 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000377 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000378 t = threading.Thread(target=lambda: None)
379 t.start()
380 t.join()
381 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000382 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000383 "#1703448 triggered after %d trials: %s" % (i, l))
384 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000385 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000386
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000387 def test_no_refcycle_through_target(self):
388 class RunSelfFunction(object):
389 def __init__(self, should_raise):
390 # The links in this refcycle from Thread back to self
391 # should be cleaned up when the thread completes.
392 self.should_raise = should_raise
393 self.thread = threading.Thread(target=self._run,
394 args=(self,),
395 kwargs={'yet_another':self})
396 self.thread.start()
397
398 def _run(self, other_ref, yet_another):
399 if self.should_raise:
400 raise SystemExit
401
402 cyclic_object = RunSelfFunction(should_raise=False)
403 weak_cyclic_object = weakref.ref(cyclic_object)
404 cyclic_object.thread.join()
405 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000406 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000407 msg=('%d references still around' %
408 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000409
410 raising_cyclic_object = RunSelfFunction(should_raise=True)
411 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
412 raising_cyclic_object.thread.join()
413 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000414 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000415 msg=('%d references still around' %
416 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000417
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000418 def test_old_threading_api(self):
419 # Just a quick sanity check to make sure the old method names are
420 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000421 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000422 t.isDaemon()
423 t.setDaemon(True)
424 t.getName()
425 t.setName("name")
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000426 e = threading.Event()
427 e.isSet()
428 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000429
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000430 def test_repr_daemon(self):
431 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200432 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000433 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200434 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000435
luzpaza5293b42017-11-05 07:37:50 -0600436 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000437 t = threading.Thread()
438 self.assertFalse(t.daemon)
439 t = threading.Thread(daemon=False)
440 self.assertFalse(t.daemon)
441 t = threading.Thread(daemon=True)
442 self.assertTrue(t.daemon)
443
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200444 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
445 def test_dummy_thread_after_fork(self):
446 # Issue #14308: a dummy thread in the active list doesn't mess up
447 # the after-fork mechanism.
448 code = """if 1:
449 import _thread, threading, os, time
450
451 def background_thread(evt):
452 # Creates and registers the _DummyThread instance
453 threading.current_thread()
454 evt.set()
455 time.sleep(10)
456
457 evt = threading.Event()
458 _thread.start_new_thread(background_thread, (evt,))
459 evt.wait()
460 assert threading.active_count() == 2, threading.active_count()
461 if os.fork() == 0:
462 assert threading.active_count() == 1, threading.active_count()
463 os._exit(0)
464 else:
465 os.wait()
466 """
467 _, out, err = assert_python_ok("-c", code)
468 self.assertEqual(out, b'')
469 self.assertEqual(err, b'')
470
Charles-François Natali9939cc82013-08-30 23:32:53 +0200471 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
472 def test_is_alive_after_fork(self):
473 # Try hard to trigger #18418: is_alive() could sometimes be True on
474 # threads that vanished after a fork.
475 old_interval = sys.getswitchinterval()
476 self.addCleanup(sys.setswitchinterval, old_interval)
477
478 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100479 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200480
481 for i in range(20):
482 t = threading.Thread(target=lambda: None)
483 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200484 pid = os.fork()
485 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700486 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200487 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700488 t.join()
489
Victor Stinnera9f96872020-03-31 21:49:44 +0200490 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200491
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300492 def test_main_thread(self):
493 main = threading.main_thread()
494 self.assertEqual(main.name, 'MainThread')
495 self.assertEqual(main.ident, threading.current_thread().ident)
496 self.assertEqual(main.ident, threading.get_ident())
497
498 def f():
499 self.assertNotEqual(threading.main_thread().ident,
500 threading.current_thread().ident)
501 th = threading.Thread(target=f)
502 th.start()
503 th.join()
504
505 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
506 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
507 def test_main_thread_after_fork(self):
508 code = """if 1:
509 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200510 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300511
512 pid = os.fork()
513 if pid == 0:
514 main = threading.main_thread()
515 print(main.name)
516 print(main.ident == threading.current_thread().ident)
517 print(main.ident == threading.get_ident())
518 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200519 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300520 """
521 _, out, err = assert_python_ok("-c", code)
522 data = out.decode().replace('\r', '')
523 self.assertEqual(err, b"")
524 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
525
526 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
527 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
528 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
529 def test_main_thread_after_fork_from_nonmain_thread(self):
530 code = """if 1:
531 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200532 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300533
534 def f():
535 pid = os.fork()
536 if pid == 0:
537 main = threading.main_thread()
538 print(main.name)
539 print(main.ident == threading.current_thread().ident)
540 print(main.ident == threading.get_ident())
541 # stdout is fully buffered because not a tty,
542 # we have to flush before exit.
543 sys.stdout.flush()
544 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200545 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300546
547 th = threading.Thread(target=f)
548 th.start()
549 th.join()
550 """
551 _, out, err = assert_python_ok("-c", code)
552 data = out.decode().replace('\r', '')
553 self.assertEqual(err, b"")
554 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
555
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200556 def test_main_thread_during_shutdown(self):
557 # bpo-31516: current_thread() should still point to the main thread
558 # at shutdown
559 code = """if 1:
560 import gc, threading
561
562 main_thread = threading.current_thread()
563 assert main_thread is threading.main_thread() # sanity check
564
565 class RefCycle:
566 def __init__(self):
567 self.cycle = self
568
569 def __del__(self):
570 print("GC:",
571 threading.current_thread() is main_thread,
572 threading.main_thread() is main_thread,
573 threading.enumerate() == [main_thread])
574
575 RefCycle()
576 gc.collect() # sanity check
577 x = RefCycle()
578 """
579 _, out, err = assert_python_ok("-c", code)
580 data = out.decode()
581 self.assertEqual(err, b"")
582 self.assertEqual(data.splitlines(),
583 ["GC: True True True"] * 2)
584
Victor Stinner468e5fe2019-06-13 01:30:17 +0200585 def test_finalization_shutdown(self):
586 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
587 # until Python thread states of all non-daemon threads get deleted.
588 #
589 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
590 # test the finalization of the main interpreter.
591 code = """if 1:
592 import os
593 import threading
594 import time
595 import random
596
597 def random_sleep():
598 seconds = random.random() * 0.010
599 time.sleep(seconds)
600
601 class Sleeper:
602 def __del__(self):
603 random_sleep()
604
605 tls = threading.local()
606
607 def f():
608 # Sleep a bit so that the thread is still running when
609 # Py_Finalize() is called.
610 random_sleep()
611 tls.x = Sleeper()
612 random_sleep()
613
614 threading.Thread(target=f).start()
615 random_sleep()
616 """
617 rc, out, err = assert_python_ok("-c", code)
618 self.assertEqual(err, b"")
619
Antoine Pitrou7b476992013-09-07 23:38:37 +0200620 def test_tstate_lock(self):
621 # Test an implementation detail of Thread objects.
622 started = _thread.allocate_lock()
623 finish = _thread.allocate_lock()
624 started.acquire()
625 finish.acquire()
626 def f():
627 started.release()
628 finish.acquire()
629 time.sleep(0.01)
630 # The tstate lock is None until the thread is started
631 t = threading.Thread(target=f)
632 self.assertIs(t._tstate_lock, None)
633 t.start()
634 started.acquire()
635 self.assertTrue(t.is_alive())
636 # The tstate lock can't be acquired when the thread is running
637 # (or suspended).
638 tstate_lock = t._tstate_lock
639 self.assertFalse(tstate_lock.acquire(timeout=0), False)
640 finish.release()
641 # When the thread ends, the state_lock can be successfully
642 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100643 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200644 # But is_alive() is still True: we hold _tstate_lock now, which
645 # prevents is_alive() from knowing the thread's end-of-life C code
646 # is done.
647 self.assertTrue(t.is_alive())
648 # Let is_alive() find out the C code is done.
649 tstate_lock.release()
650 self.assertFalse(t.is_alive())
651 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200652 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700653 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200654
Tim Peters72460fa2013-09-09 18:48:24 -0500655 def test_repr_stopped(self):
656 # Verify that "stopped" shows up in repr(Thread) appropriately.
657 started = _thread.allocate_lock()
658 finish = _thread.allocate_lock()
659 started.acquire()
660 finish.acquire()
661 def f():
662 started.release()
663 finish.acquire()
664 t = threading.Thread(target=f)
665 t.start()
666 started.acquire()
667 self.assertIn("started", repr(t))
668 finish.release()
669 # "stopped" should appear in the repr in a reasonable amount of time.
670 # Implementation detail: as of this writing, that's trivially true
671 # if .join() is called, and almost trivially true if .is_alive() is
672 # called. The detail we're testing here is that "stopped" shows up
673 # "all on its own".
674 LOOKING_FOR = "stopped"
675 for i in range(500):
676 if LOOKING_FOR in repr(t):
677 break
678 time.sleep(0.01)
679 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700680 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000681
Tim Peters7634e1c2013-10-08 20:55:51 -0500682 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500683 # BoundedSemaphore should raise ValueError if released too often.
684 for limit in range(1, 10):
685 bs = threading.BoundedSemaphore(limit)
686 threads = [threading.Thread(target=bs.acquire)
687 for _ in range(limit)]
688 for t in threads:
689 t.start()
690 for t in threads:
691 t.join()
692 threads = [threading.Thread(target=bs.release)
693 for _ in range(limit)]
694 for t in threads:
695 t.start()
696 for t in threads:
697 t.join()
698 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500699
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200700 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100701 def test_frame_tstate_tracing(self):
702 # Issue #14432: Crash when a generator is created in a C thread that is
703 # destroyed while the generator is still used. The issue was that a
704 # generator contains a frame, and the frame kept a reference to the
705 # Python state of the destroyed C thread. The crash occurs when a trace
706 # function is setup.
707
708 def noop_trace(frame, event, arg):
709 # no operation
710 return noop_trace
711
712 def generator():
713 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300714 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100715
716 def callback():
717 if callback.gen is None:
718 callback.gen = generator()
719 return next(callback.gen)
720 callback.gen = None
721
722 old_trace = sys.gettrace()
723 sys.settrace(noop_trace)
724 try:
725 # Install a trace function
726 threading.settrace(noop_trace)
727
728 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200729 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100730 _testcapi.call_in_temporary_c_thread(callback)
731
732 # Call the generator in a different Python thread, check that the
733 # generator didn't keep a reference to the destroyed thread state
734 for test in range(3):
735 # The trace function is still called here
736 callback()
737 finally:
738 sys.settrace(old_trace)
739
Victor Stinner6f75c872019-06-13 12:06:24 +0200740 @cpython_only
741 def test_shutdown_locks(self):
742 for daemon in (False, True):
743 with self.subTest(daemon=daemon):
744 event = threading.Event()
745 thread = threading.Thread(target=event.wait, daemon=daemon)
746
747 # Thread.start() must add lock to _shutdown_locks,
748 # but only for non-daemon thread
749 thread.start()
750 tstate_lock = thread._tstate_lock
751 if not daemon:
752 self.assertIn(tstate_lock, threading._shutdown_locks)
753 else:
754 self.assertNotIn(tstate_lock, threading._shutdown_locks)
755
756 # unblock the thread and join it
757 event.set()
758 thread.join()
759
760 # Thread._stop() must remove tstate_lock from _shutdown_locks.
761 # Daemon threads must never add it to _shutdown_locks.
762 self.assertNotIn(tstate_lock, threading._shutdown_locks)
763
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100764 def test_locals_at_exit(self):
765 # bpo-19466: thread locals must not be deleted before destructors
766 # are called
767 rc, out, err = assert_python_ok("-c", """if 1:
768 import threading
769
770 class Atexit:
771 def __del__(self):
772 print("thread_dict.atexit = %r" % thread_dict.atexit)
773
774 thread_dict = threading.local()
775 thread_dict.atexit = "value"
776
777 atexit = Atexit()
778 """)
779 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
780
Victor Stinner45956b92013-11-12 16:37:55 +0100781
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000782class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000783
784 def _run_and_join(self, script):
785 script = """if 1:
786 import sys, os, time, threading
787
788 # a thread, which waits for the main program to terminate
789 def joiningfunc(mainthread):
790 mainthread.join()
791 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000792 # stdout is fully buffered because not a tty, we have to flush
793 # before exit.
794 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000795 \n""" + script
796
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200797 rc, out, err = assert_python_ok("-c", script)
798 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000799 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000800
801 def test_1_join_on_shutdown(self):
802 # The usual case: on exit, wait for a non-daemon thread
803 script = """if 1:
804 import os
805 t = threading.Thread(target=joiningfunc,
806 args=(threading.current_thread(),))
807 t.start()
808 time.sleep(0.1)
809 print('end of main')
810 """
811 self._run_and_join(script)
812
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000813 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200814 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000815 def test_2_join_in_forked_process(self):
816 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000817 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200818 from test import support
819
Jesse Nollera8513972008-07-17 16:49:17 +0000820 childpid = os.fork()
821 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200822 # parent process
823 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000824 sys.exit(0)
825
Victor Stinnera9f96872020-03-31 21:49:44 +0200826 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000827 t = threading.Thread(target=joiningfunc,
828 args=(threading.current_thread(),))
829 t.start()
830 print('end of main')
831 """
832 self._run_and_join(script)
833
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000834 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200835 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000836 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000837 # Like the test above, but fork() was called from a worker thread
838 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000839
Jesse Nollera8513972008-07-17 16:49:17 +0000840 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200841 from test import support
842
Jesse Nollera8513972008-07-17 16:49:17 +0000843 main_thread = threading.current_thread()
844 def worker():
845 childpid = os.fork()
846 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200847 # parent process
848 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000849 sys.exit(0)
850
Victor Stinnera9f96872020-03-31 21:49:44 +0200851 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000852 t = threading.Thread(target=joiningfunc,
853 args=(main_thread,))
854 print('end of main')
855 t.start()
856 t.join() # Should not block: main_thread is already stopped
857
858 w = threading.Thread(target=worker)
859 w.start()
860 """
861 self._run_and_join(script)
862
Victor Stinner26d31862011-07-01 14:26:24 +0200863 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500864 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200865 # Check that a daemon thread cannot crash the interpreter on shutdown
866 # by manipulating internal structures that are being disposed of in
867 # the main thread.
868 script = """if True:
869 import os
870 import random
871 import sys
872 import time
873 import threading
874
875 thread_has_run = set()
876
877 def random_io():
878 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200879 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200880 with open(os.__file__, 'rb') as in_f:
881 stuff = in_f.read(200)
882 with open(os.devnull, 'wb') as null_f:
883 null_f.write(stuff)
884 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200885 thread_has_run.add(threading.current_thread())
886
887 def main():
888 count = 0
889 for _ in range(40):
890 new_thread = threading.Thread(target=random_io)
891 new_thread.daemon = True
892 new_thread.start()
893 count += 1
894 while len(thread_has_run) < count:
895 time.sleep(0.001)
896 # Trigger process shutdown
897 sys.exit(0)
898
899 main()
900 """
901 rc, out, err = assert_python_ok('-c', script)
902 self.assertFalse(err)
903
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100904 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100905 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100906 def test_reinit_tls_after_fork(self):
907 # Issue #13817: fork() would deadlock in a multithreaded program with
908 # the ad-hoc TLS implementation.
909
910 def do_fork_and_wait():
911 # just fork a child process and wait it
912 pid = os.fork()
913 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200914 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100915 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200916 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100917
918 # start a bunch of threads that will fork() child processes
919 threads = []
920 for i in range(16):
921 t = threading.Thread(target=do_fork_and_wait)
922 threads.append(t)
923 t.start()
924
925 for t in threads:
926 t.join()
927
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200928 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
929 def test_clear_threads_states_after_fork(self):
930 # Issue #17094: check that threads states are cleared after fork()
931
932 # start a bunch of threads
933 threads = []
934 for i in range(16):
935 t = threading.Thread(target=lambda : time.sleep(0.3))
936 threads.append(t)
937 t.start()
938
939 pid = os.fork()
940 if pid == 0:
941 # check that threads states have been cleared
942 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200943 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200944 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200945 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200946 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200947 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200948
949 for t in threads:
950 t.join()
951
Jesse Nollera8513972008-07-17 16:49:17 +0000952
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200953class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +0200954 def pipe(self):
955 r, w = os.pipe()
956 self.addCleanup(os.close, r)
957 self.addCleanup(os.close, w)
958 if hasattr(os, 'set_blocking'):
959 os.set_blocking(r, False)
960 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200961
962 def test_threads_join(self):
963 # Non-daemon threads should be joined at subinterpreter shutdown
964 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +0200965 r, w = self.pipe()
966 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200967 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200968 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200969 import threading
970 import time
971
Victor Stinner468e5fe2019-06-13 01:30:17 +0200972 def random_sleep():
973 seconds = random.random() * 0.010
974 time.sleep(seconds)
975
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200976 def f():
977 # Sleep a bit so that the thread is still running when
978 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200979 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200980 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200981
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200982 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200983 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200984 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100985 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200986 self.assertEqual(ret, 0)
987 # The thread was joined properly.
988 self.assertEqual(os.read(r, 1), b"x")
989
Antoine Pitrou7b476992013-09-07 23:38:37 +0200990 def test_threads_join_2(self):
991 # Same as above, but a delay gets introduced after the thread's
992 # Python code returned but before the thread state is deleted.
993 # To achieve this, we register a thread-local object which sleeps
994 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +0200995 r, w = self.pipe()
996 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +0200997 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200998 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +0200999 import threading
1000 import time
1001
Victor Stinner468e5fe2019-06-13 01:30:17 +02001002 def random_sleep():
1003 seconds = random.random() * 0.010
1004 time.sleep(seconds)
1005
Antoine Pitrou7b476992013-09-07 23:38:37 +02001006 class Sleeper:
1007 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001008 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001009
1010 tls = threading.local()
1011
1012 def f():
1013 # Sleep a bit so that the thread is still running when
1014 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001015 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001016 tls.x = Sleeper()
1017 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001018
Antoine Pitrou7b476992013-09-07 23:38:37 +02001019 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001020 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001021 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001022 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001023 self.assertEqual(ret, 0)
1024 # The thread was joined properly.
1025 self.assertEqual(os.read(r, 1), b"x")
1026
Victor Stinner14d53312020-04-12 23:45:09 +02001027 @cpython_only
1028 def test_daemon_threads_fatal_error(self):
1029 subinterp_code = f"""if 1:
1030 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001031 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001032 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001033
Victor Stinner14d53312020-04-12 23:45:09 +02001034 def f():
1035 # Make sure the daemon thread is still running when
1036 # Py_EndInterpreter is called.
1037 time.sleep({test.support.SHORT_TIMEOUT})
1038 threading.Thread(target=f, daemon=True).start()
1039 """
1040 script = r"""if 1:
1041 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001042
Victor Stinner14d53312020-04-12 23:45:09 +02001043 _testcapi.run_in_subinterp(%r)
1044 """ % (subinterp_code,)
1045 with test.support.SuppressCrashReport():
1046 rc, out, err = assert_python_failure("-c", script)
1047 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1048 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001049
1050
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001051class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001052 # A RuntimeError should be raised if Thread.start() is called
1053 # multiple times.
1054 def test_start_thread_again(self):
1055 thread = threading.Thread()
1056 thread.start()
1057 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001058 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001059
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001060 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001061 current_thread = threading.current_thread()
1062 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001063
1064 def test_joining_inactive_thread(self):
1065 thread = threading.Thread()
1066 self.assertRaises(RuntimeError, thread.join)
1067
1068 def test_daemonize_active_thread(self):
1069 thread = threading.Thread()
1070 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001071 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001072 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001073
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001074 def test_releasing_unacquired_lock(self):
1075 lock = threading.Lock()
1076 self.assertRaises(RuntimeError, lock.release)
1077
Ned Deily9a7c5242011-05-28 00:19:56 -07001078 def test_recursion_limit(self):
1079 # Issue 9670
1080 # test that excessive recursion within a non-main thread causes
1081 # an exception rather than crashing the interpreter on platforms
1082 # like Mac OS X or FreeBSD which have small default stack sizes
1083 # for threads
1084 script = """if True:
1085 import threading
1086
1087 def recurse():
1088 return recurse()
1089
1090 def outer():
1091 try:
1092 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001093 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001094 pass
1095
1096 w = threading.Thread(target=outer)
1097 w.start()
1098 w.join()
1099 print('end of main thread')
1100 """
1101 expected_output = "end of main thread\n"
1102 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001103 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001104 stdout, stderr = p.communicate()
1105 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001106 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001107 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001108
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001109 def test_print_exception(self):
1110 script = r"""if True:
1111 import threading
1112 import time
1113
1114 running = False
1115 def run():
1116 global running
1117 running = True
1118 while running:
1119 time.sleep(0.01)
1120 1/0
1121 t = threading.Thread(target=run)
1122 t.start()
1123 while not running:
1124 time.sleep(0.01)
1125 running = False
1126 t.join()
1127 """
1128 rc, out, err = assert_python_ok("-c", script)
1129 self.assertEqual(out, b'')
1130 err = err.decode()
1131 self.assertIn("Exception in thread", err)
1132 self.assertIn("Traceback (most recent call last):", err)
1133 self.assertIn("ZeroDivisionError", err)
1134 self.assertNotIn("Unhandled exception", err)
1135
1136 def test_print_exception_stderr_is_none_1(self):
1137 script = r"""if True:
1138 import sys
1139 import threading
1140 import time
1141
1142 running = False
1143 def run():
1144 global running
1145 running = True
1146 while running:
1147 time.sleep(0.01)
1148 1/0
1149 t = threading.Thread(target=run)
1150 t.start()
1151 while not running:
1152 time.sleep(0.01)
1153 sys.stderr = None
1154 running = False
1155 t.join()
1156 """
1157 rc, out, err = assert_python_ok("-c", script)
1158 self.assertEqual(out, b'')
1159 err = err.decode()
1160 self.assertIn("Exception in thread", err)
1161 self.assertIn("Traceback (most recent call last):", err)
1162 self.assertIn("ZeroDivisionError", err)
1163 self.assertNotIn("Unhandled exception", err)
1164
1165 def test_print_exception_stderr_is_none_2(self):
1166 script = r"""if True:
1167 import sys
1168 import threading
1169 import time
1170
1171 running = False
1172 def run():
1173 global running
1174 running = True
1175 while running:
1176 time.sleep(0.01)
1177 1/0
1178 sys.stderr = None
1179 t = threading.Thread(target=run)
1180 t.start()
1181 while not running:
1182 time.sleep(0.01)
1183 running = False
1184 t.join()
1185 """
1186 rc, out, err = assert_python_ok("-c", script)
1187 self.assertEqual(out, b'')
1188 self.assertNotIn("Unhandled exception", err.decode())
1189
Victor Stinnereec93312016-08-18 18:13:10 +02001190 def test_bare_raise_in_brand_new_thread(self):
1191 def bare_raise():
1192 raise
1193
1194 class Issue27558(threading.Thread):
1195 exc = None
1196
1197 def run(self):
1198 try:
1199 bare_raise()
1200 except Exception as exc:
1201 self.exc = exc
1202
1203 thread = Issue27558()
1204 thread.start()
1205 thread.join()
1206 self.assertIsNotNone(thread.exc)
1207 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001208 # explicitly break the reference cycle to not leak a dangling thread
1209 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001210
Victor Stinnercd590a72019-05-28 00:39:52 +02001211
1212class ThreadRunFail(threading.Thread):
1213 def run(self):
1214 raise ValueError("run failed")
1215
1216
1217class ExceptHookTests(BaseTestCase):
1218 def test_excepthook(self):
1219 with support.captured_output("stderr") as stderr:
1220 thread = ThreadRunFail(name="excepthook thread")
1221 thread.start()
1222 thread.join()
1223
1224 stderr = stderr.getvalue().strip()
1225 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1226 self.assertIn('Traceback (most recent call last):\n', stderr)
1227 self.assertIn(' raise ValueError("run failed")', stderr)
1228 self.assertIn('ValueError: run failed', stderr)
1229
1230 @support.cpython_only
1231 def test_excepthook_thread_None(self):
1232 # threading.excepthook called with thread=None: log the thread
1233 # identifier in this case.
1234 with support.captured_output("stderr") as stderr:
1235 try:
1236 raise ValueError("bug")
1237 except Exception as exc:
1238 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001239 try:
1240 threading.excepthook(args)
1241 finally:
1242 # Explicitly break a reference cycle
1243 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001244
1245 stderr = stderr.getvalue().strip()
1246 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1247 self.assertIn('Traceback (most recent call last):\n', stderr)
1248 self.assertIn(' raise ValueError("bug")', stderr)
1249 self.assertIn('ValueError: bug', stderr)
1250
1251 def test_system_exit(self):
1252 class ThreadExit(threading.Thread):
1253 def run(self):
1254 sys.exit(1)
1255
1256 # threading.excepthook() silently ignores SystemExit
1257 with support.captured_output("stderr") as stderr:
1258 thread = ThreadExit()
1259 thread.start()
1260 thread.join()
1261
1262 self.assertEqual(stderr.getvalue(), '')
1263
1264 def test_custom_excepthook(self):
1265 args = None
1266
1267 def hook(hook_args):
1268 nonlocal args
1269 args = hook_args
1270
1271 try:
1272 with support.swap_attr(threading, 'excepthook', hook):
1273 thread = ThreadRunFail()
1274 thread.start()
1275 thread.join()
1276
1277 self.assertEqual(args.exc_type, ValueError)
1278 self.assertEqual(str(args.exc_value), 'run failed')
1279 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1280 self.assertIs(args.thread, thread)
1281 finally:
1282 # Break reference cycle
1283 args = None
1284
1285 def test_custom_excepthook_fail(self):
1286 def threading_hook(args):
1287 raise ValueError("threading_hook failed")
1288
1289 err_str = None
1290
1291 def sys_hook(exc_type, exc_value, exc_traceback):
1292 nonlocal err_str
1293 err_str = str(exc_value)
1294
1295 with support.swap_attr(threading, 'excepthook', threading_hook), \
1296 support.swap_attr(sys, 'excepthook', sys_hook), \
1297 support.captured_output('stderr') as stderr:
1298 thread = ThreadRunFail()
1299 thread.start()
1300 thread.join()
1301
1302 self.assertEqual(stderr.getvalue(),
1303 'Exception in threading.excepthook:\n')
1304 self.assertEqual(err_str, 'threading_hook failed')
1305
1306
R David Murray19aeb432013-03-30 17:19:38 -04001307class TimerTests(BaseTestCase):
1308
1309 def setUp(self):
1310 BaseTestCase.setUp(self)
1311 self.callback_args = []
1312 self.callback_event = threading.Event()
1313
1314 def test_init_immutable_default_args(self):
1315 # Issue 17435: constructor defaults were mutable objects, they could be
1316 # mutated via the object attributes and affect other Timer objects.
1317 timer1 = threading.Timer(0.01, self._callback_spy)
1318 timer1.start()
1319 self.callback_event.wait()
1320 timer1.args.append("blah")
1321 timer1.kwargs["foo"] = "bar"
1322 self.callback_event.clear()
1323 timer2 = threading.Timer(0.01, self._callback_spy)
1324 timer2.start()
1325 self.callback_event.wait()
1326 self.assertEqual(len(self.callback_args), 2)
1327 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001328 timer1.join()
1329 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001330
1331 def _callback_spy(self, *args, **kwargs):
1332 self.callback_args.append((args[:], kwargs.copy()))
1333 self.callback_event.set()
1334
Antoine Pitrou557934f2009-11-06 22:41:14 +00001335class LockTests(lock_tests.LockTests):
1336 locktype = staticmethod(threading.Lock)
1337
Antoine Pitrou434736a2009-11-10 18:46:01 +00001338class PyRLockTests(lock_tests.RLockTests):
1339 locktype = staticmethod(threading._PyRLock)
1340
Charles-François Natali6b671b22012-01-28 11:36:04 +01001341@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001342class CRLockTests(lock_tests.RLockTests):
1343 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001344
1345class EventTests(lock_tests.EventTests):
1346 eventtype = staticmethod(threading.Event)
1347
1348class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001349 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001350 locktype = staticmethod(threading.Condition)
1351
1352class ConditionTests(lock_tests.ConditionTests):
1353 condtype = staticmethod(threading.Condition)
1354
1355class SemaphoreTests(lock_tests.SemaphoreTests):
1356 semtype = staticmethod(threading.Semaphore)
1357
1358class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1359 semtype = staticmethod(threading.BoundedSemaphore)
1360
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001361class BarrierTests(lock_tests.BarrierTests):
1362 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001363
Matěj Cepl608876b2019-05-23 22:30:00 +02001364
Martin Panter19e69c52015-11-14 12:46:42 +00001365class MiscTestCase(unittest.TestCase):
1366 def test__all__(self):
1367 extra = {"ThreadError"}
1368 blacklist = {'currentThread', 'activeCount'}
1369 support.check__all__(self, threading, ('threading', '_thread'),
1370 extra=extra, blacklist=blacklist)
1371
Matěj Cepl608876b2019-05-23 22:30:00 +02001372
1373class InterruptMainTests(unittest.TestCase):
1374 def test_interrupt_main_subthread(self):
1375 # Calling start_new_thread with a function that executes interrupt_main
1376 # should raise KeyboardInterrupt upon completion.
1377 def call_interrupt():
1378 _thread.interrupt_main()
1379 t = threading.Thread(target=call_interrupt)
1380 with self.assertRaises(KeyboardInterrupt):
1381 t.start()
1382 t.join()
1383 t.join()
1384
1385 def test_interrupt_main_mainthread(self):
1386 # Make sure that if interrupt_main is called in main thread that
1387 # KeyboardInterrupt is raised instantly.
1388 with self.assertRaises(KeyboardInterrupt):
1389 _thread.interrupt_main()
1390
1391 def test_interrupt_main_noerror(self):
1392 handler = signal.getsignal(signal.SIGINT)
1393 try:
1394 # No exception should arise.
1395 signal.signal(signal.SIGINT, signal.SIG_IGN)
1396 _thread.interrupt_main()
1397
1398 signal.signal(signal.SIGINT, signal.SIG_DFL)
1399 _thread.interrupt_main()
1400 finally:
1401 # Restore original handler
1402 signal.signal(signal.SIGINT, handler)
1403
1404
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001405class AtexitTests(unittest.TestCase):
1406
1407 def test_atexit_output(self):
1408 rc, out, err = assert_python_ok("-c", """if True:
1409 import threading
1410
1411 def run_last():
1412 print('parrot')
1413
1414 threading._register_atexit(run_last)
1415 """)
1416
1417 self.assertFalse(err)
1418 self.assertEqual(out.strip(), b'parrot')
1419
1420 def test_atexit_called_once(self):
1421 rc, out, err = assert_python_ok("-c", """if True:
1422 import threading
1423 from unittest.mock import Mock
1424
1425 mock = Mock()
1426 threading._register_atexit(mock)
1427 mock.assert_not_called()
1428 # force early shutdown to ensure it was called once
1429 threading._shutdown()
1430 mock.assert_called_once()
1431 """)
1432
1433 self.assertFalse(err)
1434
1435 def test_atexit_after_shutdown(self):
1436 # The only way to do this is by registering an atexit within
1437 # an atexit, which is intended to raise an exception.
1438 rc, out, err = assert_python_ok("-c", """if True:
1439 import threading
1440
1441 def func():
1442 pass
1443
1444 def run_last():
1445 threading._register_atexit(func)
1446
1447 threading._register_atexit(run_last)
1448 """)
1449
1450 self.assertTrue(err)
1451 self.assertIn("RuntimeError: can't register atexit after shutdown",
1452 err.decode())
1453
1454
Tim Peters84d54892005-01-08 06:03:17 +00001455if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001456 unittest.main()