blob: 81e5f70d6d6aeae7b5a6b20503f1dbf217961e9e [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
Victor Stinnerc6e5c112020-02-03 15:17:15 +01006from test.support import verbose, import_module, cpython_only
Berker Peksagce643912015-05-06 06:33:17 +03007from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02008
Skip Montanaro4533f602001-08-20 20:28:48 +00009import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020011import _thread
12import threading
Skip Montanaro4533f602001-08-20 20:28:48 +000013import time
Tim Peters84d54892005-01-08 06:03:17 +000014import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000015import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000016import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000017import subprocess
Matěj Cepl608876b2019-05-23 22:30:00 +020018import signal
Victor Stinner066e5b12019-06-14 18:55:22 +020019import textwrap
Skip Montanaro4533f602001-08-20 20:28:48 +000020
Antoine Pitrou557934f2009-11-06 22:41:14 +000021from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000022from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000023
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030024
25# Between fork() and exec(), only async-safe functions are allowed (issues
26# #12316 and #11870), and fork() from a worker thread is known to trigger
27# problems with some operating systems (issue #3863): skip problematic tests
28# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010029platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030030
31
Tim Peters84d54892005-01-08 06:03:17 +000032# A trivial mutable counter.
33class Counter(object):
34 def __init__(self):
35 self.value = 0
36 def inc(self):
37 self.value += 1
38 def dec(self):
39 self.value -= 1
40 def get(self):
41 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000042
43class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000044 def __init__(self, name, testcase, sema, mutex, nrunning):
45 threading.Thread.__init__(self, name=name)
46 self.testcase = testcase
47 self.sema = sema
48 self.mutex = mutex
49 self.nrunning = nrunning
50
Skip Montanaro4533f602001-08-20 20:28:48 +000051 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000052 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000053 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000054 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000055 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000056
Christian Heimes4fbc72b2008-03-22 00:47:35 +000057 with self.sema:
58 with self.mutex:
59 self.nrunning.inc()
60 if verbose:
61 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020062 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000063
Christian Heimes4fbc72b2008-03-22 00:47:35 +000064 time.sleep(delay)
65 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000066 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000067
Christian Heimes4fbc72b2008-03-22 00:47:35 +000068 with self.mutex:
69 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020070 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 if verbose:
72 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000073 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000074
Skip Montanaro4533f602001-08-20 20:28:48 +000075
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000076class BaseTestCase(unittest.TestCase):
77 def setUp(self):
78 self._threads = test.support.threading_setup()
79
80 def tearDown(self):
81 test.support.threading_cleanup(*self._threads)
82 test.support.reap_children()
83
84
85class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000086
Tim Peters84d54892005-01-08 06:03:17 +000087 # Create a bunch of threads, let each do some work, wait until all are
88 # done.
89 def test_various_ops(self):
90 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
91 # times about 1 second per clump).
92 NUMTASKS = 10
93
94 # no more than 3 of the 10 can run at once
95 sema = threading.BoundedSemaphore(value=3)
96 mutex = threading.RLock()
97 numrunning = Counter()
98
99 threads = []
100
101 for i in range(NUMTASKS):
102 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
103 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200104 self.assertIsNone(t.ident)
105 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000106 t.start()
107
Jake Teslerb121f632019-05-22 08:43:17 -0700108 if hasattr(threading, 'get_native_id'):
109 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
110 self.assertNotIn(None, native_ids)
111 self.assertEqual(len(native_ids), NUMTASKS + 1)
112
Tim Peters84d54892005-01-08 06:03:17 +0000113 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000114 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000115 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200116 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200117 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000118 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200119 self.assertIsNotNone(t.ident)
120 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000121 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000123 self.assertEqual(numrunning.get(), 0)
124
Benjamin Petersond23f8222009-04-05 19:13:16 +0000125 def test_ident_of_no_threading_threads(self):
126 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200127 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000128 def f():
129 ident.append(threading.currentThread().ident)
130 done.set()
131 done = threading.Event()
132 ident = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700133 with support.wait_threads_exit():
134 tid = _thread.start_new_thread(f, ())
135 done.wait()
136 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000137 # Kill the "immortal" _DummyThread
138 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000139
Victor Stinner8c663fd2017-11-08 14:44:44 -0800140 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 def test_various_ops_small_stack(self):
142 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800143 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 try:
145 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000146 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000147 raise unittest.SkipTest(
148 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000149 self.test_various_ops()
150 threading.stack_size(0)
151
Victor Stinner8c663fd2017-11-08 14:44:44 -0800152 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153 def test_various_ops_large_stack(self):
154 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800155 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156 try:
157 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000158 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000159 raise unittest.SkipTest(
160 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000161 self.test_various_ops()
162 threading.stack_size(0)
163
Tim Peters711906e2005-01-08 07:30:42 +0000164 def test_foreign_thread(self):
165 # Check that a "foreign" thread can use the threading module.
166 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000167 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000168 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000169 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000170 mutex.release()
171
172 mutex = threading.Lock()
173 mutex.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700174 with support.wait_threads_exit():
175 tid = _thread.start_new_thread(f, (mutex,))
176 # Wait for the thread to finish.
177 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000178 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000179 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800180 #Issue 29376
181 self.assertTrue(threading._active[tid].is_alive())
182 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000183 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000184
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000185 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
186 # exposed at the Python level. This test relies on ctypes to get at it.
187 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200188 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000189
190 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200191 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000192
193 class AsyncExc(Exception):
194 pass
195
196 exception = ctypes.py_object(AsyncExc)
197
Antoine Pitroube4d8092009-10-18 18:27:17 +0000198 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200199 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200200 self.assertIsInstance(tid, int)
201 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000202
203 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200204 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000205 # The exception is async, so we might have to keep the VM busy until
206 # it notices.
207 while True:
208 pass
209 except AsyncExc:
210 pass
211 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000212 # This code is unreachable but it reflects the intent. If we wanted
213 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000214 self.fail("AsyncExc not raised")
215 try:
216 self.assertEqual(result, 1) # one thread state modified
217 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000218 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000219 pass
220
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221 # `worker_started` is set by the thread when it's inside a try/except
222 # block waiting to catch the asynchronously set AsyncExc exception.
223 # `worker_saw_exception` is set by the thread upon catching that
224 # exception.
225 worker_started = threading.Event()
226 worker_saw_exception = threading.Event()
227
228 class Worker(threading.Thread):
229 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200230 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000231 self.finished = False
232
233 try:
234 while True:
235 worker_started.set()
236 time.sleep(0.1)
237 except AsyncExc:
238 self.finished = True
239 worker_saw_exception.set()
240
241 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000242 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000243 t.start()
244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246
247 # Try a thread id that doesn't make sense.
248 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200250 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000251 self.assertEqual(result, 0) # no thread states modified
252
253 # Now raise an exception in the worker thread.
254 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000255 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000256 ret = worker_started.wait()
257 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000258 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000259 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200260 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000261 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000262 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200263 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000264 self.assertEqual(result, 1) # one thread state modified
265 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000266 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100267 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000268 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000269 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000270 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000271 if t.finished:
272 t.join()
273 # else the thread is still running, and we have no way to kill it
274
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000275 def test_limbo_cleanup(self):
276 # Issue 7481: Failure to start thread should cleanup the limbo map.
277 def fail_new_thread(*args):
278 raise threading.ThreadError()
279 _start_new_thread = threading._start_new_thread
280 threading._start_new_thread = fail_new_thread
281 try:
282 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000283 self.assertRaises(threading.ThreadError, t.start)
284 self.assertFalse(
285 t in threading._limbo,
286 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000287 finally:
288 threading._start_new_thread = _start_new_thread
289
Min ho Kimc4cacc82019-07-31 08:16:13 +1000290 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000291 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
292 # very late on python exit: on deallocation of a running thread for
293 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200294 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000295
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200296 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000297 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000298
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000299 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000300 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000301 ready.acquire()
302
Christian Heimes7d2ff882007-11-30 14:35:04 +0000303 # Module globals are cleared before __del__ is run
304 # So we save the functions in class dict
305 class C:
306 ensure = ctypes.pythonapi.PyGILState_Ensure
307 release = ctypes.pythonapi.PyGILState_Release
308 def __del__(self):
309 state = self.ensure()
310 self.release(state)
311
312 def waitingThread():
313 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000314 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000315 time.sleep(100)
316
Georg Brandl2067bfd2008-05-25 13:05:15 +0000317 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000318 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000319 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200320 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000321 self.assertEqual(rc, 42)
322
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000323 def test_finalize_with_trace(self):
324 # Issue1733757
325 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200326 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000327 import sys, threading
328
329 # A deadlock-killer, to prevent the
330 # testsuite to hang forever
331 def killer():
332 import os, time
333 time.sleep(2)
334 print('program blocked; aborting')
335 os._exit(2)
336 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000337 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000338 t.start()
339
340 # This is the trace function
341 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000342 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000343 return func
344
345 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200346 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000347
Antoine Pitrou011bd622009-10-20 21:52:47 +0000348 def test_join_nondaemon_on_shutdown(self):
349 # Issue 1722344
350 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200351 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000352 import threading
353 from time import sleep
354
355 def child():
356 sleep(1)
357 # As a non-daemon thread we SHOULD wake up and nothing
358 # should be torn down yet
359 print("Woke up, sleep function is:", sleep)
360
361 threading.Thread(target=child).start()
362 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200363 """)
364 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000365 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200366 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000367
Christian Heimes1af737c2008-01-23 08:24:23 +0000368 def test_enumerate_after_join(self):
369 # Try hard to trigger #1703448: a thread is still returned in
370 # threading.enumerate() after it has been join()ed.
371 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000372 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000373 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000374 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000375 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000376 t = threading.Thread(target=lambda: None)
377 t.start()
378 t.join()
379 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000380 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000381 "#1703448 triggered after %d trials: %s" % (i, l))
382 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000383 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000384
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000385 def test_no_refcycle_through_target(self):
386 class RunSelfFunction(object):
387 def __init__(self, should_raise):
388 # The links in this refcycle from Thread back to self
389 # should be cleaned up when the thread completes.
390 self.should_raise = should_raise
391 self.thread = threading.Thread(target=self._run,
392 args=(self,),
393 kwargs={'yet_another':self})
394 self.thread.start()
395
396 def _run(self, other_ref, yet_another):
397 if self.should_raise:
398 raise SystemExit
399
400 cyclic_object = RunSelfFunction(should_raise=False)
401 weak_cyclic_object = weakref.ref(cyclic_object)
402 cyclic_object.thread.join()
403 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000404 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000405 msg=('%d references still around' %
406 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000407
408 raising_cyclic_object = RunSelfFunction(should_raise=True)
409 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
410 raising_cyclic_object.thread.join()
411 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000412 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000413 msg=('%d references still around' %
414 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000415
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000416 def test_old_threading_api(self):
417 # Just a quick sanity check to make sure the old method names are
418 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000419 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000420 t.isDaemon()
421 t.setDaemon(True)
422 t.getName()
423 t.setName("name")
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000424 e = threading.Event()
425 e.isSet()
426 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000427
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000428 def test_repr_daemon(self):
429 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200430 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000431 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200432 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000433
luzpaza5293b42017-11-05 07:37:50 -0600434 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000435 t = threading.Thread()
436 self.assertFalse(t.daemon)
437 t = threading.Thread(daemon=False)
438 self.assertFalse(t.daemon)
439 t = threading.Thread(daemon=True)
440 self.assertTrue(t.daemon)
441
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200442 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
443 def test_dummy_thread_after_fork(self):
444 # Issue #14308: a dummy thread in the active list doesn't mess up
445 # the after-fork mechanism.
446 code = """if 1:
447 import _thread, threading, os, time
448
449 def background_thread(evt):
450 # Creates and registers the _DummyThread instance
451 threading.current_thread()
452 evt.set()
453 time.sleep(10)
454
455 evt = threading.Event()
456 _thread.start_new_thread(background_thread, (evt,))
457 evt.wait()
458 assert threading.active_count() == 2, threading.active_count()
459 if os.fork() == 0:
460 assert threading.active_count() == 1, threading.active_count()
461 os._exit(0)
462 else:
463 os.wait()
464 """
465 _, out, err = assert_python_ok("-c", code)
466 self.assertEqual(out, b'')
467 self.assertEqual(err, b'')
468
Charles-François Natali9939cc82013-08-30 23:32:53 +0200469 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
470 def test_is_alive_after_fork(self):
471 # Try hard to trigger #18418: is_alive() could sometimes be True on
472 # threads that vanished after a fork.
473 old_interval = sys.getswitchinterval()
474 self.addCleanup(sys.setswitchinterval, old_interval)
475
476 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100477 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200478
479 for i in range(20):
480 t = threading.Thread(target=lambda: None)
481 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200482 pid = os.fork()
483 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700484 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200485 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700486 t.join()
487
Victor Stinnera9f96872020-03-31 21:49:44 +0200488 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200489
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300490 def test_main_thread(self):
491 main = threading.main_thread()
492 self.assertEqual(main.name, 'MainThread')
493 self.assertEqual(main.ident, threading.current_thread().ident)
494 self.assertEqual(main.ident, threading.get_ident())
495
496 def f():
497 self.assertNotEqual(threading.main_thread().ident,
498 threading.current_thread().ident)
499 th = threading.Thread(target=f)
500 th.start()
501 th.join()
502
503 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
504 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
505 def test_main_thread_after_fork(self):
506 code = """if 1:
507 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200508 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300509
510 pid = os.fork()
511 if pid == 0:
512 main = threading.main_thread()
513 print(main.name)
514 print(main.ident == threading.current_thread().ident)
515 print(main.ident == threading.get_ident())
516 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200517 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300518 """
519 _, out, err = assert_python_ok("-c", code)
520 data = out.decode().replace('\r', '')
521 self.assertEqual(err, b"")
522 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
523
524 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
525 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
526 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
527 def test_main_thread_after_fork_from_nonmain_thread(self):
528 code = """if 1:
529 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200530 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300531
532 def f():
533 pid = os.fork()
534 if pid == 0:
535 main = threading.main_thread()
536 print(main.name)
537 print(main.ident == threading.current_thread().ident)
538 print(main.ident == threading.get_ident())
539 # stdout is fully buffered because not a tty,
540 # we have to flush before exit.
541 sys.stdout.flush()
542 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200543 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300544
545 th = threading.Thread(target=f)
546 th.start()
547 th.join()
548 """
549 _, out, err = assert_python_ok("-c", code)
550 data = out.decode().replace('\r', '')
551 self.assertEqual(err, b"")
552 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
553
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200554 def test_main_thread_during_shutdown(self):
555 # bpo-31516: current_thread() should still point to the main thread
556 # at shutdown
557 code = """if 1:
558 import gc, threading
559
560 main_thread = threading.current_thread()
561 assert main_thread is threading.main_thread() # sanity check
562
563 class RefCycle:
564 def __init__(self):
565 self.cycle = self
566
567 def __del__(self):
568 print("GC:",
569 threading.current_thread() is main_thread,
570 threading.main_thread() is main_thread,
571 threading.enumerate() == [main_thread])
572
573 RefCycle()
574 gc.collect() # sanity check
575 x = RefCycle()
576 """
577 _, out, err = assert_python_ok("-c", code)
578 data = out.decode()
579 self.assertEqual(err, b"")
580 self.assertEqual(data.splitlines(),
581 ["GC: True True True"] * 2)
582
Victor Stinner468e5fe2019-06-13 01:30:17 +0200583 def test_finalization_shutdown(self):
584 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
585 # until Python thread states of all non-daemon threads get deleted.
586 #
587 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
588 # test the finalization of the main interpreter.
589 code = """if 1:
590 import os
591 import threading
592 import time
593 import random
594
595 def random_sleep():
596 seconds = random.random() * 0.010
597 time.sleep(seconds)
598
599 class Sleeper:
600 def __del__(self):
601 random_sleep()
602
603 tls = threading.local()
604
605 def f():
606 # Sleep a bit so that the thread is still running when
607 # Py_Finalize() is called.
608 random_sleep()
609 tls.x = Sleeper()
610 random_sleep()
611
612 threading.Thread(target=f).start()
613 random_sleep()
614 """
615 rc, out, err = assert_python_ok("-c", code)
616 self.assertEqual(err, b"")
617
Antoine Pitrou7b476992013-09-07 23:38:37 +0200618 def test_tstate_lock(self):
619 # Test an implementation detail of Thread objects.
620 started = _thread.allocate_lock()
621 finish = _thread.allocate_lock()
622 started.acquire()
623 finish.acquire()
624 def f():
625 started.release()
626 finish.acquire()
627 time.sleep(0.01)
628 # The tstate lock is None until the thread is started
629 t = threading.Thread(target=f)
630 self.assertIs(t._tstate_lock, None)
631 t.start()
632 started.acquire()
633 self.assertTrue(t.is_alive())
634 # The tstate lock can't be acquired when the thread is running
635 # (or suspended).
636 tstate_lock = t._tstate_lock
637 self.assertFalse(tstate_lock.acquire(timeout=0), False)
638 finish.release()
639 # When the thread ends, the state_lock can be successfully
640 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100641 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200642 # But is_alive() is still True: we hold _tstate_lock now, which
643 # prevents is_alive() from knowing the thread's end-of-life C code
644 # is done.
645 self.assertTrue(t.is_alive())
646 # Let is_alive() find out the C code is done.
647 tstate_lock.release()
648 self.assertFalse(t.is_alive())
649 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200650 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700651 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200652
Tim Peters72460fa2013-09-09 18:48:24 -0500653 def test_repr_stopped(self):
654 # Verify that "stopped" shows up in repr(Thread) appropriately.
655 started = _thread.allocate_lock()
656 finish = _thread.allocate_lock()
657 started.acquire()
658 finish.acquire()
659 def f():
660 started.release()
661 finish.acquire()
662 t = threading.Thread(target=f)
663 t.start()
664 started.acquire()
665 self.assertIn("started", repr(t))
666 finish.release()
667 # "stopped" should appear in the repr in a reasonable amount of time.
668 # Implementation detail: as of this writing, that's trivially true
669 # if .join() is called, and almost trivially true if .is_alive() is
670 # called. The detail we're testing here is that "stopped" shows up
671 # "all on its own".
672 LOOKING_FOR = "stopped"
673 for i in range(500):
674 if LOOKING_FOR in repr(t):
675 break
676 time.sleep(0.01)
677 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700678 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000679
Tim Peters7634e1c2013-10-08 20:55:51 -0500680 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500681 # BoundedSemaphore should raise ValueError if released too often.
682 for limit in range(1, 10):
683 bs = threading.BoundedSemaphore(limit)
684 threads = [threading.Thread(target=bs.acquire)
685 for _ in range(limit)]
686 for t in threads:
687 t.start()
688 for t in threads:
689 t.join()
690 threads = [threading.Thread(target=bs.release)
691 for _ in range(limit)]
692 for t in threads:
693 t.start()
694 for t in threads:
695 t.join()
696 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500697
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200698 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100699 def test_frame_tstate_tracing(self):
700 # Issue #14432: Crash when a generator is created in a C thread that is
701 # destroyed while the generator is still used. The issue was that a
702 # generator contains a frame, and the frame kept a reference to the
703 # Python state of the destroyed C thread. The crash occurs when a trace
704 # function is setup.
705
706 def noop_trace(frame, event, arg):
707 # no operation
708 return noop_trace
709
710 def generator():
711 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300712 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100713
714 def callback():
715 if callback.gen is None:
716 callback.gen = generator()
717 return next(callback.gen)
718 callback.gen = None
719
720 old_trace = sys.gettrace()
721 sys.settrace(noop_trace)
722 try:
723 # Install a trace function
724 threading.settrace(noop_trace)
725
726 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200727 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100728 _testcapi.call_in_temporary_c_thread(callback)
729
730 # Call the generator in a different Python thread, check that the
731 # generator didn't keep a reference to the destroyed thread state
732 for test in range(3):
733 # The trace function is still called here
734 callback()
735 finally:
736 sys.settrace(old_trace)
737
Victor Stinner6f75c872019-06-13 12:06:24 +0200738 @cpython_only
739 def test_shutdown_locks(self):
740 for daemon in (False, True):
741 with self.subTest(daemon=daemon):
742 event = threading.Event()
743 thread = threading.Thread(target=event.wait, daemon=daemon)
744
745 # Thread.start() must add lock to _shutdown_locks,
746 # but only for non-daemon thread
747 thread.start()
748 tstate_lock = thread._tstate_lock
749 if not daemon:
750 self.assertIn(tstate_lock, threading._shutdown_locks)
751 else:
752 self.assertNotIn(tstate_lock, threading._shutdown_locks)
753
754 # unblock the thread and join it
755 event.set()
756 thread.join()
757
758 # Thread._stop() must remove tstate_lock from _shutdown_locks.
759 # Daemon threads must never add it to _shutdown_locks.
760 self.assertNotIn(tstate_lock, threading._shutdown_locks)
761
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100762 def test_locals_at_exit(self):
763 # bpo-19466: thread locals must not be deleted before destructors
764 # are called
765 rc, out, err = assert_python_ok("-c", """if 1:
766 import threading
767
768 class Atexit:
769 def __del__(self):
770 print("thread_dict.atexit = %r" % thread_dict.atexit)
771
772 thread_dict = threading.local()
773 thread_dict.atexit = "value"
774
775 atexit = Atexit()
776 """)
777 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
778
Victor Stinner45956b92013-11-12 16:37:55 +0100779
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000780class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000781
782 def _run_and_join(self, script):
783 script = """if 1:
784 import sys, os, time, threading
785
786 # a thread, which waits for the main program to terminate
787 def joiningfunc(mainthread):
788 mainthread.join()
789 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000790 # stdout is fully buffered because not a tty, we have to flush
791 # before exit.
792 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000793 \n""" + script
794
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200795 rc, out, err = assert_python_ok("-c", script)
796 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000797 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000798
799 def test_1_join_on_shutdown(self):
800 # The usual case: on exit, wait for a non-daemon thread
801 script = """if 1:
802 import os
803 t = threading.Thread(target=joiningfunc,
804 args=(threading.current_thread(),))
805 t.start()
806 time.sleep(0.1)
807 print('end of main')
808 """
809 self._run_and_join(script)
810
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000811 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200812 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000813 def test_2_join_in_forked_process(self):
814 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000815 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200816 from test import support
817
Jesse Nollera8513972008-07-17 16:49:17 +0000818 childpid = os.fork()
819 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200820 # parent process
821 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000822 sys.exit(0)
823
Victor Stinnera9f96872020-03-31 21:49:44 +0200824 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000825 t = threading.Thread(target=joiningfunc,
826 args=(threading.current_thread(),))
827 t.start()
828 print('end of main')
829 """
830 self._run_and_join(script)
831
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000832 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200833 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000834 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000835 # Like the test above, but fork() was called from a worker thread
836 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000837
Jesse Nollera8513972008-07-17 16:49:17 +0000838 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200839 from test import support
840
Jesse Nollera8513972008-07-17 16:49:17 +0000841 main_thread = threading.current_thread()
842 def worker():
843 childpid = os.fork()
844 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200845 # parent process
846 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000847 sys.exit(0)
848
Victor Stinnera9f96872020-03-31 21:49:44 +0200849 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000850 t = threading.Thread(target=joiningfunc,
851 args=(main_thread,))
852 print('end of main')
853 t.start()
854 t.join() # Should not block: main_thread is already stopped
855
856 w = threading.Thread(target=worker)
857 w.start()
858 """
859 self._run_and_join(script)
860
Victor Stinner26d31862011-07-01 14:26:24 +0200861 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500862 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200863 # Check that a daemon thread cannot crash the interpreter on shutdown
864 # by manipulating internal structures that are being disposed of in
865 # the main thread.
866 script = """if True:
867 import os
868 import random
869 import sys
870 import time
871 import threading
872
873 thread_has_run = set()
874
875 def random_io():
876 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200877 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200878 with open(os.__file__, 'rb') as in_f:
879 stuff = in_f.read(200)
880 with open(os.devnull, 'wb') as null_f:
881 null_f.write(stuff)
882 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200883 thread_has_run.add(threading.current_thread())
884
885 def main():
886 count = 0
887 for _ in range(40):
888 new_thread = threading.Thread(target=random_io)
889 new_thread.daemon = True
890 new_thread.start()
891 count += 1
892 while len(thread_has_run) < count:
893 time.sleep(0.001)
894 # Trigger process shutdown
895 sys.exit(0)
896
897 main()
898 """
899 rc, out, err = assert_python_ok('-c', script)
900 self.assertFalse(err)
901
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100902 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100903 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100904 def test_reinit_tls_after_fork(self):
905 # Issue #13817: fork() would deadlock in a multithreaded program with
906 # the ad-hoc TLS implementation.
907
908 def do_fork_and_wait():
909 # just fork a child process and wait it
910 pid = os.fork()
911 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200912 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100913 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200914 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100915
916 # start a bunch of threads that will fork() child processes
917 threads = []
918 for i in range(16):
919 t = threading.Thread(target=do_fork_and_wait)
920 threads.append(t)
921 t.start()
922
923 for t in threads:
924 t.join()
925
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200926 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
927 def test_clear_threads_states_after_fork(self):
928 # Issue #17094: check that threads states are cleared after fork()
929
930 # start a bunch of threads
931 threads = []
932 for i in range(16):
933 t = threading.Thread(target=lambda : time.sleep(0.3))
934 threads.append(t)
935 t.start()
936
937 pid = os.fork()
938 if pid == 0:
939 # check that threads states have been cleared
940 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200941 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200942 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200943 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200944 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200945 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200946
947 for t in threads:
948 t.join()
949
Jesse Nollera8513972008-07-17 16:49:17 +0000950
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200951class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +0200952 def pipe(self):
953 r, w = os.pipe()
954 self.addCleanup(os.close, r)
955 self.addCleanup(os.close, w)
956 if hasattr(os, 'set_blocking'):
957 os.set_blocking(r, False)
958 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200959
960 def test_threads_join(self):
961 # Non-daemon threads should be joined at subinterpreter shutdown
962 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +0200963 r, w = self.pipe()
964 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200965 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200966 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200967 import threading
968 import time
969
Victor Stinner468e5fe2019-06-13 01:30:17 +0200970 def random_sleep():
971 seconds = random.random() * 0.010
972 time.sleep(seconds)
973
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200974 def f():
975 # Sleep a bit so that the thread is still running when
976 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200977 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200978 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200979
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200980 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200981 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200982 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100983 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200984 self.assertEqual(ret, 0)
985 # The thread was joined properly.
986 self.assertEqual(os.read(r, 1), b"x")
987
Antoine Pitrou7b476992013-09-07 23:38:37 +0200988 def test_threads_join_2(self):
989 # Same as above, but a delay gets introduced after the thread's
990 # Python code returned but before the thread state is deleted.
991 # To achieve this, we register a thread-local object which sleeps
992 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +0200993 r, w = self.pipe()
994 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +0200995 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200996 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +0200997 import threading
998 import time
999
Victor Stinner468e5fe2019-06-13 01:30:17 +02001000 def random_sleep():
1001 seconds = random.random() * 0.010
1002 time.sleep(seconds)
1003
Antoine Pitrou7b476992013-09-07 23:38:37 +02001004 class Sleeper:
1005 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001006 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001007
1008 tls = threading.local()
1009
1010 def f():
1011 # Sleep a bit so that the thread is still running when
1012 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001013 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001014 tls.x = Sleeper()
1015 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001016
Antoine Pitrou7b476992013-09-07 23:38:37 +02001017 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001018 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001019 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001020 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001021 self.assertEqual(ret, 0)
1022 # The thread was joined properly.
1023 self.assertEqual(os.read(r, 1), b"x")
1024
Victor Stinner14d53312020-04-12 23:45:09 +02001025 @cpython_only
1026 def test_daemon_threads_fatal_error(self):
1027 subinterp_code = f"""if 1:
1028 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001029 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001030 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001031
Victor Stinner14d53312020-04-12 23:45:09 +02001032 def f():
1033 # Make sure the daemon thread is still running when
1034 # Py_EndInterpreter is called.
1035 time.sleep({test.support.SHORT_TIMEOUT})
1036 threading.Thread(target=f, daemon=True).start()
1037 """
1038 script = r"""if 1:
1039 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001040
Victor Stinner14d53312020-04-12 23:45:09 +02001041 _testcapi.run_in_subinterp(%r)
1042 """ % (subinterp_code,)
1043 with test.support.SuppressCrashReport():
1044 rc, out, err = assert_python_failure("-c", script)
1045 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1046 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001047
1048
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001049class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001050 # A RuntimeError should be raised if Thread.start() is called
1051 # multiple times.
1052 def test_start_thread_again(self):
1053 thread = threading.Thread()
1054 thread.start()
1055 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001056 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001057
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001058 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001059 current_thread = threading.current_thread()
1060 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001061
1062 def test_joining_inactive_thread(self):
1063 thread = threading.Thread()
1064 self.assertRaises(RuntimeError, thread.join)
1065
1066 def test_daemonize_active_thread(self):
1067 thread = threading.Thread()
1068 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001069 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001070 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001071
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001072 def test_releasing_unacquired_lock(self):
1073 lock = threading.Lock()
1074 self.assertRaises(RuntimeError, lock.release)
1075
Ned Deily9a7c5242011-05-28 00:19:56 -07001076 def test_recursion_limit(self):
1077 # Issue 9670
1078 # test that excessive recursion within a non-main thread causes
1079 # an exception rather than crashing the interpreter on platforms
1080 # like Mac OS X or FreeBSD which have small default stack sizes
1081 # for threads
1082 script = """if True:
1083 import threading
1084
1085 def recurse():
1086 return recurse()
1087
1088 def outer():
1089 try:
1090 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001091 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001092 pass
1093
1094 w = threading.Thread(target=outer)
1095 w.start()
1096 w.join()
1097 print('end of main thread')
1098 """
1099 expected_output = "end of main thread\n"
1100 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001101 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001102 stdout, stderr = p.communicate()
1103 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001104 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001105 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001106
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001107 def test_print_exception(self):
1108 script = r"""if True:
1109 import threading
1110 import time
1111
1112 running = False
1113 def run():
1114 global running
1115 running = True
1116 while running:
1117 time.sleep(0.01)
1118 1/0
1119 t = threading.Thread(target=run)
1120 t.start()
1121 while not running:
1122 time.sleep(0.01)
1123 running = False
1124 t.join()
1125 """
1126 rc, out, err = assert_python_ok("-c", script)
1127 self.assertEqual(out, b'')
1128 err = err.decode()
1129 self.assertIn("Exception in thread", err)
1130 self.assertIn("Traceback (most recent call last):", err)
1131 self.assertIn("ZeroDivisionError", err)
1132 self.assertNotIn("Unhandled exception", err)
1133
1134 def test_print_exception_stderr_is_none_1(self):
1135 script = r"""if True:
1136 import sys
1137 import threading
1138 import time
1139
1140 running = False
1141 def run():
1142 global running
1143 running = True
1144 while running:
1145 time.sleep(0.01)
1146 1/0
1147 t = threading.Thread(target=run)
1148 t.start()
1149 while not running:
1150 time.sleep(0.01)
1151 sys.stderr = None
1152 running = False
1153 t.join()
1154 """
1155 rc, out, err = assert_python_ok("-c", script)
1156 self.assertEqual(out, b'')
1157 err = err.decode()
1158 self.assertIn("Exception in thread", err)
1159 self.assertIn("Traceback (most recent call last):", err)
1160 self.assertIn("ZeroDivisionError", err)
1161 self.assertNotIn("Unhandled exception", err)
1162
1163 def test_print_exception_stderr_is_none_2(self):
1164 script = r"""if True:
1165 import sys
1166 import threading
1167 import time
1168
1169 running = False
1170 def run():
1171 global running
1172 running = True
1173 while running:
1174 time.sleep(0.01)
1175 1/0
1176 sys.stderr = None
1177 t = threading.Thread(target=run)
1178 t.start()
1179 while not running:
1180 time.sleep(0.01)
1181 running = False
1182 t.join()
1183 """
1184 rc, out, err = assert_python_ok("-c", script)
1185 self.assertEqual(out, b'')
1186 self.assertNotIn("Unhandled exception", err.decode())
1187
Victor Stinnereec93312016-08-18 18:13:10 +02001188 def test_bare_raise_in_brand_new_thread(self):
1189 def bare_raise():
1190 raise
1191
1192 class Issue27558(threading.Thread):
1193 exc = None
1194
1195 def run(self):
1196 try:
1197 bare_raise()
1198 except Exception as exc:
1199 self.exc = exc
1200
1201 thread = Issue27558()
1202 thread.start()
1203 thread.join()
1204 self.assertIsNotNone(thread.exc)
1205 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001206 # explicitly break the reference cycle to not leak a dangling thread
1207 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001208
Victor Stinnercd590a72019-05-28 00:39:52 +02001209
1210class ThreadRunFail(threading.Thread):
1211 def run(self):
1212 raise ValueError("run failed")
1213
1214
1215class ExceptHookTests(BaseTestCase):
1216 def test_excepthook(self):
1217 with support.captured_output("stderr") as stderr:
1218 thread = ThreadRunFail(name="excepthook thread")
1219 thread.start()
1220 thread.join()
1221
1222 stderr = stderr.getvalue().strip()
1223 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1224 self.assertIn('Traceback (most recent call last):\n', stderr)
1225 self.assertIn(' raise ValueError("run failed")', stderr)
1226 self.assertIn('ValueError: run failed', stderr)
1227
1228 @support.cpython_only
1229 def test_excepthook_thread_None(self):
1230 # threading.excepthook called with thread=None: log the thread
1231 # identifier in this case.
1232 with support.captured_output("stderr") as stderr:
1233 try:
1234 raise ValueError("bug")
1235 except Exception as exc:
1236 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001237 try:
1238 threading.excepthook(args)
1239 finally:
1240 # Explicitly break a reference cycle
1241 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001242
1243 stderr = stderr.getvalue().strip()
1244 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1245 self.assertIn('Traceback (most recent call last):\n', stderr)
1246 self.assertIn(' raise ValueError("bug")', stderr)
1247 self.assertIn('ValueError: bug', stderr)
1248
1249 def test_system_exit(self):
1250 class ThreadExit(threading.Thread):
1251 def run(self):
1252 sys.exit(1)
1253
1254 # threading.excepthook() silently ignores SystemExit
1255 with support.captured_output("stderr") as stderr:
1256 thread = ThreadExit()
1257 thread.start()
1258 thread.join()
1259
1260 self.assertEqual(stderr.getvalue(), '')
1261
1262 def test_custom_excepthook(self):
1263 args = None
1264
1265 def hook(hook_args):
1266 nonlocal args
1267 args = hook_args
1268
1269 try:
1270 with support.swap_attr(threading, 'excepthook', hook):
1271 thread = ThreadRunFail()
1272 thread.start()
1273 thread.join()
1274
1275 self.assertEqual(args.exc_type, ValueError)
1276 self.assertEqual(str(args.exc_value), 'run failed')
1277 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1278 self.assertIs(args.thread, thread)
1279 finally:
1280 # Break reference cycle
1281 args = None
1282
1283 def test_custom_excepthook_fail(self):
1284 def threading_hook(args):
1285 raise ValueError("threading_hook failed")
1286
1287 err_str = None
1288
1289 def sys_hook(exc_type, exc_value, exc_traceback):
1290 nonlocal err_str
1291 err_str = str(exc_value)
1292
1293 with support.swap_attr(threading, 'excepthook', threading_hook), \
1294 support.swap_attr(sys, 'excepthook', sys_hook), \
1295 support.captured_output('stderr') as stderr:
1296 thread = ThreadRunFail()
1297 thread.start()
1298 thread.join()
1299
1300 self.assertEqual(stderr.getvalue(),
1301 'Exception in threading.excepthook:\n')
1302 self.assertEqual(err_str, 'threading_hook failed')
1303
1304
R David Murray19aeb432013-03-30 17:19:38 -04001305class TimerTests(BaseTestCase):
1306
1307 def setUp(self):
1308 BaseTestCase.setUp(self)
1309 self.callback_args = []
1310 self.callback_event = threading.Event()
1311
1312 def test_init_immutable_default_args(self):
1313 # Issue 17435: constructor defaults were mutable objects, they could be
1314 # mutated via the object attributes and affect other Timer objects.
1315 timer1 = threading.Timer(0.01, self._callback_spy)
1316 timer1.start()
1317 self.callback_event.wait()
1318 timer1.args.append("blah")
1319 timer1.kwargs["foo"] = "bar"
1320 self.callback_event.clear()
1321 timer2 = threading.Timer(0.01, self._callback_spy)
1322 timer2.start()
1323 self.callback_event.wait()
1324 self.assertEqual(len(self.callback_args), 2)
1325 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001326 timer1.join()
1327 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001328
1329 def _callback_spy(self, *args, **kwargs):
1330 self.callback_args.append((args[:], kwargs.copy()))
1331 self.callback_event.set()
1332
Antoine Pitrou557934f2009-11-06 22:41:14 +00001333class LockTests(lock_tests.LockTests):
1334 locktype = staticmethod(threading.Lock)
1335
Antoine Pitrou434736a2009-11-10 18:46:01 +00001336class PyRLockTests(lock_tests.RLockTests):
1337 locktype = staticmethod(threading._PyRLock)
1338
Charles-François Natali6b671b22012-01-28 11:36:04 +01001339@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001340class CRLockTests(lock_tests.RLockTests):
1341 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001342
1343class EventTests(lock_tests.EventTests):
1344 eventtype = staticmethod(threading.Event)
1345
1346class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001347 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001348 locktype = staticmethod(threading.Condition)
1349
1350class ConditionTests(lock_tests.ConditionTests):
1351 condtype = staticmethod(threading.Condition)
1352
1353class SemaphoreTests(lock_tests.SemaphoreTests):
1354 semtype = staticmethod(threading.Semaphore)
1355
1356class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1357 semtype = staticmethod(threading.BoundedSemaphore)
1358
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001359class BarrierTests(lock_tests.BarrierTests):
1360 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001361
Matěj Cepl608876b2019-05-23 22:30:00 +02001362
Martin Panter19e69c52015-11-14 12:46:42 +00001363class MiscTestCase(unittest.TestCase):
1364 def test__all__(self):
1365 extra = {"ThreadError"}
1366 blacklist = {'currentThread', 'activeCount'}
1367 support.check__all__(self, threading, ('threading', '_thread'),
1368 extra=extra, blacklist=blacklist)
1369
Matěj Cepl608876b2019-05-23 22:30:00 +02001370
1371class InterruptMainTests(unittest.TestCase):
1372 def test_interrupt_main_subthread(self):
1373 # Calling start_new_thread with a function that executes interrupt_main
1374 # should raise KeyboardInterrupt upon completion.
1375 def call_interrupt():
1376 _thread.interrupt_main()
1377 t = threading.Thread(target=call_interrupt)
1378 with self.assertRaises(KeyboardInterrupt):
1379 t.start()
1380 t.join()
1381 t.join()
1382
1383 def test_interrupt_main_mainthread(self):
1384 # Make sure that if interrupt_main is called in main thread that
1385 # KeyboardInterrupt is raised instantly.
1386 with self.assertRaises(KeyboardInterrupt):
1387 _thread.interrupt_main()
1388
1389 def test_interrupt_main_noerror(self):
1390 handler = signal.getsignal(signal.SIGINT)
1391 try:
1392 # No exception should arise.
1393 signal.signal(signal.SIGINT, signal.SIG_IGN)
1394 _thread.interrupt_main()
1395
1396 signal.signal(signal.SIGINT, signal.SIG_DFL)
1397 _thread.interrupt_main()
1398 finally:
1399 # Restore original handler
1400 signal.signal(signal.SIGINT, handler)
1401
1402
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001403class AtexitTests(unittest.TestCase):
1404
1405 def test_atexit_output(self):
1406 rc, out, err = assert_python_ok("-c", """if True:
1407 import threading
1408
1409 def run_last():
1410 print('parrot')
1411
1412 threading._register_atexit(run_last)
1413 """)
1414
1415 self.assertFalse(err)
1416 self.assertEqual(out.strip(), b'parrot')
1417
1418 def test_atexit_called_once(self):
1419 rc, out, err = assert_python_ok("-c", """if True:
1420 import threading
1421 from unittest.mock import Mock
1422
1423 mock = Mock()
1424 threading._register_atexit(mock)
1425 mock.assert_not_called()
1426 # force early shutdown to ensure it was called once
1427 threading._shutdown()
1428 mock.assert_called_once()
1429 """)
1430
1431 self.assertFalse(err)
1432
1433 def test_atexit_after_shutdown(self):
1434 # The only way to do this is by registering an atexit within
1435 # an atexit, which is intended to raise an exception.
1436 rc, out, err = assert_python_ok("-c", """if True:
1437 import threading
1438
1439 def func():
1440 pass
1441
1442 def run_last():
1443 threading._register_atexit(func)
1444
1445 threading._register_atexit(run_last)
1446 """)
1447
1448 self.assertTrue(err)
1449 self.assertIn("RuntimeError: can't register atexit after shutdown",
1450 err.decode())
1451
1452
Tim Peters84d54892005-01-08 06:03:17 +00001453if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001454 unittest.main()