blob: 2f0f3ae0946a579b5e4f0caa974514ffbb3346a3 [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
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200472 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
473 def test_dummy_thread_after_fork(self):
474 # Issue #14308: a dummy thread in the active list doesn't mess up
475 # the after-fork mechanism.
476 code = """if 1:
477 import _thread, threading, os, time
478
479 def background_thread(evt):
480 # Creates and registers the _DummyThread instance
481 threading.current_thread()
482 evt.set()
483 time.sleep(10)
484
485 evt = threading.Event()
486 _thread.start_new_thread(background_thread, (evt,))
487 evt.wait()
488 assert threading.active_count() == 2, threading.active_count()
489 if os.fork() == 0:
490 assert threading.active_count() == 1, threading.active_count()
491 os._exit(0)
492 else:
493 os.wait()
494 """
495 _, out, err = assert_python_ok("-c", code)
496 self.assertEqual(out, b'')
497 self.assertEqual(err, b'')
498
Charles-François Natali9939cc82013-08-30 23:32:53 +0200499 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
500 def test_is_alive_after_fork(self):
501 # Try hard to trigger #18418: is_alive() could sometimes be True on
502 # threads that vanished after a fork.
503 old_interval = sys.getswitchinterval()
504 self.addCleanup(sys.setswitchinterval, old_interval)
505
506 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100507 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200508
509 for i in range(20):
510 t = threading.Thread(target=lambda: None)
511 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200512 pid = os.fork()
513 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700514 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200515 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700516 t.join()
517
Victor Stinnera9f96872020-03-31 21:49:44 +0200518 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200519
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300520 def test_main_thread(self):
521 main = threading.main_thread()
522 self.assertEqual(main.name, 'MainThread')
523 self.assertEqual(main.ident, threading.current_thread().ident)
524 self.assertEqual(main.ident, threading.get_ident())
525
526 def f():
527 self.assertNotEqual(threading.main_thread().ident,
528 threading.current_thread().ident)
529 th = threading.Thread(target=f)
530 th.start()
531 th.join()
532
533 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
534 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
535 def test_main_thread_after_fork(self):
536 code = """if 1:
537 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200538 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300539
540 pid = os.fork()
541 if pid == 0:
542 main = threading.main_thread()
543 print(main.name)
544 print(main.ident == threading.current_thread().ident)
545 print(main.ident == threading.get_ident())
546 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200547 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300548 """
549 _, out, err = assert_python_ok("-c", code)
550 data = out.decode().replace('\r', '')
551 self.assertEqual(err, b"")
552 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
553
554 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
555 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
556 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
557 def test_main_thread_after_fork_from_nonmain_thread(self):
558 code = """if 1:
559 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200560 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300561
Victor Stinner98c16c92020-09-23 23:21:19 +0200562 def func():
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300563 pid = os.fork()
564 if pid == 0:
565 main = threading.main_thread()
566 print(main.name)
567 print(main.ident == threading.current_thread().ident)
568 print(main.ident == threading.get_ident())
569 # stdout is fully buffered because not a tty,
570 # we have to flush before exit.
571 sys.stdout.flush()
572 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200573 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300574
Victor Stinner98c16c92020-09-23 23:21:19 +0200575 th = threading.Thread(target=func)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300576 th.start()
577 th.join()
578 """
579 _, out, err = assert_python_ok("-c", code)
580 data = out.decode().replace('\r', '')
581 self.assertEqual(err, b"")
Victor Stinner98c16c92020-09-23 23:21:19 +0200582 self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300583
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200584 def test_main_thread_during_shutdown(self):
585 # bpo-31516: current_thread() should still point to the main thread
586 # at shutdown
587 code = """if 1:
588 import gc, threading
589
590 main_thread = threading.current_thread()
591 assert main_thread is threading.main_thread() # sanity check
592
593 class RefCycle:
594 def __init__(self):
595 self.cycle = self
596
597 def __del__(self):
598 print("GC:",
599 threading.current_thread() is main_thread,
600 threading.main_thread() is main_thread,
601 threading.enumerate() == [main_thread])
602
603 RefCycle()
604 gc.collect() # sanity check
605 x = RefCycle()
606 """
607 _, out, err = assert_python_ok("-c", code)
608 data = out.decode()
609 self.assertEqual(err, b"")
610 self.assertEqual(data.splitlines(),
611 ["GC: True True True"] * 2)
612
Victor Stinner468e5fe2019-06-13 01:30:17 +0200613 def test_finalization_shutdown(self):
614 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
615 # until Python thread states of all non-daemon threads get deleted.
616 #
617 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
618 # test the finalization of the main interpreter.
619 code = """if 1:
620 import os
621 import threading
622 import time
623 import random
624
625 def random_sleep():
626 seconds = random.random() * 0.010
627 time.sleep(seconds)
628
629 class Sleeper:
630 def __del__(self):
631 random_sleep()
632
633 tls = threading.local()
634
635 def f():
636 # Sleep a bit so that the thread is still running when
637 # Py_Finalize() is called.
638 random_sleep()
639 tls.x = Sleeper()
640 random_sleep()
641
642 threading.Thread(target=f).start()
643 random_sleep()
644 """
645 rc, out, err = assert_python_ok("-c", code)
646 self.assertEqual(err, b"")
647
Antoine Pitrou7b476992013-09-07 23:38:37 +0200648 def test_tstate_lock(self):
649 # Test an implementation detail of Thread objects.
650 started = _thread.allocate_lock()
651 finish = _thread.allocate_lock()
652 started.acquire()
653 finish.acquire()
654 def f():
655 started.release()
656 finish.acquire()
657 time.sleep(0.01)
658 # The tstate lock is None until the thread is started
659 t = threading.Thread(target=f)
660 self.assertIs(t._tstate_lock, None)
661 t.start()
662 started.acquire()
663 self.assertTrue(t.is_alive())
664 # The tstate lock can't be acquired when the thread is running
665 # (or suspended).
666 tstate_lock = t._tstate_lock
667 self.assertFalse(tstate_lock.acquire(timeout=0), False)
668 finish.release()
669 # When the thread ends, the state_lock can be successfully
670 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100671 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200672 # But is_alive() is still True: we hold _tstate_lock now, which
673 # prevents is_alive() from knowing the thread's end-of-life C code
674 # is done.
675 self.assertTrue(t.is_alive())
676 # Let is_alive() find out the C code is done.
677 tstate_lock.release()
678 self.assertFalse(t.is_alive())
679 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200680 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700681 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200682
Tim Peters72460fa2013-09-09 18:48:24 -0500683 def test_repr_stopped(self):
684 # Verify that "stopped" shows up in repr(Thread) appropriately.
685 started = _thread.allocate_lock()
686 finish = _thread.allocate_lock()
687 started.acquire()
688 finish.acquire()
689 def f():
690 started.release()
691 finish.acquire()
692 t = threading.Thread(target=f)
693 t.start()
694 started.acquire()
695 self.assertIn("started", repr(t))
696 finish.release()
697 # "stopped" should appear in the repr in a reasonable amount of time.
698 # Implementation detail: as of this writing, that's trivially true
699 # if .join() is called, and almost trivially true if .is_alive() is
700 # called. The detail we're testing here is that "stopped" shows up
701 # "all on its own".
702 LOOKING_FOR = "stopped"
703 for i in range(500):
704 if LOOKING_FOR in repr(t):
705 break
706 time.sleep(0.01)
707 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700708 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000709
Tim Peters7634e1c2013-10-08 20:55:51 -0500710 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500711 # BoundedSemaphore should raise ValueError if released too often.
712 for limit in range(1, 10):
713 bs = threading.BoundedSemaphore(limit)
714 threads = [threading.Thread(target=bs.acquire)
715 for _ in range(limit)]
716 for t in threads:
717 t.start()
718 for t in threads:
719 t.join()
720 threads = [threading.Thread(target=bs.release)
721 for _ in range(limit)]
722 for t in threads:
723 t.start()
724 for t in threads:
725 t.join()
726 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500727
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200728 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100729 def test_frame_tstate_tracing(self):
730 # Issue #14432: Crash when a generator is created in a C thread that is
731 # destroyed while the generator is still used. The issue was that a
732 # generator contains a frame, and the frame kept a reference to the
733 # Python state of the destroyed C thread. The crash occurs when a trace
734 # function is setup.
735
736 def noop_trace(frame, event, arg):
737 # no operation
738 return noop_trace
739
740 def generator():
741 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300742 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100743
744 def callback():
745 if callback.gen is None:
746 callback.gen = generator()
747 return next(callback.gen)
748 callback.gen = None
749
750 old_trace = sys.gettrace()
751 sys.settrace(noop_trace)
752 try:
753 # Install a trace function
754 threading.settrace(noop_trace)
755
756 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200757 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100758 _testcapi.call_in_temporary_c_thread(callback)
759
760 # Call the generator in a different Python thread, check that the
761 # generator didn't keep a reference to the destroyed thread state
762 for test in range(3):
763 # The trace function is still called here
764 callback()
765 finally:
766 sys.settrace(old_trace)
767
Victor Stinner6f75c872019-06-13 12:06:24 +0200768 @cpython_only
769 def test_shutdown_locks(self):
770 for daemon in (False, True):
771 with self.subTest(daemon=daemon):
772 event = threading.Event()
773 thread = threading.Thread(target=event.wait, daemon=daemon)
774
775 # Thread.start() must add lock to _shutdown_locks,
776 # but only for non-daemon thread
777 thread.start()
778 tstate_lock = thread._tstate_lock
779 if not daemon:
780 self.assertIn(tstate_lock, threading._shutdown_locks)
781 else:
782 self.assertNotIn(tstate_lock, threading._shutdown_locks)
783
784 # unblock the thread and join it
785 event.set()
786 thread.join()
787
788 # Thread._stop() must remove tstate_lock from _shutdown_locks.
789 # Daemon threads must never add it to _shutdown_locks.
790 self.assertNotIn(tstate_lock, threading._shutdown_locks)
791
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100792 def test_locals_at_exit(self):
793 # bpo-19466: thread locals must not be deleted before destructors
794 # are called
795 rc, out, err = assert_python_ok("-c", """if 1:
796 import threading
797
798 class Atexit:
799 def __del__(self):
800 print("thread_dict.atexit = %r" % thread_dict.atexit)
801
802 thread_dict = threading.local()
803 thread_dict.atexit = "value"
804
805 atexit = Atexit()
806 """)
807 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
808
Victor Stinner45956b92013-11-12 16:37:55 +0100809
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000810class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000811
812 def _run_and_join(self, script):
813 script = """if 1:
814 import sys, os, time, threading
815
816 # a thread, which waits for the main program to terminate
817 def joiningfunc(mainthread):
818 mainthread.join()
819 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000820 # stdout is fully buffered because not a tty, we have to flush
821 # before exit.
822 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000823 \n""" + script
824
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200825 rc, out, err = assert_python_ok("-c", script)
826 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000827 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000828
829 def test_1_join_on_shutdown(self):
830 # The usual case: on exit, wait for a non-daemon thread
831 script = """if 1:
832 import os
833 t = threading.Thread(target=joiningfunc,
834 args=(threading.current_thread(),))
835 t.start()
836 time.sleep(0.1)
837 print('end of main')
838 """
839 self._run_and_join(script)
840
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000841 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200842 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000843 def test_2_join_in_forked_process(self):
844 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000845 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200846 from test import support
847
Jesse Nollera8513972008-07-17 16:49:17 +0000848 childpid = os.fork()
849 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200850 # parent process
851 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000852 sys.exit(0)
853
Victor Stinnera9f96872020-03-31 21:49:44 +0200854 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000855 t = threading.Thread(target=joiningfunc,
856 args=(threading.current_thread(),))
857 t.start()
858 print('end of main')
859 """
860 self._run_and_join(script)
861
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000862 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200863 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000864 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000865 # Like the test above, but fork() was called from a worker thread
866 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000867
Jesse Nollera8513972008-07-17 16:49:17 +0000868 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200869 from test import support
870
Jesse Nollera8513972008-07-17 16:49:17 +0000871 main_thread = threading.current_thread()
872 def worker():
873 childpid = os.fork()
874 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200875 # parent process
876 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000877 sys.exit(0)
878
Victor Stinnera9f96872020-03-31 21:49:44 +0200879 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000880 t = threading.Thread(target=joiningfunc,
881 args=(main_thread,))
882 print('end of main')
883 t.start()
884 t.join() # Should not block: main_thread is already stopped
885
886 w = threading.Thread(target=worker)
887 w.start()
888 """
889 self._run_and_join(script)
890
Victor Stinner26d31862011-07-01 14:26:24 +0200891 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500892 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200893 # Check that a daemon thread cannot crash the interpreter on shutdown
894 # by manipulating internal structures that are being disposed of in
895 # the main thread.
896 script = """if True:
897 import os
898 import random
899 import sys
900 import time
901 import threading
902
903 thread_has_run = set()
904
905 def random_io():
906 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200907 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200908 with open(os.__file__, 'rb') as in_f:
909 stuff = in_f.read(200)
910 with open(os.devnull, 'wb') as null_f:
911 null_f.write(stuff)
912 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200913 thread_has_run.add(threading.current_thread())
914
915 def main():
916 count = 0
917 for _ in range(40):
918 new_thread = threading.Thread(target=random_io)
919 new_thread.daemon = True
920 new_thread.start()
921 count += 1
922 while len(thread_has_run) < count:
923 time.sleep(0.001)
924 # Trigger process shutdown
925 sys.exit(0)
926
927 main()
928 """
929 rc, out, err = assert_python_ok('-c', script)
930 self.assertFalse(err)
931
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100932 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100933 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100934 def test_reinit_tls_after_fork(self):
935 # Issue #13817: fork() would deadlock in a multithreaded program with
936 # the ad-hoc TLS implementation.
937
938 def do_fork_and_wait():
939 # just fork a child process and wait it
940 pid = os.fork()
941 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200942 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100943 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200944 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100945
946 # start a bunch of threads that will fork() child processes
947 threads = []
948 for i in range(16):
949 t = threading.Thread(target=do_fork_and_wait)
950 threads.append(t)
951 t.start()
952
953 for t in threads:
954 t.join()
955
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200956 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
957 def test_clear_threads_states_after_fork(self):
958 # Issue #17094: check that threads states are cleared after fork()
959
960 # start a bunch of threads
961 threads = []
962 for i in range(16):
963 t = threading.Thread(target=lambda : time.sleep(0.3))
964 threads.append(t)
965 t.start()
966
967 pid = os.fork()
968 if pid == 0:
969 # check that threads states have been cleared
970 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200971 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200972 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200973 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200974 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200975 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200976
977 for t in threads:
978 t.join()
979
Jesse Nollera8513972008-07-17 16:49:17 +0000980
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200981class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +0200982 def pipe(self):
983 r, w = os.pipe()
984 self.addCleanup(os.close, r)
985 self.addCleanup(os.close, w)
986 if hasattr(os, 'set_blocking'):
987 os.set_blocking(r, False)
988 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200989
990 def test_threads_join(self):
991 # Non-daemon threads should be joined at subinterpreter shutdown
992 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +0200993 r, w = self.pipe()
994 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200995 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200996 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +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 Pitrou7eaf3f72013-08-25 19:48:18 +02001004 def f():
1005 # Sleep a bit so that the thread is still running when
1006 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001007 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001008 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001009
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001010 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001011 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001012 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001013 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001014 self.assertEqual(ret, 0)
1015 # The thread was joined properly.
1016 self.assertEqual(os.read(r, 1), b"x")
1017
Antoine Pitrou7b476992013-09-07 23:38:37 +02001018 def test_threads_join_2(self):
1019 # Same as above, but a delay gets introduced after the thread's
1020 # Python code returned but before the thread state is deleted.
1021 # To achieve this, we register a thread-local object which sleeps
1022 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001023 r, w = self.pipe()
1024 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001025 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001026 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001027 import threading
1028 import time
1029
Victor Stinner468e5fe2019-06-13 01:30:17 +02001030 def random_sleep():
1031 seconds = random.random() * 0.010
1032 time.sleep(seconds)
1033
Antoine Pitrou7b476992013-09-07 23:38:37 +02001034 class Sleeper:
1035 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001036 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001037
1038 tls = threading.local()
1039
1040 def f():
1041 # Sleep a bit so that the thread is still running when
1042 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001043 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001044 tls.x = Sleeper()
1045 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001046
Antoine Pitrou7b476992013-09-07 23:38:37 +02001047 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001048 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001049 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001050 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001051 self.assertEqual(ret, 0)
1052 # The thread was joined properly.
1053 self.assertEqual(os.read(r, 1), b"x")
1054
Victor Stinner14d53312020-04-12 23:45:09 +02001055 @cpython_only
1056 def test_daemon_threads_fatal_error(self):
1057 subinterp_code = f"""if 1:
1058 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001059 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001060 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001061
Victor Stinner14d53312020-04-12 23:45:09 +02001062 def f():
1063 # Make sure the daemon thread is still running when
1064 # Py_EndInterpreter is called.
1065 time.sleep({test.support.SHORT_TIMEOUT})
1066 threading.Thread(target=f, daemon=True).start()
1067 """
1068 script = r"""if 1:
1069 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001070
Victor Stinner14d53312020-04-12 23:45:09 +02001071 _testcapi.run_in_subinterp(%r)
1072 """ % (subinterp_code,)
1073 with test.support.SuppressCrashReport():
1074 rc, out, err = assert_python_failure("-c", script)
1075 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1076 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001077
1078
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001079class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001080 # A RuntimeError should be raised if Thread.start() is called
1081 # multiple times.
1082 def test_start_thread_again(self):
1083 thread = threading.Thread()
1084 thread.start()
1085 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001086 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001087
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001088 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001089 current_thread = threading.current_thread()
1090 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001091
1092 def test_joining_inactive_thread(self):
1093 thread = threading.Thread()
1094 self.assertRaises(RuntimeError, thread.join)
1095
1096 def test_daemonize_active_thread(self):
1097 thread = threading.Thread()
1098 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001099 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001100 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001101
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001102 def test_releasing_unacquired_lock(self):
1103 lock = threading.Lock()
1104 self.assertRaises(RuntimeError, lock.release)
1105
Ned Deily9a7c5242011-05-28 00:19:56 -07001106 def test_recursion_limit(self):
1107 # Issue 9670
1108 # test that excessive recursion within a non-main thread causes
1109 # an exception rather than crashing the interpreter on platforms
1110 # like Mac OS X or FreeBSD which have small default stack sizes
1111 # for threads
1112 script = """if True:
1113 import threading
1114
1115 def recurse():
1116 return recurse()
1117
1118 def outer():
1119 try:
1120 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001121 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001122 pass
1123
1124 w = threading.Thread(target=outer)
1125 w.start()
1126 w.join()
1127 print('end of main thread')
1128 """
1129 expected_output = "end of main thread\n"
1130 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001131 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001132 stdout, stderr = p.communicate()
1133 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001134 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001135 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001136
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001137 def test_print_exception(self):
1138 script = r"""if True:
1139 import threading
1140 import time
1141
1142 running = False
1143 def run():
1144 global running
1145 running = True
1146 while running:
1147 time.sleep(0.01)
1148 1/0
1149 t = threading.Thread(target=run)
1150 t.start()
1151 while not running:
1152 time.sleep(0.01)
1153 running = False
1154 t.join()
1155 """
1156 rc, out, err = assert_python_ok("-c", script)
1157 self.assertEqual(out, b'')
1158 err = err.decode()
1159 self.assertIn("Exception in thread", err)
1160 self.assertIn("Traceback (most recent call last):", err)
1161 self.assertIn("ZeroDivisionError", err)
1162 self.assertNotIn("Unhandled exception", err)
1163
1164 def test_print_exception_stderr_is_none_1(self):
1165 script = r"""if True:
1166 import sys
1167 import threading
1168 import time
1169
1170 running = False
1171 def run():
1172 global running
1173 running = True
1174 while running:
1175 time.sleep(0.01)
1176 1/0
1177 t = threading.Thread(target=run)
1178 t.start()
1179 while not running:
1180 time.sleep(0.01)
1181 sys.stderr = None
1182 running = False
1183 t.join()
1184 """
1185 rc, out, err = assert_python_ok("-c", script)
1186 self.assertEqual(out, b'')
1187 err = err.decode()
1188 self.assertIn("Exception in thread", err)
1189 self.assertIn("Traceback (most recent call last):", err)
1190 self.assertIn("ZeroDivisionError", err)
1191 self.assertNotIn("Unhandled exception", err)
1192
1193 def test_print_exception_stderr_is_none_2(self):
1194 script = r"""if True:
1195 import sys
1196 import threading
1197 import time
1198
1199 running = False
1200 def run():
1201 global running
1202 running = True
1203 while running:
1204 time.sleep(0.01)
1205 1/0
1206 sys.stderr = None
1207 t = threading.Thread(target=run)
1208 t.start()
1209 while not running:
1210 time.sleep(0.01)
1211 running = False
1212 t.join()
1213 """
1214 rc, out, err = assert_python_ok("-c", script)
1215 self.assertEqual(out, b'')
1216 self.assertNotIn("Unhandled exception", err.decode())
1217
Victor Stinnereec93312016-08-18 18:13:10 +02001218 def test_bare_raise_in_brand_new_thread(self):
1219 def bare_raise():
1220 raise
1221
1222 class Issue27558(threading.Thread):
1223 exc = None
1224
1225 def run(self):
1226 try:
1227 bare_raise()
1228 except Exception as exc:
1229 self.exc = exc
1230
1231 thread = Issue27558()
1232 thread.start()
1233 thread.join()
1234 self.assertIsNotNone(thread.exc)
1235 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001236 # explicitly break the reference cycle to not leak a dangling thread
1237 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001238
Victor Stinnercd590a72019-05-28 00:39:52 +02001239
1240class ThreadRunFail(threading.Thread):
1241 def run(self):
1242 raise ValueError("run failed")
1243
1244
1245class ExceptHookTests(BaseTestCase):
1246 def test_excepthook(self):
1247 with support.captured_output("stderr") as stderr:
1248 thread = ThreadRunFail(name="excepthook thread")
1249 thread.start()
1250 thread.join()
1251
1252 stderr = stderr.getvalue().strip()
1253 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1254 self.assertIn('Traceback (most recent call last):\n', stderr)
1255 self.assertIn(' raise ValueError("run failed")', stderr)
1256 self.assertIn('ValueError: run failed', stderr)
1257
1258 @support.cpython_only
1259 def test_excepthook_thread_None(self):
1260 # threading.excepthook called with thread=None: log the thread
1261 # identifier in this case.
1262 with support.captured_output("stderr") as stderr:
1263 try:
1264 raise ValueError("bug")
1265 except Exception as exc:
1266 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001267 try:
1268 threading.excepthook(args)
1269 finally:
1270 # Explicitly break a reference cycle
1271 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001272
1273 stderr = stderr.getvalue().strip()
1274 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1275 self.assertIn('Traceback (most recent call last):\n', stderr)
1276 self.assertIn(' raise ValueError("bug")', stderr)
1277 self.assertIn('ValueError: bug', stderr)
1278
1279 def test_system_exit(self):
1280 class ThreadExit(threading.Thread):
1281 def run(self):
1282 sys.exit(1)
1283
1284 # threading.excepthook() silently ignores SystemExit
1285 with support.captured_output("stderr") as stderr:
1286 thread = ThreadExit()
1287 thread.start()
1288 thread.join()
1289
1290 self.assertEqual(stderr.getvalue(), '')
1291
1292 def test_custom_excepthook(self):
1293 args = None
1294
1295 def hook(hook_args):
1296 nonlocal args
1297 args = hook_args
1298
1299 try:
1300 with support.swap_attr(threading, 'excepthook', hook):
1301 thread = ThreadRunFail()
1302 thread.start()
1303 thread.join()
1304
1305 self.assertEqual(args.exc_type, ValueError)
1306 self.assertEqual(str(args.exc_value), 'run failed')
1307 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1308 self.assertIs(args.thread, thread)
1309 finally:
1310 # Break reference cycle
1311 args = None
1312
1313 def test_custom_excepthook_fail(self):
1314 def threading_hook(args):
1315 raise ValueError("threading_hook failed")
1316
1317 err_str = None
1318
1319 def sys_hook(exc_type, exc_value, exc_traceback):
1320 nonlocal err_str
1321 err_str = str(exc_value)
1322
1323 with support.swap_attr(threading, 'excepthook', threading_hook), \
1324 support.swap_attr(sys, 'excepthook', sys_hook), \
1325 support.captured_output('stderr') as stderr:
1326 thread = ThreadRunFail()
1327 thread.start()
1328 thread.join()
1329
1330 self.assertEqual(stderr.getvalue(),
1331 'Exception in threading.excepthook:\n')
1332 self.assertEqual(err_str, 'threading_hook failed')
1333
1334
R David Murray19aeb432013-03-30 17:19:38 -04001335class TimerTests(BaseTestCase):
1336
1337 def setUp(self):
1338 BaseTestCase.setUp(self)
1339 self.callback_args = []
1340 self.callback_event = threading.Event()
1341
1342 def test_init_immutable_default_args(self):
1343 # Issue 17435: constructor defaults were mutable objects, they could be
1344 # mutated via the object attributes and affect other Timer objects.
1345 timer1 = threading.Timer(0.01, self._callback_spy)
1346 timer1.start()
1347 self.callback_event.wait()
1348 timer1.args.append("blah")
1349 timer1.kwargs["foo"] = "bar"
1350 self.callback_event.clear()
1351 timer2 = threading.Timer(0.01, self._callback_spy)
1352 timer2.start()
1353 self.callback_event.wait()
1354 self.assertEqual(len(self.callback_args), 2)
1355 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001356 timer1.join()
1357 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001358
1359 def _callback_spy(self, *args, **kwargs):
1360 self.callback_args.append((args[:], kwargs.copy()))
1361 self.callback_event.set()
1362
Antoine Pitrou557934f2009-11-06 22:41:14 +00001363class LockTests(lock_tests.LockTests):
1364 locktype = staticmethod(threading.Lock)
1365
Antoine Pitrou434736a2009-11-10 18:46:01 +00001366class PyRLockTests(lock_tests.RLockTests):
1367 locktype = staticmethod(threading._PyRLock)
1368
Charles-François Natali6b671b22012-01-28 11:36:04 +01001369@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001370class CRLockTests(lock_tests.RLockTests):
1371 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001372
1373class EventTests(lock_tests.EventTests):
1374 eventtype = staticmethod(threading.Event)
1375
1376class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001377 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001378 locktype = staticmethod(threading.Condition)
1379
1380class ConditionTests(lock_tests.ConditionTests):
1381 condtype = staticmethod(threading.Condition)
1382
1383class SemaphoreTests(lock_tests.SemaphoreTests):
1384 semtype = staticmethod(threading.Semaphore)
1385
1386class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1387 semtype = staticmethod(threading.BoundedSemaphore)
1388
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001389class BarrierTests(lock_tests.BarrierTests):
1390 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001391
Matěj Cepl608876b2019-05-23 22:30:00 +02001392
Martin Panter19e69c52015-11-14 12:46:42 +00001393class MiscTestCase(unittest.TestCase):
1394 def test__all__(self):
1395 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001396 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001397 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001398 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001399
Matěj Cepl608876b2019-05-23 22:30:00 +02001400
1401class InterruptMainTests(unittest.TestCase):
1402 def test_interrupt_main_subthread(self):
1403 # Calling start_new_thread with a function that executes interrupt_main
1404 # should raise KeyboardInterrupt upon completion.
1405 def call_interrupt():
1406 _thread.interrupt_main()
1407 t = threading.Thread(target=call_interrupt)
1408 with self.assertRaises(KeyboardInterrupt):
1409 t.start()
1410 t.join()
1411 t.join()
1412
1413 def test_interrupt_main_mainthread(self):
1414 # Make sure that if interrupt_main is called in main thread that
1415 # KeyboardInterrupt is raised instantly.
1416 with self.assertRaises(KeyboardInterrupt):
1417 _thread.interrupt_main()
1418
1419 def test_interrupt_main_noerror(self):
1420 handler = signal.getsignal(signal.SIGINT)
1421 try:
1422 # No exception should arise.
1423 signal.signal(signal.SIGINT, signal.SIG_IGN)
1424 _thread.interrupt_main()
1425
1426 signal.signal(signal.SIGINT, signal.SIG_DFL)
1427 _thread.interrupt_main()
1428 finally:
1429 # Restore original handler
1430 signal.signal(signal.SIGINT, handler)
1431
1432
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001433class AtexitTests(unittest.TestCase):
1434
1435 def test_atexit_output(self):
1436 rc, out, err = assert_python_ok("-c", """if True:
1437 import threading
1438
1439 def run_last():
1440 print('parrot')
1441
1442 threading._register_atexit(run_last)
1443 """)
1444
1445 self.assertFalse(err)
1446 self.assertEqual(out.strip(), b'parrot')
1447
1448 def test_atexit_called_once(self):
1449 rc, out, err = assert_python_ok("-c", """if True:
1450 import threading
1451 from unittest.mock import Mock
1452
1453 mock = Mock()
1454 threading._register_atexit(mock)
1455 mock.assert_not_called()
1456 # force early shutdown to ensure it was called once
1457 threading._shutdown()
1458 mock.assert_called_once()
1459 """)
1460
1461 self.assertFalse(err)
1462
1463 def test_atexit_after_shutdown(self):
1464 # The only way to do this is by registering an atexit within
1465 # an atexit, which is intended to raise an exception.
1466 rc, out, err = assert_python_ok("-c", """if True:
1467 import threading
1468
1469 def func():
1470 pass
1471
1472 def run_last():
1473 threading._register_atexit(func)
1474
1475 threading._register_atexit(run_last)
1476 """)
1477
1478 self.assertTrue(err)
1479 self.assertIn("RuntimeError: can't register atexit after shutdown",
1480 err.decode())
1481
1482
Tim Peters84d54892005-01-08 06:03:17 +00001483if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001484 unittest.main()