blob: 0a4372ec2df39fe9f737c12d27988a60761c0fa0 [file] [log] [blame]
Antoine Pitrou4c8ce842013-09-01 19:51:49 +02001"""
2Tests for the threading module.
3"""
Skip Montanaro4533f602001-08-20 20:28:48 +00004
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005import test.support
Hai Shie80697d2020-05-28 06:10:27 +08006from test.support import threading_helper
Hai Shia7f5d932020-08-04 00:41:24 +08007from test.support import verbose, cpython_only
8from test.support.import_helper import import_module
Berker Peksagce643912015-05-06 06:33:17 +03009from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +020010
Skip Montanaro4533f602001-08-20 20:28:48 +000011import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000012import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020013import _thread
14import threading
Skip Montanaro4533f602001-08-20 20:28:48 +000015import time
Tim Peters84d54892005-01-08 06:03:17 +000016import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000017import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000018import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000019import subprocess
Matěj Cepl608876b2019-05-23 22:30:00 +020020import signal
Victor Stinner066e5b12019-06-14 18:55:22 +020021import textwrap
Skip Montanaro4533f602001-08-20 20:28:48 +000022
Victor Stinner98c16c92020-09-23 23:21:19 +020023from unittest import mock
Antoine Pitrou557934f2009-11-06 22:41:14 +000024from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000025from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000026
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030027
28# Between fork() and exec(), only async-safe functions are allowed (issues
29# #12316 and #11870), and fork() from a worker thread is known to trigger
30# problems with some operating systems (issue #3863): skip problematic tests
31# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010032platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030033
34
Tim Peters84d54892005-01-08 06:03:17 +000035# A trivial mutable counter.
36class Counter(object):
37 def __init__(self):
38 self.value = 0
39 def inc(self):
40 self.value += 1
41 def dec(self):
42 self.value -= 1
43 def get(self):
44 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000045
46class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000047 def __init__(self, name, testcase, sema, mutex, nrunning):
48 threading.Thread.__init__(self, name=name)
49 self.testcase = testcase
50 self.sema = sema
51 self.mutex = mutex
52 self.nrunning = nrunning
53
Skip Montanaro4533f602001-08-20 20:28:48 +000054 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000055 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000056 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000057 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000058 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000059
Christian Heimes4fbc72b2008-03-22 00:47:35 +000060 with self.sema:
61 with self.mutex:
62 self.nrunning.inc()
63 if verbose:
64 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020065 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000066
Christian Heimes4fbc72b2008-03-22 00:47:35 +000067 time.sleep(delay)
68 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000069 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000070
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 with self.mutex:
72 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020073 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000074 if verbose:
75 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000076 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000077
Skip Montanaro4533f602001-08-20 20:28:48 +000078
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000079class BaseTestCase(unittest.TestCase):
80 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080081 self._threads = threading_helper.threading_setup()
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000082
83 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +080084 threading_helper.threading_cleanup(*self._threads)
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000085 test.support.reap_children()
86
87
88class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000089
Victor Stinner98c16c92020-09-23 23:21:19 +020090 @cpython_only
91 def test_name(self):
92 def func(): pass
93
94 thread = threading.Thread(name="myname1")
95 self.assertEqual(thread.name, "myname1")
96
97 # Convert int name to str
98 thread = threading.Thread(name=123)
99 self.assertEqual(thread.name, "123")
100
101 # target name is ignored if name is specified
102 thread = threading.Thread(target=func, name="myname2")
103 self.assertEqual(thread.name, "myname2")
104
105 with mock.patch.object(threading, '_counter', return_value=2):
106 thread = threading.Thread(name="")
107 self.assertEqual(thread.name, "Thread-2")
108
109 with mock.patch.object(threading, '_counter', return_value=3):
110 thread = threading.Thread()
111 self.assertEqual(thread.name, "Thread-3")
112
113 with mock.patch.object(threading, '_counter', return_value=5):
114 thread = threading.Thread(target=func)
115 self.assertEqual(thread.name, "Thread-5 (func)")
116
Tim Peters84d54892005-01-08 06:03:17 +0000117 # Create a bunch of threads, let each do some work, wait until all are
118 # done.
119 def test_various_ops(self):
120 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
121 # times about 1 second per clump).
122 NUMTASKS = 10
123
124 # no more than 3 of the 10 can run at once
125 sema = threading.BoundedSemaphore(value=3)
126 mutex = threading.RLock()
127 numrunning = Counter()
128
129 threads = []
130
131 for i in range(NUMTASKS):
132 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
133 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200134 self.assertIsNone(t.ident)
135 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000136 t.start()
137
Jake Teslerb121f632019-05-22 08:43:17 -0700138 if hasattr(threading, 'get_native_id'):
139 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
140 self.assertNotIn(None, native_ids)
141 self.assertEqual(len(native_ids), NUMTASKS + 1)
142
Tim Peters84d54892005-01-08 06:03:17 +0000143 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000144 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000145 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200146 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200147 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000148 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200149 self.assertIsNotNone(t.ident)
150 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000151 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000152 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000153 self.assertEqual(numrunning.get(), 0)
154
Benjamin Petersond23f8222009-04-05 19:13:16 +0000155 def test_ident_of_no_threading_threads(self):
156 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200157 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000158 def f():
159 ident.append(threading.currentThread().ident)
160 done.set()
161 done = threading.Event()
162 ident = []
Hai Shie80697d2020-05-28 06:10:27 +0800163 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700164 tid = _thread.start_new_thread(f, ())
165 done.wait()
166 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000167 # Kill the "immortal" _DummyThread
168 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000169
Victor Stinner8c663fd2017-11-08 14:44:44 -0800170 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000171 def test_various_ops_small_stack(self):
172 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800173 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000174 try:
175 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000176 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000177 raise unittest.SkipTest(
178 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000179 self.test_various_ops()
180 threading.stack_size(0)
181
Victor Stinner8c663fd2017-11-08 14:44:44 -0800182 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000183 def test_various_ops_large_stack(self):
184 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800185 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000186 try:
187 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000188 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000189 raise unittest.SkipTest(
190 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 self.test_various_ops()
192 threading.stack_size(0)
193
Tim Peters711906e2005-01-08 07:30:42 +0000194 def test_foreign_thread(self):
195 # Check that a "foreign" thread can use the threading module.
196 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000197 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000198 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000199 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000200 mutex.release()
201
202 mutex = threading.Lock()
203 mutex.acquire()
Hai Shie80697d2020-05-28 06:10:27 +0800204 with threading_helper.wait_threads_exit():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700205 tid = _thread.start_new_thread(f, (mutex,))
206 # Wait for the thread to finish.
207 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000208 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000209 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800210 #Issue 29376
211 self.assertTrue(threading._active[tid].is_alive())
212 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000213 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000214
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000215 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
216 # exposed at the Python level. This test relies on ctypes to get at it.
217 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200218 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000219
220 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200221 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000222
223 class AsyncExc(Exception):
224 pass
225
226 exception = ctypes.py_object(AsyncExc)
227
Antoine Pitroube4d8092009-10-18 18:27:17 +0000228 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200229 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200230 self.assertIsInstance(tid, int)
231 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000232
233 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200234 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000235 # The exception is async, so we might have to keep the VM busy until
236 # it notices.
237 while True:
238 pass
239 except AsyncExc:
240 pass
241 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000242 # This code is unreachable but it reflects the intent. If we wanted
243 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000244 self.fail("AsyncExc not raised")
245 try:
246 self.assertEqual(result, 1) # one thread state modified
247 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000248 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000249 pass
250
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000251 # `worker_started` is set by the thread when it's inside a try/except
252 # block waiting to catch the asynchronously set AsyncExc exception.
253 # `worker_saw_exception` is set by the thread upon catching that
254 # exception.
255 worker_started = threading.Event()
256 worker_saw_exception = threading.Event()
257
258 class Worker(threading.Thread):
259 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200260 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000261 self.finished = False
262
263 try:
264 while True:
265 worker_started.set()
266 time.sleep(0.1)
267 except AsyncExc:
268 self.finished = True
269 worker_saw_exception.set()
270
271 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000272 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000273 t.start()
274 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000275 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000276
277 # Try a thread id that doesn't make sense.
278 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000279 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200280 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000281 self.assertEqual(result, 0) # no thread states modified
282
283 # Now raise an exception in the worker thread.
284 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000285 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000286 ret = worker_started.wait()
287 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000288 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000289 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200290 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000291 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000292 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200293 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000294 self.assertEqual(result, 1) # one thread state modified
295 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000296 print(" waiting for worker to say it caught the exception")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100297 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000298 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000299 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000300 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000301 if t.finished:
302 t.join()
303 # else the thread is still running, and we have no way to kill it
304
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000305 def test_limbo_cleanup(self):
306 # Issue 7481: Failure to start thread should cleanup the limbo map.
307 def fail_new_thread(*args):
308 raise threading.ThreadError()
309 _start_new_thread = threading._start_new_thread
310 threading._start_new_thread = fail_new_thread
311 try:
312 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000313 self.assertRaises(threading.ThreadError, t.start)
314 self.assertFalse(
315 t in threading._limbo,
316 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000317 finally:
318 threading._start_new_thread = _start_new_thread
319
Min ho Kimc4cacc82019-07-31 08:16:13 +1000320 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000321 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
322 # very late on python exit: on deallocation of a running thread for
323 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200324 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000325
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200326 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000327 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000328
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000329 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000330 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000331 ready.acquire()
332
Christian Heimes7d2ff882007-11-30 14:35:04 +0000333 # Module globals are cleared before __del__ is run
334 # So we save the functions in class dict
335 class C:
336 ensure = ctypes.pythonapi.PyGILState_Ensure
337 release = ctypes.pythonapi.PyGILState_Release
338 def __del__(self):
339 state = self.ensure()
340 self.release(state)
341
342 def waitingThread():
343 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000344 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000345 time.sleep(100)
346
Georg Brandl2067bfd2008-05-25 13:05:15 +0000347 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000348 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000349 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200350 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000351 self.assertEqual(rc, 42)
352
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000353 def test_finalize_with_trace(self):
354 # Issue1733757
355 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200356 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000357 import sys, threading
358
359 # A deadlock-killer, to prevent the
360 # testsuite to hang forever
361 def killer():
362 import os, time
363 time.sleep(2)
364 print('program blocked; aborting')
365 os._exit(2)
366 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000367 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000368 t.start()
369
370 # This is the trace function
371 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000372 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000373 return func
374
375 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200376 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000377
Antoine Pitrou011bd622009-10-20 21:52:47 +0000378 def test_join_nondaemon_on_shutdown(self):
379 # Issue 1722344
380 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200381 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000382 import threading
383 from time import sleep
384
385 def child():
386 sleep(1)
387 # As a non-daemon thread we SHOULD wake up and nothing
388 # should be torn down yet
389 print("Woke up, sleep function is:", sleep)
390
391 threading.Thread(target=child).start()
392 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200393 """)
394 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000395 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200396 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000397
Christian Heimes1af737c2008-01-23 08:24:23 +0000398 def test_enumerate_after_join(self):
399 # Try hard to trigger #1703448: a thread is still returned in
400 # threading.enumerate() after it has been join()ed.
401 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000402 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000403 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000404 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000405 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000406 t = threading.Thread(target=lambda: None)
407 t.start()
408 t.join()
409 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000410 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000411 "#1703448 triggered after %d trials: %s" % (i, l))
412 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000413 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000414
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000415 def test_no_refcycle_through_target(self):
416 class RunSelfFunction(object):
417 def __init__(self, should_raise):
418 # The links in this refcycle from Thread back to self
419 # should be cleaned up when the thread completes.
420 self.should_raise = should_raise
421 self.thread = threading.Thread(target=self._run,
422 args=(self,),
423 kwargs={'yet_another':self})
424 self.thread.start()
425
426 def _run(self, other_ref, yet_another):
427 if self.should_raise:
428 raise SystemExit
429
430 cyclic_object = RunSelfFunction(should_raise=False)
431 weak_cyclic_object = weakref.ref(cyclic_object)
432 cyclic_object.thread.join()
433 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000434 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000435 msg=('%d references still around' %
436 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000437
438 raising_cyclic_object = RunSelfFunction(should_raise=True)
439 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
440 raising_cyclic_object.thread.join()
441 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000442 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000443 msg=('%d references still around' %
444 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000445
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000446 def test_old_threading_api(self):
447 # Just a quick sanity check to make sure the old method names are
448 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000449 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000450 t.isDaemon()
451 t.setDaemon(True)
452 t.getName()
453 t.setName("name")
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000454 e = threading.Event()
455 e.isSet()
456 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000457
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000458 def test_repr_daemon(self):
459 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200460 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000461 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200462 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000463
luzpaza5293b42017-11-05 07:37:50 -0600464 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000465 t = threading.Thread()
466 self.assertFalse(t.daemon)
467 t = threading.Thread(daemon=False)
468 self.assertFalse(t.daemon)
469 t = threading.Thread(daemon=True)
470 self.assertTrue(t.daemon)
471
Victor Stinner5909a492020-11-16 15:20:34 +0100472 @unittest.skipUnless(hasattr(os, 'fork'), 'needs os.fork()')
473 def test_fork_at_exit(self):
474 # bpo-42350: Calling os.fork() after threading._shutdown() must
475 # not log an error.
476 code = textwrap.dedent("""
477 import atexit
478 import os
479 import sys
480 from test.support import wait_process
481
482 # Import the threading module to register its "at fork" callback
483 import threading
484
485 def exit_handler():
486 pid = os.fork()
487 if not pid:
488 print("child process ok", file=sys.stderr, flush=True)
489 # child process
Victor Stinner5909a492020-11-16 15:20:34 +0100490 else:
491 wait_process(pid, exitcode=0)
492
493 # exit_handler() will be called after threading._shutdown()
494 atexit.register(exit_handler)
495 """)
496 _, out, err = assert_python_ok("-c", code)
497 self.assertEqual(out, b'')
498 self.assertEqual(err.rstrip(), b'child process ok')
499
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200500 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
501 def test_dummy_thread_after_fork(self):
502 # Issue #14308: a dummy thread in the active list doesn't mess up
503 # the after-fork mechanism.
504 code = """if 1:
505 import _thread, threading, os, time
506
507 def background_thread(evt):
508 # Creates and registers the _DummyThread instance
509 threading.current_thread()
510 evt.set()
511 time.sleep(10)
512
513 evt = threading.Event()
514 _thread.start_new_thread(background_thread, (evt,))
515 evt.wait()
516 assert threading.active_count() == 2, threading.active_count()
517 if os.fork() == 0:
518 assert threading.active_count() == 1, threading.active_count()
519 os._exit(0)
520 else:
521 os.wait()
522 """
523 _, out, err = assert_python_ok("-c", code)
524 self.assertEqual(out, b'')
525 self.assertEqual(err, b'')
526
Charles-François Natali9939cc82013-08-30 23:32:53 +0200527 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
528 def test_is_alive_after_fork(self):
529 # Try hard to trigger #18418: is_alive() could sometimes be True on
530 # threads that vanished after a fork.
531 old_interval = sys.getswitchinterval()
532 self.addCleanup(sys.setswitchinterval, old_interval)
533
534 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100535 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200536
537 for i in range(20):
538 t = threading.Thread(target=lambda: None)
539 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200540 pid = os.fork()
541 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700542 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200543 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700544 t.join()
545
Victor Stinnera9f96872020-03-31 21:49:44 +0200546 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200547
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300548 def test_main_thread(self):
549 main = threading.main_thread()
550 self.assertEqual(main.name, 'MainThread')
551 self.assertEqual(main.ident, threading.current_thread().ident)
552 self.assertEqual(main.ident, threading.get_ident())
553
554 def f():
555 self.assertNotEqual(threading.main_thread().ident,
556 threading.current_thread().ident)
557 th = threading.Thread(target=f)
558 th.start()
559 th.join()
560
561 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
562 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
563 def test_main_thread_after_fork(self):
564 code = """if 1:
565 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200566 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300567
568 pid = os.fork()
569 if pid == 0:
570 main = threading.main_thread()
571 print(main.name)
572 print(main.ident == threading.current_thread().ident)
573 print(main.ident == threading.get_ident())
574 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200575 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300576 """
577 _, out, err = assert_python_ok("-c", code)
578 data = out.decode().replace('\r', '')
579 self.assertEqual(err, b"")
580 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
581
582 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
583 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
584 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
585 def test_main_thread_after_fork_from_nonmain_thread(self):
586 code = """if 1:
587 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200588 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300589
Victor Stinner98c16c92020-09-23 23:21:19 +0200590 def func():
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300591 pid = os.fork()
592 if pid == 0:
593 main = threading.main_thread()
594 print(main.name)
595 print(main.ident == threading.current_thread().ident)
596 print(main.ident == threading.get_ident())
597 # stdout is fully buffered because not a tty,
598 # we have to flush before exit.
599 sys.stdout.flush()
600 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200601 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300602
Victor Stinner98c16c92020-09-23 23:21:19 +0200603 th = threading.Thread(target=func)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300604 th.start()
605 th.join()
606 """
607 _, out, err = assert_python_ok("-c", code)
608 data = out.decode().replace('\r', '')
609 self.assertEqual(err, b"")
Victor Stinner98c16c92020-09-23 23:21:19 +0200610 self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300611
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200612 def test_main_thread_during_shutdown(self):
613 # bpo-31516: current_thread() should still point to the main thread
614 # at shutdown
615 code = """if 1:
616 import gc, threading
617
618 main_thread = threading.current_thread()
619 assert main_thread is threading.main_thread() # sanity check
620
621 class RefCycle:
622 def __init__(self):
623 self.cycle = self
624
625 def __del__(self):
626 print("GC:",
627 threading.current_thread() is main_thread,
628 threading.main_thread() is main_thread,
629 threading.enumerate() == [main_thread])
630
631 RefCycle()
632 gc.collect() # sanity check
633 x = RefCycle()
634 """
635 _, out, err = assert_python_ok("-c", code)
636 data = out.decode()
637 self.assertEqual(err, b"")
638 self.assertEqual(data.splitlines(),
639 ["GC: True True True"] * 2)
640
Victor Stinner468e5fe2019-06-13 01:30:17 +0200641 def test_finalization_shutdown(self):
642 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
643 # until Python thread states of all non-daemon threads get deleted.
644 #
645 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
646 # test the finalization of the main interpreter.
647 code = """if 1:
648 import os
649 import threading
650 import time
651 import random
652
653 def random_sleep():
654 seconds = random.random() * 0.010
655 time.sleep(seconds)
656
657 class Sleeper:
658 def __del__(self):
659 random_sleep()
660
661 tls = threading.local()
662
663 def f():
664 # Sleep a bit so that the thread is still running when
665 # Py_Finalize() is called.
666 random_sleep()
667 tls.x = Sleeper()
668 random_sleep()
669
670 threading.Thread(target=f).start()
671 random_sleep()
672 """
673 rc, out, err = assert_python_ok("-c", code)
674 self.assertEqual(err, b"")
675
Antoine Pitrou7b476992013-09-07 23:38:37 +0200676 def test_tstate_lock(self):
677 # Test an implementation detail of Thread objects.
678 started = _thread.allocate_lock()
679 finish = _thread.allocate_lock()
680 started.acquire()
681 finish.acquire()
682 def f():
683 started.release()
684 finish.acquire()
685 time.sleep(0.01)
686 # The tstate lock is None until the thread is started
687 t = threading.Thread(target=f)
688 self.assertIs(t._tstate_lock, None)
689 t.start()
690 started.acquire()
691 self.assertTrue(t.is_alive())
692 # The tstate lock can't be acquired when the thread is running
693 # (or suspended).
694 tstate_lock = t._tstate_lock
695 self.assertFalse(tstate_lock.acquire(timeout=0), False)
696 finish.release()
697 # When the thread ends, the state_lock can be successfully
698 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100699 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200700 # But is_alive() is still True: we hold _tstate_lock now, which
701 # prevents is_alive() from knowing the thread's end-of-life C code
702 # is done.
703 self.assertTrue(t.is_alive())
704 # Let is_alive() find out the C code is done.
705 tstate_lock.release()
706 self.assertFalse(t.is_alive())
707 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200708 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700709 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200710
Tim Peters72460fa2013-09-09 18:48:24 -0500711 def test_repr_stopped(self):
712 # Verify that "stopped" shows up in repr(Thread) appropriately.
713 started = _thread.allocate_lock()
714 finish = _thread.allocate_lock()
715 started.acquire()
716 finish.acquire()
717 def f():
718 started.release()
719 finish.acquire()
720 t = threading.Thread(target=f)
721 t.start()
722 started.acquire()
723 self.assertIn("started", repr(t))
724 finish.release()
725 # "stopped" should appear in the repr in a reasonable amount of time.
726 # Implementation detail: as of this writing, that's trivially true
727 # if .join() is called, and almost trivially true if .is_alive() is
728 # called. The detail we're testing here is that "stopped" shows up
729 # "all on its own".
730 LOOKING_FOR = "stopped"
731 for i in range(500):
732 if LOOKING_FOR in repr(t):
733 break
734 time.sleep(0.01)
735 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700736 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000737
Tim Peters7634e1c2013-10-08 20:55:51 -0500738 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500739 # BoundedSemaphore should raise ValueError if released too often.
740 for limit in range(1, 10):
741 bs = threading.BoundedSemaphore(limit)
742 threads = [threading.Thread(target=bs.acquire)
743 for _ in range(limit)]
744 for t in threads:
745 t.start()
746 for t in threads:
747 t.join()
748 threads = [threading.Thread(target=bs.release)
749 for _ in range(limit)]
750 for t in threads:
751 t.start()
752 for t in threads:
753 t.join()
754 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500755
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200756 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100757 def test_frame_tstate_tracing(self):
758 # Issue #14432: Crash when a generator is created in a C thread that is
759 # destroyed while the generator is still used. The issue was that a
760 # generator contains a frame, and the frame kept a reference to the
761 # Python state of the destroyed C thread. The crash occurs when a trace
762 # function is setup.
763
764 def noop_trace(frame, event, arg):
765 # no operation
766 return noop_trace
767
768 def generator():
769 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300770 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100771
772 def callback():
773 if callback.gen is None:
774 callback.gen = generator()
775 return next(callback.gen)
776 callback.gen = None
777
778 old_trace = sys.gettrace()
779 sys.settrace(noop_trace)
780 try:
781 # Install a trace function
782 threading.settrace(noop_trace)
783
784 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200785 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100786 _testcapi.call_in_temporary_c_thread(callback)
787
788 # Call the generator in a different Python thread, check that the
789 # generator didn't keep a reference to the destroyed thread state
790 for test in range(3):
791 # The trace function is still called here
792 callback()
793 finally:
794 sys.settrace(old_trace)
795
Mario Corchero0001a1b2020-11-04 10:27:43 +0100796 def test_gettrace(self):
797 def noop_trace(frame, event, arg):
798 # no operation
799 return noop_trace
800 old_trace = threading.gettrace()
801 try:
802 threading.settrace(noop_trace)
803 trace_func = threading.gettrace()
804 self.assertEqual(noop_trace,trace_func)
805 finally:
806 threading.settrace(old_trace)
807
808 def test_getprofile(self):
809 def fn(*args): pass
810 old_profile = threading.getprofile()
811 try:
812 threading.setprofile(fn)
813 self.assertEqual(fn, threading.getprofile())
814 finally:
815 threading.setprofile(old_profile)
816
Victor Stinner6f75c872019-06-13 12:06:24 +0200817 @cpython_only
818 def test_shutdown_locks(self):
819 for daemon in (False, True):
820 with self.subTest(daemon=daemon):
821 event = threading.Event()
822 thread = threading.Thread(target=event.wait, daemon=daemon)
823
824 # Thread.start() must add lock to _shutdown_locks,
825 # but only for non-daemon thread
826 thread.start()
827 tstate_lock = thread._tstate_lock
828 if not daemon:
829 self.assertIn(tstate_lock, threading._shutdown_locks)
830 else:
831 self.assertNotIn(tstate_lock, threading._shutdown_locks)
832
833 # unblock the thread and join it
834 event.set()
835 thread.join()
836
837 # Thread._stop() must remove tstate_lock from _shutdown_locks.
838 # Daemon threads must never add it to _shutdown_locks.
839 self.assertNotIn(tstate_lock, threading._shutdown_locks)
840
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100841 def test_locals_at_exit(self):
842 # bpo-19466: thread locals must not be deleted before destructors
843 # are called
844 rc, out, err = assert_python_ok("-c", """if 1:
845 import threading
846
847 class Atexit:
848 def __del__(self):
849 print("thread_dict.atexit = %r" % thread_dict.atexit)
850
851 thread_dict = threading.local()
852 thread_dict.atexit = "value"
853
854 atexit = Atexit()
855 """)
856 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
857
Victor Stinner45956b92013-11-12 16:37:55 +0100858
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000859class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000860
861 def _run_and_join(self, script):
862 script = """if 1:
863 import sys, os, time, threading
864
865 # a thread, which waits for the main program to terminate
866 def joiningfunc(mainthread):
867 mainthread.join()
868 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000869 # stdout is fully buffered because not a tty, we have to flush
870 # before exit.
871 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000872 \n""" + script
873
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200874 rc, out, err = assert_python_ok("-c", script)
875 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000876 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000877
878 def test_1_join_on_shutdown(self):
879 # The usual case: on exit, wait for a non-daemon thread
880 script = """if 1:
881 import os
882 t = threading.Thread(target=joiningfunc,
883 args=(threading.current_thread(),))
884 t.start()
885 time.sleep(0.1)
886 print('end of main')
887 """
888 self._run_and_join(script)
889
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000890 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200891 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000892 def test_2_join_in_forked_process(self):
893 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000894 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200895 from test import support
896
Jesse Nollera8513972008-07-17 16:49:17 +0000897 childpid = os.fork()
898 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200899 # parent process
900 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000901 sys.exit(0)
902
Victor Stinnera9f96872020-03-31 21:49:44 +0200903 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000904 t = threading.Thread(target=joiningfunc,
905 args=(threading.current_thread(),))
906 t.start()
907 print('end of main')
908 """
909 self._run_and_join(script)
910
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000911 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200912 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000913 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000914 # Like the test above, but fork() was called from a worker thread
915 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000916
Jesse Nollera8513972008-07-17 16:49:17 +0000917 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200918 from test import support
919
Jesse Nollera8513972008-07-17 16:49:17 +0000920 main_thread = threading.current_thread()
921 def worker():
922 childpid = os.fork()
923 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200924 # parent process
925 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000926 sys.exit(0)
927
Victor Stinnera9f96872020-03-31 21:49:44 +0200928 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000929 t = threading.Thread(target=joiningfunc,
930 args=(main_thread,))
931 print('end of main')
932 t.start()
933 t.join() # Should not block: main_thread is already stopped
934
935 w = threading.Thread(target=worker)
936 w.start()
937 """
938 self._run_and_join(script)
939
Victor Stinner26d31862011-07-01 14:26:24 +0200940 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500941 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200942 # Check that a daemon thread cannot crash the interpreter on shutdown
943 # by manipulating internal structures that are being disposed of in
944 # the main thread.
945 script = """if True:
946 import os
947 import random
948 import sys
949 import time
950 import threading
951
952 thread_has_run = set()
953
954 def random_io():
955 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200956 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200957 with open(os.__file__, 'rb') as in_f:
958 stuff = in_f.read(200)
959 with open(os.devnull, 'wb') as null_f:
960 null_f.write(stuff)
961 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200962 thread_has_run.add(threading.current_thread())
963
964 def main():
965 count = 0
966 for _ in range(40):
967 new_thread = threading.Thread(target=random_io)
968 new_thread.daemon = True
969 new_thread.start()
970 count += 1
971 while len(thread_has_run) < count:
972 time.sleep(0.001)
973 # Trigger process shutdown
974 sys.exit(0)
975
976 main()
977 """
978 rc, out, err = assert_python_ok('-c', script)
979 self.assertFalse(err)
980
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100981 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100982 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100983 def test_reinit_tls_after_fork(self):
984 # Issue #13817: fork() would deadlock in a multithreaded program with
985 # the ad-hoc TLS implementation.
986
987 def do_fork_and_wait():
988 # just fork a child process and wait it
989 pid = os.fork()
990 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200991 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100992 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200993 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100994
995 # start a bunch of threads that will fork() child processes
996 threads = []
997 for i in range(16):
998 t = threading.Thread(target=do_fork_and_wait)
999 threads.append(t)
1000 t.start()
1001
1002 for t in threads:
1003 t.join()
1004
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001005 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
1006 def test_clear_threads_states_after_fork(self):
1007 # Issue #17094: check that threads states are cleared after fork()
1008
1009 # start a bunch of threads
1010 threads = []
1011 for i in range(16):
1012 t = threading.Thread(target=lambda : time.sleep(0.3))
1013 threads.append(t)
1014 t.start()
1015
1016 pid = os.fork()
1017 if pid == 0:
1018 # check that threads states have been cleared
1019 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +02001020 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001021 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001022 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001023 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001024 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001025
1026 for t in threads:
1027 t.join()
1028
Jesse Nollera8513972008-07-17 16:49:17 +00001029
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001030class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001031 def pipe(self):
1032 r, w = os.pipe()
1033 self.addCleanup(os.close, r)
1034 self.addCleanup(os.close, w)
1035 if hasattr(os, 'set_blocking'):
1036 os.set_blocking(r, False)
1037 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001038
1039 def test_threads_join(self):
1040 # Non-daemon threads should be joined at subinterpreter shutdown
1041 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001042 r, w = self.pipe()
1043 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001044 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001045 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001046 import threading
1047 import time
1048
Victor Stinner468e5fe2019-06-13 01:30:17 +02001049 def random_sleep():
1050 seconds = random.random() * 0.010
1051 time.sleep(seconds)
1052
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001053 def f():
1054 # Sleep a bit so that the thread is still running when
1055 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001056 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001057 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001058
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001059 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001060 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001061 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001062 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001063 self.assertEqual(ret, 0)
1064 # The thread was joined properly.
1065 self.assertEqual(os.read(r, 1), b"x")
1066
Antoine Pitrou7b476992013-09-07 23:38:37 +02001067 def test_threads_join_2(self):
1068 # Same as above, but a delay gets introduced after the thread's
1069 # Python code returned but before the thread state is deleted.
1070 # To achieve this, we register a thread-local object which sleeps
1071 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001072 r, w = self.pipe()
1073 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001074 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001075 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001076 import threading
1077 import time
1078
Victor Stinner468e5fe2019-06-13 01:30:17 +02001079 def random_sleep():
1080 seconds = random.random() * 0.010
1081 time.sleep(seconds)
1082
Antoine Pitrou7b476992013-09-07 23:38:37 +02001083 class Sleeper:
1084 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001085 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001086
1087 tls = threading.local()
1088
1089 def f():
1090 # Sleep a bit so that the thread is still running when
1091 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001092 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001093 tls.x = Sleeper()
1094 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001095
Antoine Pitrou7b476992013-09-07 23:38:37 +02001096 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001097 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001098 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001099 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001100 self.assertEqual(ret, 0)
1101 # The thread was joined properly.
1102 self.assertEqual(os.read(r, 1), b"x")
1103
Victor Stinner14d53312020-04-12 23:45:09 +02001104 @cpython_only
1105 def test_daemon_threads_fatal_error(self):
1106 subinterp_code = f"""if 1:
1107 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001108 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001109 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001110
Victor Stinner14d53312020-04-12 23:45:09 +02001111 def f():
1112 # Make sure the daemon thread is still running when
1113 # Py_EndInterpreter is called.
1114 time.sleep({test.support.SHORT_TIMEOUT})
1115 threading.Thread(target=f, daemon=True).start()
1116 """
1117 script = r"""if 1:
1118 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001119
Victor Stinner14d53312020-04-12 23:45:09 +02001120 _testcapi.run_in_subinterp(%r)
1121 """ % (subinterp_code,)
1122 with test.support.SuppressCrashReport():
1123 rc, out, err = assert_python_failure("-c", script)
1124 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1125 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001126
1127
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001128class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001129 # A RuntimeError should be raised if Thread.start() is called
1130 # multiple times.
1131 def test_start_thread_again(self):
1132 thread = threading.Thread()
1133 thread.start()
1134 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001135 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001136
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001137 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001138 current_thread = threading.current_thread()
1139 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001140
1141 def test_joining_inactive_thread(self):
1142 thread = threading.Thread()
1143 self.assertRaises(RuntimeError, thread.join)
1144
1145 def test_daemonize_active_thread(self):
1146 thread = threading.Thread()
1147 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001148 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001149 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001150
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001151 def test_releasing_unacquired_lock(self):
1152 lock = threading.Lock()
1153 self.assertRaises(RuntimeError, lock.release)
1154
Ned Deily9a7c5242011-05-28 00:19:56 -07001155 def test_recursion_limit(self):
1156 # Issue 9670
1157 # test that excessive recursion within a non-main thread causes
1158 # an exception rather than crashing the interpreter on platforms
1159 # like Mac OS X or FreeBSD which have small default stack sizes
1160 # for threads
1161 script = """if True:
1162 import threading
1163
1164 def recurse():
1165 return recurse()
1166
1167 def outer():
1168 try:
1169 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001170 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001171 pass
1172
1173 w = threading.Thread(target=outer)
1174 w.start()
1175 w.join()
1176 print('end of main thread')
1177 """
1178 expected_output = "end of main thread\n"
1179 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001180 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001181 stdout, stderr = p.communicate()
1182 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001183 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001184 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001185
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001186 def test_print_exception(self):
1187 script = r"""if True:
1188 import threading
1189 import time
1190
1191 running = False
1192 def run():
1193 global running
1194 running = True
1195 while running:
1196 time.sleep(0.01)
1197 1/0
1198 t = threading.Thread(target=run)
1199 t.start()
1200 while not running:
1201 time.sleep(0.01)
1202 running = False
1203 t.join()
1204 """
1205 rc, out, err = assert_python_ok("-c", script)
1206 self.assertEqual(out, b'')
1207 err = err.decode()
1208 self.assertIn("Exception in thread", err)
1209 self.assertIn("Traceback (most recent call last):", err)
1210 self.assertIn("ZeroDivisionError", err)
1211 self.assertNotIn("Unhandled exception", err)
1212
1213 def test_print_exception_stderr_is_none_1(self):
1214 script = r"""if True:
1215 import sys
1216 import threading
1217 import time
1218
1219 running = False
1220 def run():
1221 global running
1222 running = True
1223 while running:
1224 time.sleep(0.01)
1225 1/0
1226 t = threading.Thread(target=run)
1227 t.start()
1228 while not running:
1229 time.sleep(0.01)
1230 sys.stderr = None
1231 running = False
1232 t.join()
1233 """
1234 rc, out, err = assert_python_ok("-c", script)
1235 self.assertEqual(out, b'')
1236 err = err.decode()
1237 self.assertIn("Exception in thread", err)
1238 self.assertIn("Traceback (most recent call last):", err)
1239 self.assertIn("ZeroDivisionError", err)
1240 self.assertNotIn("Unhandled exception", err)
1241
1242 def test_print_exception_stderr_is_none_2(self):
1243 script = r"""if True:
1244 import sys
1245 import threading
1246 import time
1247
1248 running = False
1249 def run():
1250 global running
1251 running = True
1252 while running:
1253 time.sleep(0.01)
1254 1/0
1255 sys.stderr = None
1256 t = threading.Thread(target=run)
1257 t.start()
1258 while not running:
1259 time.sleep(0.01)
1260 running = False
1261 t.join()
1262 """
1263 rc, out, err = assert_python_ok("-c", script)
1264 self.assertEqual(out, b'')
1265 self.assertNotIn("Unhandled exception", err.decode())
1266
Victor Stinnereec93312016-08-18 18:13:10 +02001267 def test_bare_raise_in_brand_new_thread(self):
1268 def bare_raise():
1269 raise
1270
1271 class Issue27558(threading.Thread):
1272 exc = None
1273
1274 def run(self):
1275 try:
1276 bare_raise()
1277 except Exception as exc:
1278 self.exc = exc
1279
1280 thread = Issue27558()
1281 thread.start()
1282 thread.join()
1283 self.assertIsNotNone(thread.exc)
1284 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001285 # explicitly break the reference cycle to not leak a dangling thread
1286 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001287
Victor Stinnercd590a72019-05-28 00:39:52 +02001288
1289class ThreadRunFail(threading.Thread):
1290 def run(self):
1291 raise ValueError("run failed")
1292
1293
1294class ExceptHookTests(BaseTestCase):
1295 def test_excepthook(self):
1296 with support.captured_output("stderr") as stderr:
1297 thread = ThreadRunFail(name="excepthook thread")
1298 thread.start()
1299 thread.join()
1300
1301 stderr = stderr.getvalue().strip()
1302 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1303 self.assertIn('Traceback (most recent call last):\n', stderr)
1304 self.assertIn(' raise ValueError("run failed")', stderr)
1305 self.assertIn('ValueError: run failed', stderr)
1306
1307 @support.cpython_only
1308 def test_excepthook_thread_None(self):
1309 # threading.excepthook called with thread=None: log the thread
1310 # identifier in this case.
1311 with support.captured_output("stderr") as stderr:
1312 try:
1313 raise ValueError("bug")
1314 except Exception as exc:
1315 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001316 try:
1317 threading.excepthook(args)
1318 finally:
1319 # Explicitly break a reference cycle
1320 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001321
1322 stderr = stderr.getvalue().strip()
1323 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1324 self.assertIn('Traceback (most recent call last):\n', stderr)
1325 self.assertIn(' raise ValueError("bug")', stderr)
1326 self.assertIn('ValueError: bug', stderr)
1327
1328 def test_system_exit(self):
1329 class ThreadExit(threading.Thread):
1330 def run(self):
1331 sys.exit(1)
1332
1333 # threading.excepthook() silently ignores SystemExit
1334 with support.captured_output("stderr") as stderr:
1335 thread = ThreadExit()
1336 thread.start()
1337 thread.join()
1338
1339 self.assertEqual(stderr.getvalue(), '')
1340
1341 def test_custom_excepthook(self):
1342 args = None
1343
1344 def hook(hook_args):
1345 nonlocal args
1346 args = hook_args
1347
1348 try:
1349 with support.swap_attr(threading, 'excepthook', hook):
1350 thread = ThreadRunFail()
1351 thread.start()
1352 thread.join()
1353
1354 self.assertEqual(args.exc_type, ValueError)
1355 self.assertEqual(str(args.exc_value), 'run failed')
1356 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1357 self.assertIs(args.thread, thread)
1358 finally:
1359 # Break reference cycle
1360 args = None
1361
1362 def test_custom_excepthook_fail(self):
1363 def threading_hook(args):
1364 raise ValueError("threading_hook failed")
1365
1366 err_str = None
1367
1368 def sys_hook(exc_type, exc_value, exc_traceback):
1369 nonlocal err_str
1370 err_str = str(exc_value)
1371
1372 with support.swap_attr(threading, 'excepthook', threading_hook), \
1373 support.swap_attr(sys, 'excepthook', sys_hook), \
1374 support.captured_output('stderr') as stderr:
1375 thread = ThreadRunFail()
1376 thread.start()
1377 thread.join()
1378
1379 self.assertEqual(stderr.getvalue(),
1380 'Exception in threading.excepthook:\n')
1381 self.assertEqual(err_str, 'threading_hook failed')
1382
Mario Corchero750c5ab2020-11-12 18:27:44 +01001383 def test_original_excepthook(self):
1384 def run_thread():
1385 with support.captured_output("stderr") as output:
1386 thread = ThreadRunFail(name="excepthook thread")
1387 thread.start()
1388 thread.join()
1389 return output.getvalue()
1390
1391 def threading_hook(args):
1392 print("Running a thread failed", file=sys.stderr)
1393
1394 default_output = run_thread()
1395 with support.swap_attr(threading, 'excepthook', threading_hook):
1396 custom_hook_output = run_thread()
1397 threading.excepthook = threading.__excepthook__
1398 recovered_output = run_thread()
1399
1400 self.assertEqual(default_output, recovered_output)
1401 self.assertNotEqual(default_output, custom_hook_output)
1402 self.assertEqual(custom_hook_output, "Running a thread failed\n")
1403
Victor Stinnercd590a72019-05-28 00:39:52 +02001404
R David Murray19aeb432013-03-30 17:19:38 -04001405class TimerTests(BaseTestCase):
1406
1407 def setUp(self):
1408 BaseTestCase.setUp(self)
1409 self.callback_args = []
1410 self.callback_event = threading.Event()
1411
1412 def test_init_immutable_default_args(self):
1413 # Issue 17435: constructor defaults were mutable objects, they could be
1414 # mutated via the object attributes and affect other Timer objects.
1415 timer1 = threading.Timer(0.01, self._callback_spy)
1416 timer1.start()
1417 self.callback_event.wait()
1418 timer1.args.append("blah")
1419 timer1.kwargs["foo"] = "bar"
1420 self.callback_event.clear()
1421 timer2 = threading.Timer(0.01, self._callback_spy)
1422 timer2.start()
1423 self.callback_event.wait()
1424 self.assertEqual(len(self.callback_args), 2)
1425 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001426 timer1.join()
1427 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001428
1429 def _callback_spy(self, *args, **kwargs):
1430 self.callback_args.append((args[:], kwargs.copy()))
1431 self.callback_event.set()
1432
Antoine Pitrou557934f2009-11-06 22:41:14 +00001433class LockTests(lock_tests.LockTests):
1434 locktype = staticmethod(threading.Lock)
1435
Antoine Pitrou434736a2009-11-10 18:46:01 +00001436class PyRLockTests(lock_tests.RLockTests):
1437 locktype = staticmethod(threading._PyRLock)
1438
Charles-François Natali6b671b22012-01-28 11:36:04 +01001439@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001440class CRLockTests(lock_tests.RLockTests):
1441 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001442
1443class EventTests(lock_tests.EventTests):
1444 eventtype = staticmethod(threading.Event)
1445
1446class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001447 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001448 locktype = staticmethod(threading.Condition)
1449
1450class ConditionTests(lock_tests.ConditionTests):
1451 condtype = staticmethod(threading.Condition)
1452
1453class SemaphoreTests(lock_tests.SemaphoreTests):
1454 semtype = staticmethod(threading.Semaphore)
1455
1456class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1457 semtype = staticmethod(threading.BoundedSemaphore)
1458
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001459class BarrierTests(lock_tests.BarrierTests):
1460 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001461
Matěj Cepl608876b2019-05-23 22:30:00 +02001462
Martin Panter19e69c52015-11-14 12:46:42 +00001463class MiscTestCase(unittest.TestCase):
1464 def test__all__(self):
1465 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001466 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001467 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001468 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001469
Matěj Cepl608876b2019-05-23 22:30:00 +02001470
1471class InterruptMainTests(unittest.TestCase):
1472 def test_interrupt_main_subthread(self):
1473 # Calling start_new_thread with a function that executes interrupt_main
1474 # should raise KeyboardInterrupt upon completion.
1475 def call_interrupt():
1476 _thread.interrupt_main()
1477 t = threading.Thread(target=call_interrupt)
1478 with self.assertRaises(KeyboardInterrupt):
1479 t.start()
1480 t.join()
1481 t.join()
1482
1483 def test_interrupt_main_mainthread(self):
1484 # Make sure that if interrupt_main is called in main thread that
1485 # KeyboardInterrupt is raised instantly.
1486 with self.assertRaises(KeyboardInterrupt):
1487 _thread.interrupt_main()
1488
1489 def test_interrupt_main_noerror(self):
1490 handler = signal.getsignal(signal.SIGINT)
1491 try:
1492 # No exception should arise.
1493 signal.signal(signal.SIGINT, signal.SIG_IGN)
1494 _thread.interrupt_main()
1495
1496 signal.signal(signal.SIGINT, signal.SIG_DFL)
1497 _thread.interrupt_main()
1498 finally:
1499 # Restore original handler
1500 signal.signal(signal.SIGINT, handler)
1501
1502
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001503class AtexitTests(unittest.TestCase):
1504
1505 def test_atexit_output(self):
1506 rc, out, err = assert_python_ok("-c", """if True:
1507 import threading
1508
1509 def run_last():
1510 print('parrot')
1511
1512 threading._register_atexit(run_last)
1513 """)
1514
1515 self.assertFalse(err)
1516 self.assertEqual(out.strip(), b'parrot')
1517
1518 def test_atexit_called_once(self):
1519 rc, out, err = assert_python_ok("-c", """if True:
1520 import threading
1521 from unittest.mock import Mock
1522
1523 mock = Mock()
1524 threading._register_atexit(mock)
1525 mock.assert_not_called()
1526 # force early shutdown to ensure it was called once
1527 threading._shutdown()
1528 mock.assert_called_once()
1529 """)
1530
1531 self.assertFalse(err)
1532
1533 def test_atexit_after_shutdown(self):
1534 # The only way to do this is by registering an atexit within
1535 # an atexit, which is intended to raise an exception.
1536 rc, out, err = assert_python_ok("-c", """if True:
1537 import threading
1538
1539 def func():
1540 pass
1541
1542 def run_last():
1543 threading._register_atexit(func)
1544
1545 threading._register_atexit(run_last)
1546 """)
1547
1548 self.assertTrue(err)
1549 self.assertIn("RuntimeError: can't register atexit after shutdown",
1550 err.decode())
1551
1552
Tim Peters84d54892005-01-08 06:03:17 +00001553if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001554 unittest.main()