blob: ad82e304e32f3dbd51a72e7eae709621b664501e [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
Victor Stinnerc6e5c112020-02-03 15:17:15 +01007from test.support import verbose, import_module, cpython_only
Berker Peksagce643912015-05-06 06:33:17 +03008from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02009
Skip Montanaro4533f602001-08-20 20:28:48 +000010import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020012import _thread
13import threading
Skip Montanaro4533f602001-08-20 20:28:48 +000014import time
Tim Peters84d54892005-01-08 06:03:17 +000015import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000016import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000017import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000018import subprocess
Matěj Cepl608876b2019-05-23 22:30:00 +020019import signal
Victor Stinner066e5b12019-06-14 18:55:22 +020020import textwrap
Skip Montanaro4533f602001-08-20 20:28:48 +000021
Antoine Pitrou557934f2009-11-06 22:41:14 +000022from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000023from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000024
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030025
26# Between fork() and exec(), only async-safe functions are allowed (issues
27# #12316 and #11870), and fork() from a worker thread is known to trigger
28# problems with some operating systems (issue #3863): skip problematic tests
29# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010030platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030031
32
Tim Peters84d54892005-01-08 06:03:17 +000033# A trivial mutable counter.
34class Counter(object):
35 def __init__(self):
36 self.value = 0
37 def inc(self):
38 self.value += 1
39 def dec(self):
40 self.value -= 1
41 def get(self):
42 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000043
44class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000045 def __init__(self, name, testcase, sema, mutex, nrunning):
46 threading.Thread.__init__(self, name=name)
47 self.testcase = testcase
48 self.sema = sema
49 self.mutex = mutex
50 self.nrunning = nrunning
51
Skip Montanaro4533f602001-08-20 20:28:48 +000052 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000054 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000055 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000056 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000057
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 with self.sema:
59 with self.mutex:
60 self.nrunning.inc()
61 if verbose:
62 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020063 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000064
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 time.sleep(delay)
66 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000067 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000068
Christian Heimes4fbc72b2008-03-22 00:47:35 +000069 with self.mutex:
70 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020071 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000072 if verbose:
73 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000074 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000075
Skip Montanaro4533f602001-08-20 20:28:48 +000076
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000077class BaseTestCase(unittest.TestCase):
78 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080079 self._threads = threading_helper.threading_setup()
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000080
81 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +080082 threading_helper.threading_cleanup(*self._threads)
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000083 test.support.reap_children()
84
85
86class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000087
Tim Peters84d54892005-01-08 06:03:17 +000088 # Create a bunch of threads, let each do some work, wait until all are
89 # done.
90 def test_various_ops(self):
91 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
92 # times about 1 second per clump).
93 NUMTASKS = 10
94
95 # no more than 3 of the 10 can run at once
96 sema = threading.BoundedSemaphore(value=3)
97 mutex = threading.RLock()
98 numrunning = Counter()
99
100 threads = []
101
102 for i in range(NUMTASKS):
103 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
104 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200105 self.assertIsNone(t.ident)
106 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000107 t.start()
108
Jake Teslerb121f632019-05-22 08:43:17 -0700109 if hasattr(threading, 'get_native_id'):
110 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
111 self.assertNotIn(None, native_ids)
112 self.assertEqual(len(native_ids), NUMTASKS + 1)
113
Tim Peters84d54892005-01-08 06:03:17 +0000114 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000115 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000116 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200117 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200118 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000119 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200120 self.assertIsNotNone(t.ident)
121 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000122 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000124 self.assertEqual(numrunning.get(), 0)
125
Benjamin Petersond23f8222009-04-05 19:13:16 +0000126 def test_ident_of_no_threading_threads(self):
127 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200128 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000129 def f():
130 ident.append(threading.currentThread().ident)
131 done.set()
132 done = threading.Event()
133 ident = []
Hai Shie80697d2020-05-28 06:10:27 +0800134 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700135 tid = _thread.start_new_thread(f, ())
136 done.wait()
137 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000138 # Kill the "immortal" _DummyThread
139 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000140
Victor Stinner8c663fd2017-11-08 14:44:44 -0800141 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 def test_various_ops_small_stack(self):
143 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800144 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 try:
146 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000147 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000148 raise unittest.SkipTest(
149 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 self.test_various_ops()
151 threading.stack_size(0)
152
Victor Stinner8c663fd2017-11-08 14:44:44 -0800153 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154 def test_various_ops_large_stack(self):
155 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800156 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157 try:
158 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000159 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000160 raise unittest.SkipTest(
161 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162 self.test_various_ops()
163 threading.stack_size(0)
164
Tim Peters711906e2005-01-08 07:30:42 +0000165 def test_foreign_thread(self):
166 # Check that a "foreign" thread can use the threading module.
167 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000168 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000169 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000170 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000171 mutex.release()
172
173 mutex = threading.Lock()
174 mutex.acquire()
Hai Shie80697d2020-05-28 06:10:27 +0800175 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700176 tid = _thread.start_new_thread(f, (mutex,))
177 # Wait for the thread to finish.
178 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000179 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000180 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800181 #Issue 29376
182 self.assertTrue(threading._active[tid].is_alive())
183 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000184 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000185
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000186 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
187 # exposed at the Python level. This test relies on ctypes to get at it.
188 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200189 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190
191 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200192 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193
194 class AsyncExc(Exception):
195 pass
196
197 exception = ctypes.py_object(AsyncExc)
198
Antoine Pitroube4d8092009-10-18 18:27:17 +0000199 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200200 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200201 self.assertIsInstance(tid, int)
202 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000203
204 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200205 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000206 # The exception is async, so we might have to keep the VM busy until
207 # it notices.
208 while True:
209 pass
210 except AsyncExc:
211 pass
212 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000213 # This code is unreachable but it reflects the intent. If we wanted
214 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000215 self.fail("AsyncExc not raised")
216 try:
217 self.assertEqual(result, 1) # one thread state modified
218 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000219 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000220 pass
221
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000222 # `worker_started` is set by the thread when it's inside a try/except
223 # block waiting to catch the asynchronously set AsyncExc exception.
224 # `worker_saw_exception` is set by the thread upon catching that
225 # exception.
226 worker_started = threading.Event()
227 worker_saw_exception = threading.Event()
228
229 class Worker(threading.Thread):
230 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200231 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 self.finished = False
233
234 try:
235 while True:
236 worker_started.set()
237 time.sleep(0.1)
238 except AsyncExc:
239 self.finished = True
240 worker_saw_exception.set()
241
242 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000243 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 t.start()
245 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000246 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247
248 # Try a thread id that doesn't make sense.
249 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200251 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000252 self.assertEqual(result, 0) # no thread states modified
253
254 # Now raise an exception in the worker thread.
255 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000256 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000257 ret = worker_started.wait()
258 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000259 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000260 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200261 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000262 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000263 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200264 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000265 self.assertEqual(result, 1) # one thread state modified
266 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000267 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100268 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000270 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000271 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000272 if t.finished:
273 t.join()
274 # else the thread is still running, and we have no way to kill it
275
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000276 def test_limbo_cleanup(self):
277 # Issue 7481: Failure to start thread should cleanup the limbo map.
278 def fail_new_thread(*args):
279 raise threading.ThreadError()
280 _start_new_thread = threading._start_new_thread
281 threading._start_new_thread = fail_new_thread
282 try:
283 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000284 self.assertRaises(threading.ThreadError, t.start)
285 self.assertFalse(
286 t in threading._limbo,
287 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000288 finally:
289 threading._start_new_thread = _start_new_thread
290
Min ho Kimc4cacc82019-07-31 08:16:13 +1000291 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000292 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
293 # very late on python exit: on deallocation of a running thread for
294 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200295 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200297 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000298 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000299
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000300 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000301 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000302 ready.acquire()
303
Christian Heimes7d2ff882007-11-30 14:35:04 +0000304 # Module globals are cleared before __del__ is run
305 # So we save the functions in class dict
306 class C:
307 ensure = ctypes.pythonapi.PyGILState_Ensure
308 release = ctypes.pythonapi.PyGILState_Release
309 def __del__(self):
310 state = self.ensure()
311 self.release(state)
312
313 def waitingThread():
314 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000315 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000316 time.sleep(100)
317
Georg Brandl2067bfd2008-05-25 13:05:15 +0000318 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000319 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000320 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200321 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000322 self.assertEqual(rc, 42)
323
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324 def test_finalize_with_trace(self):
325 # Issue1733757
326 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200327 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000328 import sys, threading
329
330 # A deadlock-killer, to prevent the
331 # testsuite to hang forever
332 def killer():
333 import os, time
334 time.sleep(2)
335 print('program blocked; aborting')
336 os._exit(2)
337 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000338 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000339 t.start()
340
341 # This is the trace function
342 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000343 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000344 return func
345
346 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200347 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000348
Antoine Pitrou011bd622009-10-20 21:52:47 +0000349 def test_join_nondaemon_on_shutdown(self):
350 # Issue 1722344
351 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200352 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000353 import threading
354 from time import sleep
355
356 def child():
357 sleep(1)
358 # As a non-daemon thread we SHOULD wake up and nothing
359 # should be torn down yet
360 print("Woke up, sleep function is:", sleep)
361
362 threading.Thread(target=child).start()
363 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200364 """)
365 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000366 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200367 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000368
Christian Heimes1af737c2008-01-23 08:24:23 +0000369 def test_enumerate_after_join(self):
370 # Try hard to trigger #1703448: a thread is still returned in
371 # threading.enumerate() after it has been join()ed.
372 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000373 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000374 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000375 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000376 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000377 t = threading.Thread(target=lambda: None)
378 t.start()
379 t.join()
380 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000381 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000382 "#1703448 triggered after %d trials: %s" % (i, l))
383 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000384 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000385
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000386 def test_no_refcycle_through_target(self):
387 class RunSelfFunction(object):
388 def __init__(self, should_raise):
389 # The links in this refcycle from Thread back to self
390 # should be cleaned up when the thread completes.
391 self.should_raise = should_raise
392 self.thread = threading.Thread(target=self._run,
393 args=(self,),
394 kwargs={'yet_another':self})
395 self.thread.start()
396
397 def _run(self, other_ref, yet_another):
398 if self.should_raise:
399 raise SystemExit
400
401 cyclic_object = RunSelfFunction(should_raise=False)
402 weak_cyclic_object = weakref.ref(cyclic_object)
403 cyclic_object.thread.join()
404 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000405 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000406 msg=('%d references still around' %
407 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000408
409 raising_cyclic_object = RunSelfFunction(should_raise=True)
410 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
411 raising_cyclic_object.thread.join()
412 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000413 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000414 msg=('%d references still around' %
415 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000416
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000417 def test_old_threading_api(self):
418 # Just a quick sanity check to make sure the old method names are
419 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000420 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000421 t.isDaemon()
422 t.setDaemon(True)
423 t.getName()
424 t.setName("name")
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000425 e = threading.Event()
426 e.isSet()
427 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000428
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000429 def test_repr_daemon(self):
430 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200431 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000432 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200433 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000434
luzpaza5293b42017-11-05 07:37:50 -0600435 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000436 t = threading.Thread()
437 self.assertFalse(t.daemon)
438 t = threading.Thread(daemon=False)
439 self.assertFalse(t.daemon)
440 t = threading.Thread(daemon=True)
441 self.assertTrue(t.daemon)
442
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200443 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
444 def test_dummy_thread_after_fork(self):
445 # Issue #14308: a dummy thread in the active list doesn't mess up
446 # the after-fork mechanism.
447 code = """if 1:
448 import _thread, threading, os, time
449
450 def background_thread(evt):
451 # Creates and registers the _DummyThread instance
452 threading.current_thread()
453 evt.set()
454 time.sleep(10)
455
456 evt = threading.Event()
457 _thread.start_new_thread(background_thread, (evt,))
458 evt.wait()
459 assert threading.active_count() == 2, threading.active_count()
460 if os.fork() == 0:
461 assert threading.active_count() == 1, threading.active_count()
462 os._exit(0)
463 else:
464 os.wait()
465 """
466 _, out, err = assert_python_ok("-c", code)
467 self.assertEqual(out, b'')
468 self.assertEqual(err, b'')
469
Charles-François Natali9939cc82013-08-30 23:32:53 +0200470 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
471 def test_is_alive_after_fork(self):
472 # Try hard to trigger #18418: is_alive() could sometimes be True on
473 # threads that vanished after a fork.
474 old_interval = sys.getswitchinterval()
475 self.addCleanup(sys.setswitchinterval, old_interval)
476
477 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100478 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200479
480 for i in range(20):
481 t = threading.Thread(target=lambda: None)
482 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200483 pid = os.fork()
484 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700485 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200486 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700487 t.join()
488
Victor Stinnera9f96872020-03-31 21:49:44 +0200489 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200490
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300491 def test_main_thread(self):
492 main = threading.main_thread()
493 self.assertEqual(main.name, 'MainThread')
494 self.assertEqual(main.ident, threading.current_thread().ident)
495 self.assertEqual(main.ident, threading.get_ident())
496
497 def f():
498 self.assertNotEqual(threading.main_thread().ident,
499 threading.current_thread().ident)
500 th = threading.Thread(target=f)
501 th.start()
502 th.join()
503
504 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
505 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
506 def test_main_thread_after_fork(self):
507 code = """if 1:
508 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200509 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300510
511 pid = os.fork()
512 if pid == 0:
513 main = threading.main_thread()
514 print(main.name)
515 print(main.ident == threading.current_thread().ident)
516 print(main.ident == threading.get_ident())
517 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200518 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300519 """
520 _, out, err = assert_python_ok("-c", code)
521 data = out.decode().replace('\r', '')
522 self.assertEqual(err, b"")
523 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
524
525 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
526 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
527 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
528 def test_main_thread_after_fork_from_nonmain_thread(self):
529 code = """if 1:
530 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200531 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300532
533 def f():
534 pid = os.fork()
535 if pid == 0:
536 main = threading.main_thread()
537 print(main.name)
538 print(main.ident == threading.current_thread().ident)
539 print(main.ident == threading.get_ident())
540 # stdout is fully buffered because not a tty,
541 # we have to flush before exit.
542 sys.stdout.flush()
543 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200544 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300545
546 th = threading.Thread(target=f)
547 th.start()
548 th.join()
549 """
550 _, out, err = assert_python_ok("-c", code)
551 data = out.decode().replace('\r', '')
552 self.assertEqual(err, b"")
553 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
554
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200555 def test_main_thread_during_shutdown(self):
556 # bpo-31516: current_thread() should still point to the main thread
557 # at shutdown
558 code = """if 1:
559 import gc, threading
560
561 main_thread = threading.current_thread()
562 assert main_thread is threading.main_thread() # sanity check
563
564 class RefCycle:
565 def __init__(self):
566 self.cycle = self
567
568 def __del__(self):
569 print("GC:",
570 threading.current_thread() is main_thread,
571 threading.main_thread() is main_thread,
572 threading.enumerate() == [main_thread])
573
574 RefCycle()
575 gc.collect() # sanity check
576 x = RefCycle()
577 """
578 _, out, err = assert_python_ok("-c", code)
579 data = out.decode()
580 self.assertEqual(err, b"")
581 self.assertEqual(data.splitlines(),
582 ["GC: True True True"] * 2)
583
Victor Stinner468e5fe2019-06-13 01:30:17 +0200584 def test_finalization_shutdown(self):
585 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
586 # until Python thread states of all non-daemon threads get deleted.
587 #
588 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
589 # test the finalization of the main interpreter.
590 code = """if 1:
591 import os
592 import threading
593 import time
594 import random
595
596 def random_sleep():
597 seconds = random.random() * 0.010
598 time.sleep(seconds)
599
600 class Sleeper:
601 def __del__(self):
602 random_sleep()
603
604 tls = threading.local()
605
606 def f():
607 # Sleep a bit so that the thread is still running when
608 # Py_Finalize() is called.
609 random_sleep()
610 tls.x = Sleeper()
611 random_sleep()
612
613 threading.Thread(target=f).start()
614 random_sleep()
615 """
616 rc, out, err = assert_python_ok("-c", code)
617 self.assertEqual(err, b"")
618
Antoine Pitrou7b476992013-09-07 23:38:37 +0200619 def test_tstate_lock(self):
620 # Test an implementation detail of Thread objects.
621 started = _thread.allocate_lock()
622 finish = _thread.allocate_lock()
623 started.acquire()
624 finish.acquire()
625 def f():
626 started.release()
627 finish.acquire()
628 time.sleep(0.01)
629 # The tstate lock is None until the thread is started
630 t = threading.Thread(target=f)
631 self.assertIs(t._tstate_lock, None)
632 t.start()
633 started.acquire()
634 self.assertTrue(t.is_alive())
635 # The tstate lock can't be acquired when the thread is running
636 # (or suspended).
637 tstate_lock = t._tstate_lock
638 self.assertFalse(tstate_lock.acquire(timeout=0), False)
639 finish.release()
640 # When the thread ends, the state_lock can be successfully
641 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100642 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200643 # But is_alive() is still True: we hold _tstate_lock now, which
644 # prevents is_alive() from knowing the thread's end-of-life C code
645 # is done.
646 self.assertTrue(t.is_alive())
647 # Let is_alive() find out the C code is done.
648 tstate_lock.release()
649 self.assertFalse(t.is_alive())
650 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200651 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700652 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200653
Tim Peters72460fa2013-09-09 18:48:24 -0500654 def test_repr_stopped(self):
655 # Verify that "stopped" shows up in repr(Thread) appropriately.
656 started = _thread.allocate_lock()
657 finish = _thread.allocate_lock()
658 started.acquire()
659 finish.acquire()
660 def f():
661 started.release()
662 finish.acquire()
663 t = threading.Thread(target=f)
664 t.start()
665 started.acquire()
666 self.assertIn("started", repr(t))
667 finish.release()
668 # "stopped" should appear in the repr in a reasonable amount of time.
669 # Implementation detail: as of this writing, that's trivially true
670 # if .join() is called, and almost trivially true if .is_alive() is
671 # called. The detail we're testing here is that "stopped" shows up
672 # "all on its own".
673 LOOKING_FOR = "stopped"
674 for i in range(500):
675 if LOOKING_FOR in repr(t):
676 break
677 time.sleep(0.01)
678 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700679 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000680
Tim Peters7634e1c2013-10-08 20:55:51 -0500681 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500682 # BoundedSemaphore should raise ValueError if released too often.
683 for limit in range(1, 10):
684 bs = threading.BoundedSemaphore(limit)
685 threads = [threading.Thread(target=bs.acquire)
686 for _ in range(limit)]
687 for t in threads:
688 t.start()
689 for t in threads:
690 t.join()
691 threads = [threading.Thread(target=bs.release)
692 for _ in range(limit)]
693 for t in threads:
694 t.start()
695 for t in threads:
696 t.join()
697 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500698
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200699 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100700 def test_frame_tstate_tracing(self):
701 # Issue #14432: Crash when a generator is created in a C thread that is
702 # destroyed while the generator is still used. The issue was that a
703 # generator contains a frame, and the frame kept a reference to the
704 # Python state of the destroyed C thread. The crash occurs when a trace
705 # function is setup.
706
707 def noop_trace(frame, event, arg):
708 # no operation
709 return noop_trace
710
711 def generator():
712 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300713 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100714
715 def callback():
716 if callback.gen is None:
717 callback.gen = generator()
718 return next(callback.gen)
719 callback.gen = None
720
721 old_trace = sys.gettrace()
722 sys.settrace(noop_trace)
723 try:
724 # Install a trace function
725 threading.settrace(noop_trace)
726
727 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200728 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100729 _testcapi.call_in_temporary_c_thread(callback)
730
731 # Call the generator in a different Python thread, check that the
732 # generator didn't keep a reference to the destroyed thread state
733 for test in range(3):
734 # The trace function is still called here
735 callback()
736 finally:
737 sys.settrace(old_trace)
738
Victor Stinner6f75c872019-06-13 12:06:24 +0200739 @cpython_only
740 def test_shutdown_locks(self):
741 for daemon in (False, True):
742 with self.subTest(daemon=daemon):
743 event = threading.Event()
744 thread = threading.Thread(target=event.wait, daemon=daemon)
745
746 # Thread.start() must add lock to _shutdown_locks,
747 # but only for non-daemon thread
748 thread.start()
749 tstate_lock = thread._tstate_lock
750 if not daemon:
751 self.assertIn(tstate_lock, threading._shutdown_locks)
752 else:
753 self.assertNotIn(tstate_lock, threading._shutdown_locks)
754
755 # unblock the thread and join it
756 event.set()
757 thread.join()
758
759 # Thread._stop() must remove tstate_lock from _shutdown_locks.
760 # Daemon threads must never add it to _shutdown_locks.
761 self.assertNotIn(tstate_lock, threading._shutdown_locks)
762
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100763 def test_locals_at_exit(self):
764 # bpo-19466: thread locals must not be deleted before destructors
765 # are called
766 rc, out, err = assert_python_ok("-c", """if 1:
767 import threading
768
769 class Atexit:
770 def __del__(self):
771 print("thread_dict.atexit = %r" % thread_dict.atexit)
772
773 thread_dict = threading.local()
774 thread_dict.atexit = "value"
775
776 atexit = Atexit()
777 """)
778 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
779
Victor Stinner45956b92013-11-12 16:37:55 +0100780
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000781class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000782
783 def _run_and_join(self, script):
784 script = """if 1:
785 import sys, os, time, threading
786
787 # a thread, which waits for the main program to terminate
788 def joiningfunc(mainthread):
789 mainthread.join()
790 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000791 # stdout is fully buffered because not a tty, we have to flush
792 # before exit.
793 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000794 \n""" + script
795
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200796 rc, out, err = assert_python_ok("-c", script)
797 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000798 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000799
800 def test_1_join_on_shutdown(self):
801 # The usual case: on exit, wait for a non-daemon thread
802 script = """if 1:
803 import os
804 t = threading.Thread(target=joiningfunc,
805 args=(threading.current_thread(),))
806 t.start()
807 time.sleep(0.1)
808 print('end of main')
809 """
810 self._run_and_join(script)
811
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000812 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200813 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000814 def test_2_join_in_forked_process(self):
815 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000816 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200817 from test import support
818
Jesse Nollera8513972008-07-17 16:49:17 +0000819 childpid = os.fork()
820 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200821 # parent process
822 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000823 sys.exit(0)
824
Victor Stinnera9f96872020-03-31 21:49:44 +0200825 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000826 t = threading.Thread(target=joiningfunc,
827 args=(threading.current_thread(),))
828 t.start()
829 print('end of main')
830 """
831 self._run_and_join(script)
832
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000833 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200834 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000835 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000836 # Like the test above, but fork() was called from a worker thread
837 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000838
Jesse Nollera8513972008-07-17 16:49:17 +0000839 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200840 from test import support
841
Jesse Nollera8513972008-07-17 16:49:17 +0000842 main_thread = threading.current_thread()
843 def worker():
844 childpid = os.fork()
845 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200846 # parent process
847 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000848 sys.exit(0)
849
Victor Stinnera9f96872020-03-31 21:49:44 +0200850 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000851 t = threading.Thread(target=joiningfunc,
852 args=(main_thread,))
853 print('end of main')
854 t.start()
855 t.join() # Should not block: main_thread is already stopped
856
857 w = threading.Thread(target=worker)
858 w.start()
859 """
860 self._run_and_join(script)
861
Victor Stinner26d31862011-07-01 14:26:24 +0200862 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500863 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200864 # Check that a daemon thread cannot crash the interpreter on shutdown
865 # by manipulating internal structures that are being disposed of in
866 # the main thread.
867 script = """if True:
868 import os
869 import random
870 import sys
871 import time
872 import threading
873
874 thread_has_run = set()
875
876 def random_io():
877 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200878 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200879 with open(os.__file__, 'rb') as in_f:
880 stuff = in_f.read(200)
881 with open(os.devnull, 'wb') as null_f:
882 null_f.write(stuff)
883 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200884 thread_has_run.add(threading.current_thread())
885
886 def main():
887 count = 0
888 for _ in range(40):
889 new_thread = threading.Thread(target=random_io)
890 new_thread.daemon = True
891 new_thread.start()
892 count += 1
893 while len(thread_has_run) < count:
894 time.sleep(0.001)
895 # Trigger process shutdown
896 sys.exit(0)
897
898 main()
899 """
900 rc, out, err = assert_python_ok('-c', script)
901 self.assertFalse(err)
902
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100903 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100904 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100905 def test_reinit_tls_after_fork(self):
906 # Issue #13817: fork() would deadlock in a multithreaded program with
907 # the ad-hoc TLS implementation.
908
909 def do_fork_and_wait():
910 # just fork a child process and wait it
911 pid = os.fork()
912 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200913 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100914 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200915 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100916
917 # start a bunch of threads that will fork() child processes
918 threads = []
919 for i in range(16):
920 t = threading.Thread(target=do_fork_and_wait)
921 threads.append(t)
922 t.start()
923
924 for t in threads:
925 t.join()
926
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200927 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
928 def test_clear_threads_states_after_fork(self):
929 # Issue #17094: check that threads states are cleared after fork()
930
931 # start a bunch of threads
932 threads = []
933 for i in range(16):
934 t = threading.Thread(target=lambda : time.sleep(0.3))
935 threads.append(t)
936 t.start()
937
938 pid = os.fork()
939 if pid == 0:
940 # check that threads states have been cleared
941 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200942 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200943 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200944 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200945 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200946 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200947
948 for t in threads:
949 t.join()
950
Jesse Nollera8513972008-07-17 16:49:17 +0000951
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200952class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +0200953 def pipe(self):
954 r, w = os.pipe()
955 self.addCleanup(os.close, r)
956 self.addCleanup(os.close, w)
957 if hasattr(os, 'set_blocking'):
958 os.set_blocking(r, False)
959 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200960
961 def test_threads_join(self):
962 # Non-daemon threads should be joined at subinterpreter shutdown
963 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +0200964 r, w = self.pipe()
965 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200966 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200967 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200968 import threading
969 import time
970
Victor Stinner468e5fe2019-06-13 01:30:17 +0200971 def random_sleep():
972 seconds = random.random() * 0.010
973 time.sleep(seconds)
974
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200975 def f():
976 # Sleep a bit so that the thread is still running when
977 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200978 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200979 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200980
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200981 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200982 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200983 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100984 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200985 self.assertEqual(ret, 0)
986 # The thread was joined properly.
987 self.assertEqual(os.read(r, 1), b"x")
988
Antoine Pitrou7b476992013-09-07 23:38:37 +0200989 def test_threads_join_2(self):
990 # Same as above, but a delay gets introduced after the thread's
991 # Python code returned but before the thread state is deleted.
992 # To achieve this, we register a thread-local object which sleeps
993 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +0200994 r, w = self.pipe()
995 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +0200996 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200997 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +0200998 import threading
999 import time
1000
Victor Stinner468e5fe2019-06-13 01:30:17 +02001001 def random_sleep():
1002 seconds = random.random() * 0.010
1003 time.sleep(seconds)
1004
Antoine Pitrou7b476992013-09-07 23:38:37 +02001005 class Sleeper:
1006 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001007 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001008
1009 tls = threading.local()
1010
1011 def f():
1012 # Sleep a bit so that the thread is still running when
1013 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001014 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001015 tls.x = Sleeper()
1016 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001017
Antoine Pitrou7b476992013-09-07 23:38:37 +02001018 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001019 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001020 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001021 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001022 self.assertEqual(ret, 0)
1023 # The thread was joined properly.
1024 self.assertEqual(os.read(r, 1), b"x")
1025
Victor Stinner14d53312020-04-12 23:45:09 +02001026 @cpython_only
1027 def test_daemon_threads_fatal_error(self):
1028 subinterp_code = f"""if 1:
1029 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001030 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001031 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001032
Victor Stinner14d53312020-04-12 23:45:09 +02001033 def f():
1034 # Make sure the daemon thread is still running when
1035 # Py_EndInterpreter is called.
1036 time.sleep({test.support.SHORT_TIMEOUT})
1037 threading.Thread(target=f, daemon=True).start()
1038 """
1039 script = r"""if 1:
1040 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001041
Victor Stinner14d53312020-04-12 23:45:09 +02001042 _testcapi.run_in_subinterp(%r)
1043 """ % (subinterp_code,)
1044 with test.support.SuppressCrashReport():
1045 rc, out, err = assert_python_failure("-c", script)
1046 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1047 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001048
1049
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001050class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001051 # A RuntimeError should be raised if Thread.start() is called
1052 # multiple times.
1053 def test_start_thread_again(self):
1054 thread = threading.Thread()
1055 thread.start()
1056 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001057 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001058
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001059 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001060 current_thread = threading.current_thread()
1061 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001062
1063 def test_joining_inactive_thread(self):
1064 thread = threading.Thread()
1065 self.assertRaises(RuntimeError, thread.join)
1066
1067 def test_daemonize_active_thread(self):
1068 thread = threading.Thread()
1069 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001070 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001071 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001072
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001073 def test_releasing_unacquired_lock(self):
1074 lock = threading.Lock()
1075 self.assertRaises(RuntimeError, lock.release)
1076
Ned Deily9a7c5242011-05-28 00:19:56 -07001077 def test_recursion_limit(self):
1078 # Issue 9670
1079 # test that excessive recursion within a non-main thread causes
1080 # an exception rather than crashing the interpreter on platforms
1081 # like Mac OS X or FreeBSD which have small default stack sizes
1082 # for threads
1083 script = """if True:
1084 import threading
1085
1086 def recurse():
1087 return recurse()
1088
1089 def outer():
1090 try:
1091 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001092 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001093 pass
1094
1095 w = threading.Thread(target=outer)
1096 w.start()
1097 w.join()
1098 print('end of main thread')
1099 """
1100 expected_output = "end of main thread\n"
1101 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001102 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001103 stdout, stderr = p.communicate()
1104 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001105 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001106 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001107
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001108 def test_print_exception(self):
1109 script = r"""if True:
1110 import threading
1111 import time
1112
1113 running = False
1114 def run():
1115 global running
1116 running = True
1117 while running:
1118 time.sleep(0.01)
1119 1/0
1120 t = threading.Thread(target=run)
1121 t.start()
1122 while not running:
1123 time.sleep(0.01)
1124 running = False
1125 t.join()
1126 """
1127 rc, out, err = assert_python_ok("-c", script)
1128 self.assertEqual(out, b'')
1129 err = err.decode()
1130 self.assertIn("Exception in thread", err)
1131 self.assertIn("Traceback (most recent call last):", err)
1132 self.assertIn("ZeroDivisionError", err)
1133 self.assertNotIn("Unhandled exception", err)
1134
1135 def test_print_exception_stderr_is_none_1(self):
1136 script = r"""if True:
1137 import sys
1138 import threading
1139 import time
1140
1141 running = False
1142 def run():
1143 global running
1144 running = True
1145 while running:
1146 time.sleep(0.01)
1147 1/0
1148 t = threading.Thread(target=run)
1149 t.start()
1150 while not running:
1151 time.sleep(0.01)
1152 sys.stderr = None
1153 running = False
1154 t.join()
1155 """
1156 rc, out, err = assert_python_ok("-c", script)
1157 self.assertEqual(out, b'')
1158 err = err.decode()
1159 self.assertIn("Exception in thread", err)
1160 self.assertIn("Traceback (most recent call last):", err)
1161 self.assertIn("ZeroDivisionError", err)
1162 self.assertNotIn("Unhandled exception", err)
1163
1164 def test_print_exception_stderr_is_none_2(self):
1165 script = r"""if True:
1166 import sys
1167 import threading
1168 import time
1169
1170 running = False
1171 def run():
1172 global running
1173 running = True
1174 while running:
1175 time.sleep(0.01)
1176 1/0
1177 sys.stderr = None
1178 t = threading.Thread(target=run)
1179 t.start()
1180 while not running:
1181 time.sleep(0.01)
1182 running = False
1183 t.join()
1184 """
1185 rc, out, err = assert_python_ok("-c", script)
1186 self.assertEqual(out, b'')
1187 self.assertNotIn("Unhandled exception", err.decode())
1188
Victor Stinnereec93312016-08-18 18:13:10 +02001189 def test_bare_raise_in_brand_new_thread(self):
1190 def bare_raise():
1191 raise
1192
1193 class Issue27558(threading.Thread):
1194 exc = None
1195
1196 def run(self):
1197 try:
1198 bare_raise()
1199 except Exception as exc:
1200 self.exc = exc
1201
1202 thread = Issue27558()
1203 thread.start()
1204 thread.join()
1205 self.assertIsNotNone(thread.exc)
1206 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001207 # explicitly break the reference cycle to not leak a dangling thread
1208 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001209
Victor Stinnercd590a72019-05-28 00:39:52 +02001210
1211class ThreadRunFail(threading.Thread):
1212 def run(self):
1213 raise ValueError("run failed")
1214
1215
1216class ExceptHookTests(BaseTestCase):
1217 def test_excepthook(self):
1218 with support.captured_output("stderr") as stderr:
1219 thread = ThreadRunFail(name="excepthook thread")
1220 thread.start()
1221 thread.join()
1222
1223 stderr = stderr.getvalue().strip()
1224 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1225 self.assertIn('Traceback (most recent call last):\n', stderr)
1226 self.assertIn(' raise ValueError("run failed")', stderr)
1227 self.assertIn('ValueError: run failed', stderr)
1228
1229 @support.cpython_only
1230 def test_excepthook_thread_None(self):
1231 # threading.excepthook called with thread=None: log the thread
1232 # identifier in this case.
1233 with support.captured_output("stderr") as stderr:
1234 try:
1235 raise ValueError("bug")
1236 except Exception as exc:
1237 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001238 try:
1239 threading.excepthook(args)
1240 finally:
1241 # Explicitly break a reference cycle
1242 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001243
1244 stderr = stderr.getvalue().strip()
1245 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1246 self.assertIn('Traceback (most recent call last):\n', stderr)
1247 self.assertIn(' raise ValueError("bug")', stderr)
1248 self.assertIn('ValueError: bug', stderr)
1249
1250 def test_system_exit(self):
1251 class ThreadExit(threading.Thread):
1252 def run(self):
1253 sys.exit(1)
1254
1255 # threading.excepthook() silently ignores SystemExit
1256 with support.captured_output("stderr") as stderr:
1257 thread = ThreadExit()
1258 thread.start()
1259 thread.join()
1260
1261 self.assertEqual(stderr.getvalue(), '')
1262
1263 def test_custom_excepthook(self):
1264 args = None
1265
1266 def hook(hook_args):
1267 nonlocal args
1268 args = hook_args
1269
1270 try:
1271 with support.swap_attr(threading, 'excepthook', hook):
1272 thread = ThreadRunFail()
1273 thread.start()
1274 thread.join()
1275
1276 self.assertEqual(args.exc_type, ValueError)
1277 self.assertEqual(str(args.exc_value), 'run failed')
1278 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1279 self.assertIs(args.thread, thread)
1280 finally:
1281 # Break reference cycle
1282 args = None
1283
1284 def test_custom_excepthook_fail(self):
1285 def threading_hook(args):
1286 raise ValueError("threading_hook failed")
1287
1288 err_str = None
1289
1290 def sys_hook(exc_type, exc_value, exc_traceback):
1291 nonlocal err_str
1292 err_str = str(exc_value)
1293
1294 with support.swap_attr(threading, 'excepthook', threading_hook), \
1295 support.swap_attr(sys, 'excepthook', sys_hook), \
1296 support.captured_output('stderr') as stderr:
1297 thread = ThreadRunFail()
1298 thread.start()
1299 thread.join()
1300
1301 self.assertEqual(stderr.getvalue(),
1302 'Exception in threading.excepthook:\n')
1303 self.assertEqual(err_str, 'threading_hook failed')
1304
1305
R David Murray19aeb432013-03-30 17:19:38 -04001306class TimerTests(BaseTestCase):
1307
1308 def setUp(self):
1309 BaseTestCase.setUp(self)
1310 self.callback_args = []
1311 self.callback_event = threading.Event()
1312
1313 def test_init_immutable_default_args(self):
1314 # Issue 17435: constructor defaults were mutable objects, they could be
1315 # mutated via the object attributes and affect other Timer objects.
1316 timer1 = threading.Timer(0.01, self._callback_spy)
1317 timer1.start()
1318 self.callback_event.wait()
1319 timer1.args.append("blah")
1320 timer1.kwargs["foo"] = "bar"
1321 self.callback_event.clear()
1322 timer2 = threading.Timer(0.01, self._callback_spy)
1323 timer2.start()
1324 self.callback_event.wait()
1325 self.assertEqual(len(self.callback_args), 2)
1326 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001327 timer1.join()
1328 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001329
1330 def _callback_spy(self, *args, **kwargs):
1331 self.callback_args.append((args[:], kwargs.copy()))
1332 self.callback_event.set()
1333
Antoine Pitrou557934f2009-11-06 22:41:14 +00001334class LockTests(lock_tests.LockTests):
1335 locktype = staticmethod(threading.Lock)
1336
Antoine Pitrou434736a2009-11-10 18:46:01 +00001337class PyRLockTests(lock_tests.RLockTests):
1338 locktype = staticmethod(threading._PyRLock)
1339
Charles-François Natali6b671b22012-01-28 11:36:04 +01001340@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001341class CRLockTests(lock_tests.RLockTests):
1342 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001343
1344class EventTests(lock_tests.EventTests):
1345 eventtype = staticmethod(threading.Event)
1346
1347class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001348 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001349 locktype = staticmethod(threading.Condition)
1350
1351class ConditionTests(lock_tests.ConditionTests):
1352 condtype = staticmethod(threading.Condition)
1353
1354class SemaphoreTests(lock_tests.SemaphoreTests):
1355 semtype = staticmethod(threading.Semaphore)
1356
1357class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1358 semtype = staticmethod(threading.BoundedSemaphore)
1359
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001360class BarrierTests(lock_tests.BarrierTests):
1361 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001362
Matěj Cepl608876b2019-05-23 22:30:00 +02001363
Martin Panter19e69c52015-11-14 12:46:42 +00001364class MiscTestCase(unittest.TestCase):
1365 def test__all__(self):
1366 extra = {"ThreadError"}
1367 blacklist = {'currentThread', 'activeCount'}
1368 support.check__all__(self, threading, ('threading', '_thread'),
1369 extra=extra, blacklist=blacklist)
1370
Matěj Cepl608876b2019-05-23 22:30:00 +02001371
1372class InterruptMainTests(unittest.TestCase):
1373 def test_interrupt_main_subthread(self):
1374 # Calling start_new_thread with a function that executes interrupt_main
1375 # should raise KeyboardInterrupt upon completion.
1376 def call_interrupt():
1377 _thread.interrupt_main()
1378 t = threading.Thread(target=call_interrupt)
1379 with self.assertRaises(KeyboardInterrupt):
1380 t.start()
1381 t.join()
1382 t.join()
1383
1384 def test_interrupt_main_mainthread(self):
1385 # Make sure that if interrupt_main is called in main thread that
1386 # KeyboardInterrupt is raised instantly.
1387 with self.assertRaises(KeyboardInterrupt):
1388 _thread.interrupt_main()
1389
1390 def test_interrupt_main_noerror(self):
1391 handler = signal.getsignal(signal.SIGINT)
1392 try:
1393 # No exception should arise.
1394 signal.signal(signal.SIGINT, signal.SIG_IGN)
1395 _thread.interrupt_main()
1396
1397 signal.signal(signal.SIGINT, signal.SIG_DFL)
1398 _thread.interrupt_main()
1399 finally:
1400 # Restore original handler
1401 signal.signal(signal.SIGINT, handler)
1402
1403
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001404class AtexitTests(unittest.TestCase):
1405
1406 def test_atexit_output(self):
1407 rc, out, err = assert_python_ok("-c", """if True:
1408 import threading
1409
1410 def run_last():
1411 print('parrot')
1412
1413 threading._register_atexit(run_last)
1414 """)
1415
1416 self.assertFalse(err)
1417 self.assertEqual(out.strip(), b'parrot')
1418
1419 def test_atexit_called_once(self):
1420 rc, out, err = assert_python_ok("-c", """if True:
1421 import threading
1422 from unittest.mock import Mock
1423
1424 mock = Mock()
1425 threading._register_atexit(mock)
1426 mock.assert_not_called()
1427 # force early shutdown to ensure it was called once
1428 threading._shutdown()
1429 mock.assert_called_once()
1430 """)
1431
1432 self.assertFalse(err)
1433
1434 def test_atexit_after_shutdown(self):
1435 # The only way to do this is by registering an atexit within
1436 # an atexit, which is intended to raise an exception.
1437 rc, out, err = assert_python_ok("-c", """if True:
1438 import threading
1439
1440 def func():
1441 pass
1442
1443 def run_last():
1444 threading._register_atexit(func)
1445
1446 threading._register_atexit(run_last)
1447 """)
1448
1449 self.assertTrue(err)
1450 self.assertIn("RuntimeError: can't register atexit after shutdown",
1451 err.decode())
1452
1453
Tim Peters84d54892005-01-08 06:03:17 +00001454if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001455 unittest.main()