blob: e0e5406ac26a1e7f56552f804d9880110ee8883b [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
Mario Corchero0001a1b2020-11-04 10:27:43 +0100768 def test_gettrace(self):
769 def noop_trace(frame, event, arg):
770 # no operation
771 return noop_trace
772 old_trace = threading.gettrace()
773 try:
774 threading.settrace(noop_trace)
775 trace_func = threading.gettrace()
776 self.assertEqual(noop_trace,trace_func)
777 finally:
778 threading.settrace(old_trace)
779
780 def test_getprofile(self):
781 def fn(*args): pass
782 old_profile = threading.getprofile()
783 try:
784 threading.setprofile(fn)
785 self.assertEqual(fn, threading.getprofile())
786 finally:
787 threading.setprofile(old_profile)
788
Victor Stinner6f75c872019-06-13 12:06:24 +0200789 @cpython_only
790 def test_shutdown_locks(self):
791 for daemon in (False, True):
792 with self.subTest(daemon=daemon):
793 event = threading.Event()
794 thread = threading.Thread(target=event.wait, daemon=daemon)
795
796 # Thread.start() must add lock to _shutdown_locks,
797 # but only for non-daemon thread
798 thread.start()
799 tstate_lock = thread._tstate_lock
800 if not daemon:
801 self.assertIn(tstate_lock, threading._shutdown_locks)
802 else:
803 self.assertNotIn(tstate_lock, threading._shutdown_locks)
804
805 # unblock the thread and join it
806 event.set()
807 thread.join()
808
809 # Thread._stop() must remove tstate_lock from _shutdown_locks.
810 # Daemon threads must never add it to _shutdown_locks.
811 self.assertNotIn(tstate_lock, threading._shutdown_locks)
812
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100813 def test_locals_at_exit(self):
814 # bpo-19466: thread locals must not be deleted before destructors
815 # are called
816 rc, out, err = assert_python_ok("-c", """if 1:
817 import threading
818
819 class Atexit:
820 def __del__(self):
821 print("thread_dict.atexit = %r" % thread_dict.atexit)
822
823 thread_dict = threading.local()
824 thread_dict.atexit = "value"
825
826 atexit = Atexit()
827 """)
828 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
829
Victor Stinner45956b92013-11-12 16:37:55 +0100830
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000831class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000832
833 def _run_and_join(self, script):
834 script = """if 1:
835 import sys, os, time, threading
836
837 # a thread, which waits for the main program to terminate
838 def joiningfunc(mainthread):
839 mainthread.join()
840 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000841 # stdout is fully buffered because not a tty, we have to flush
842 # before exit.
843 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000844 \n""" + script
845
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200846 rc, out, err = assert_python_ok("-c", script)
847 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000848 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000849
850 def test_1_join_on_shutdown(self):
851 # The usual case: on exit, wait for a non-daemon thread
852 script = """if 1:
853 import os
854 t = threading.Thread(target=joiningfunc,
855 args=(threading.current_thread(),))
856 t.start()
857 time.sleep(0.1)
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")
Jesse Nollera8513972008-07-17 16:49:17 +0000864 def test_2_join_in_forked_process(self):
865 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000866 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200867 from test import support
868
Jesse Nollera8513972008-07-17 16:49:17 +0000869 childpid = os.fork()
870 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200871 # parent process
872 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000873 sys.exit(0)
874
Victor Stinnera9f96872020-03-31 21:49:44 +0200875 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000876 t = threading.Thread(target=joiningfunc,
877 args=(threading.current_thread(),))
878 t.start()
879 print('end of main')
880 """
881 self._run_and_join(script)
882
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000883 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200884 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000885 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000886 # Like the test above, but fork() was called from a worker thread
887 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000888
Jesse Nollera8513972008-07-17 16:49:17 +0000889 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200890 from test import support
891
Jesse Nollera8513972008-07-17 16:49:17 +0000892 main_thread = threading.current_thread()
893 def worker():
894 childpid = os.fork()
895 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200896 # parent process
897 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000898 sys.exit(0)
899
Victor Stinnera9f96872020-03-31 21:49:44 +0200900 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000901 t = threading.Thread(target=joiningfunc,
902 args=(main_thread,))
903 print('end of main')
904 t.start()
905 t.join() # Should not block: main_thread is already stopped
906
907 w = threading.Thread(target=worker)
908 w.start()
909 """
910 self._run_and_join(script)
911
Victor Stinner26d31862011-07-01 14:26:24 +0200912 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500913 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200914 # Check that a daemon thread cannot crash the interpreter on shutdown
915 # by manipulating internal structures that are being disposed of in
916 # the main thread.
917 script = """if True:
918 import os
919 import random
920 import sys
921 import time
922 import threading
923
924 thread_has_run = set()
925
926 def random_io():
927 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200928 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200929 with open(os.__file__, 'rb') as in_f:
930 stuff = in_f.read(200)
931 with open(os.devnull, 'wb') as null_f:
932 null_f.write(stuff)
933 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200934 thread_has_run.add(threading.current_thread())
935
936 def main():
937 count = 0
938 for _ in range(40):
939 new_thread = threading.Thread(target=random_io)
940 new_thread.daemon = True
941 new_thread.start()
942 count += 1
943 while len(thread_has_run) < count:
944 time.sleep(0.001)
945 # Trigger process shutdown
946 sys.exit(0)
947
948 main()
949 """
950 rc, out, err = assert_python_ok('-c', script)
951 self.assertFalse(err)
952
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100953 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100954 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100955 def test_reinit_tls_after_fork(self):
956 # Issue #13817: fork() would deadlock in a multithreaded program with
957 # the ad-hoc TLS implementation.
958
959 def do_fork_and_wait():
960 # just fork a child process and wait it
961 pid = os.fork()
962 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200963 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100964 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200965 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100966
967 # start a bunch of threads that will fork() child processes
968 threads = []
969 for i in range(16):
970 t = threading.Thread(target=do_fork_and_wait)
971 threads.append(t)
972 t.start()
973
974 for t in threads:
975 t.join()
976
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200977 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
978 def test_clear_threads_states_after_fork(self):
979 # Issue #17094: check that threads states are cleared after fork()
980
981 # start a bunch of threads
982 threads = []
983 for i in range(16):
984 t = threading.Thread(target=lambda : time.sleep(0.3))
985 threads.append(t)
986 t.start()
987
988 pid = os.fork()
989 if pid == 0:
990 # check that threads states have been cleared
991 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200992 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200993 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200994 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200995 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200996 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200997
998 for t in threads:
999 t.join()
1000
Jesse Nollera8513972008-07-17 16:49:17 +00001001
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001002class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001003 def pipe(self):
1004 r, w = os.pipe()
1005 self.addCleanup(os.close, r)
1006 self.addCleanup(os.close, w)
1007 if hasattr(os, 'set_blocking'):
1008 os.set_blocking(r, False)
1009 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001010
1011 def test_threads_join(self):
1012 # Non-daemon threads should be joined at subinterpreter shutdown
1013 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001014 r, w = self.pipe()
1015 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001016 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001017 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001018 import threading
1019 import time
1020
Victor Stinner468e5fe2019-06-13 01:30:17 +02001021 def random_sleep():
1022 seconds = random.random() * 0.010
1023 time.sleep(seconds)
1024
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001025 def f():
1026 # Sleep a bit so that the thread is still running when
1027 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001028 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001029 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001030
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001031 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001032 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001033 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001034 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001035 self.assertEqual(ret, 0)
1036 # The thread was joined properly.
1037 self.assertEqual(os.read(r, 1), b"x")
1038
Antoine Pitrou7b476992013-09-07 23:38:37 +02001039 def test_threads_join_2(self):
1040 # Same as above, but a delay gets introduced after the thread's
1041 # Python code returned but before the thread state is deleted.
1042 # To achieve this, we register a thread-local object which sleeps
1043 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001044 r, w = self.pipe()
1045 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001046 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001047 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001048 import threading
1049 import time
1050
Victor Stinner468e5fe2019-06-13 01:30:17 +02001051 def random_sleep():
1052 seconds = random.random() * 0.010
1053 time.sleep(seconds)
1054
Antoine Pitrou7b476992013-09-07 23:38:37 +02001055 class Sleeper:
1056 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001057 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001058
1059 tls = threading.local()
1060
1061 def f():
1062 # Sleep a bit so that the thread is still running when
1063 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001064 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001065 tls.x = Sleeper()
1066 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001067
Antoine Pitrou7b476992013-09-07 23:38:37 +02001068 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001069 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001070 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001071 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001072 self.assertEqual(ret, 0)
1073 # The thread was joined properly.
1074 self.assertEqual(os.read(r, 1), b"x")
1075
Victor Stinner14d53312020-04-12 23:45:09 +02001076 @cpython_only
1077 def test_daemon_threads_fatal_error(self):
1078 subinterp_code = f"""if 1:
1079 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001080 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001081 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001082
Victor Stinner14d53312020-04-12 23:45:09 +02001083 def f():
1084 # Make sure the daemon thread is still running when
1085 # Py_EndInterpreter is called.
1086 time.sleep({test.support.SHORT_TIMEOUT})
1087 threading.Thread(target=f, daemon=True).start()
1088 """
1089 script = r"""if 1:
1090 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001091
Victor Stinner14d53312020-04-12 23:45:09 +02001092 _testcapi.run_in_subinterp(%r)
1093 """ % (subinterp_code,)
1094 with test.support.SuppressCrashReport():
1095 rc, out, err = assert_python_failure("-c", script)
1096 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1097 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001098
1099
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001100class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001101 # A RuntimeError should be raised if Thread.start() is called
1102 # multiple times.
1103 def test_start_thread_again(self):
1104 thread = threading.Thread()
1105 thread.start()
1106 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001107 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001108
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001109 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001110 current_thread = threading.current_thread()
1111 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001112
1113 def test_joining_inactive_thread(self):
1114 thread = threading.Thread()
1115 self.assertRaises(RuntimeError, thread.join)
1116
1117 def test_daemonize_active_thread(self):
1118 thread = threading.Thread()
1119 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001120 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001121 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001122
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001123 def test_releasing_unacquired_lock(self):
1124 lock = threading.Lock()
1125 self.assertRaises(RuntimeError, lock.release)
1126
Ned Deily9a7c5242011-05-28 00:19:56 -07001127 def test_recursion_limit(self):
1128 # Issue 9670
1129 # test that excessive recursion within a non-main thread causes
1130 # an exception rather than crashing the interpreter on platforms
1131 # like Mac OS X or FreeBSD which have small default stack sizes
1132 # for threads
1133 script = """if True:
1134 import threading
1135
1136 def recurse():
1137 return recurse()
1138
1139 def outer():
1140 try:
1141 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001142 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001143 pass
1144
1145 w = threading.Thread(target=outer)
1146 w.start()
1147 w.join()
1148 print('end of main thread')
1149 """
1150 expected_output = "end of main thread\n"
1151 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001152 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001153 stdout, stderr = p.communicate()
1154 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001155 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001156 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001157
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001158 def test_print_exception(self):
1159 script = r"""if True:
1160 import threading
1161 import time
1162
1163 running = False
1164 def run():
1165 global running
1166 running = True
1167 while running:
1168 time.sleep(0.01)
1169 1/0
1170 t = threading.Thread(target=run)
1171 t.start()
1172 while not running:
1173 time.sleep(0.01)
1174 running = False
1175 t.join()
1176 """
1177 rc, out, err = assert_python_ok("-c", script)
1178 self.assertEqual(out, b'')
1179 err = err.decode()
1180 self.assertIn("Exception in thread", err)
1181 self.assertIn("Traceback (most recent call last):", err)
1182 self.assertIn("ZeroDivisionError", err)
1183 self.assertNotIn("Unhandled exception", err)
1184
1185 def test_print_exception_stderr_is_none_1(self):
1186 script = r"""if True:
1187 import sys
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 sys.stderr = None
1203 running = False
1204 t.join()
1205 """
1206 rc, out, err = assert_python_ok("-c", script)
1207 self.assertEqual(out, b'')
1208 err = err.decode()
1209 self.assertIn("Exception in thread", err)
1210 self.assertIn("Traceback (most recent call last):", err)
1211 self.assertIn("ZeroDivisionError", err)
1212 self.assertNotIn("Unhandled exception", err)
1213
1214 def test_print_exception_stderr_is_none_2(self):
1215 script = r"""if True:
1216 import sys
1217 import threading
1218 import time
1219
1220 running = False
1221 def run():
1222 global running
1223 running = True
1224 while running:
1225 time.sleep(0.01)
1226 1/0
1227 sys.stderr = None
1228 t = threading.Thread(target=run)
1229 t.start()
1230 while not running:
1231 time.sleep(0.01)
1232 running = False
1233 t.join()
1234 """
1235 rc, out, err = assert_python_ok("-c", script)
1236 self.assertEqual(out, b'')
1237 self.assertNotIn("Unhandled exception", err.decode())
1238
Victor Stinnereec93312016-08-18 18:13:10 +02001239 def test_bare_raise_in_brand_new_thread(self):
1240 def bare_raise():
1241 raise
1242
1243 class Issue27558(threading.Thread):
1244 exc = None
1245
1246 def run(self):
1247 try:
1248 bare_raise()
1249 except Exception as exc:
1250 self.exc = exc
1251
1252 thread = Issue27558()
1253 thread.start()
1254 thread.join()
1255 self.assertIsNotNone(thread.exc)
1256 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001257 # explicitly break the reference cycle to not leak a dangling thread
1258 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001259
Victor Stinnercd590a72019-05-28 00:39:52 +02001260
1261class ThreadRunFail(threading.Thread):
1262 def run(self):
1263 raise ValueError("run failed")
1264
1265
1266class ExceptHookTests(BaseTestCase):
1267 def test_excepthook(self):
1268 with support.captured_output("stderr") as stderr:
1269 thread = ThreadRunFail(name="excepthook thread")
1270 thread.start()
1271 thread.join()
1272
1273 stderr = stderr.getvalue().strip()
1274 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1275 self.assertIn('Traceback (most recent call last):\n', stderr)
1276 self.assertIn(' raise ValueError("run failed")', stderr)
1277 self.assertIn('ValueError: run failed', stderr)
1278
1279 @support.cpython_only
1280 def test_excepthook_thread_None(self):
1281 # threading.excepthook called with thread=None: log the thread
1282 # identifier in this case.
1283 with support.captured_output("stderr") as stderr:
1284 try:
1285 raise ValueError("bug")
1286 except Exception as exc:
1287 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001288 try:
1289 threading.excepthook(args)
1290 finally:
1291 # Explicitly break a reference cycle
1292 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001293
1294 stderr = stderr.getvalue().strip()
1295 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1296 self.assertIn('Traceback (most recent call last):\n', stderr)
1297 self.assertIn(' raise ValueError("bug")', stderr)
1298 self.assertIn('ValueError: bug', stderr)
1299
1300 def test_system_exit(self):
1301 class ThreadExit(threading.Thread):
1302 def run(self):
1303 sys.exit(1)
1304
1305 # threading.excepthook() silently ignores SystemExit
1306 with support.captured_output("stderr") as stderr:
1307 thread = ThreadExit()
1308 thread.start()
1309 thread.join()
1310
1311 self.assertEqual(stderr.getvalue(), '')
1312
1313 def test_custom_excepthook(self):
1314 args = None
1315
1316 def hook(hook_args):
1317 nonlocal args
1318 args = hook_args
1319
1320 try:
1321 with support.swap_attr(threading, 'excepthook', hook):
1322 thread = ThreadRunFail()
1323 thread.start()
1324 thread.join()
1325
1326 self.assertEqual(args.exc_type, ValueError)
1327 self.assertEqual(str(args.exc_value), 'run failed')
1328 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1329 self.assertIs(args.thread, thread)
1330 finally:
1331 # Break reference cycle
1332 args = None
1333
1334 def test_custom_excepthook_fail(self):
1335 def threading_hook(args):
1336 raise ValueError("threading_hook failed")
1337
1338 err_str = None
1339
1340 def sys_hook(exc_type, exc_value, exc_traceback):
1341 nonlocal err_str
1342 err_str = str(exc_value)
1343
1344 with support.swap_attr(threading, 'excepthook', threading_hook), \
1345 support.swap_attr(sys, 'excepthook', sys_hook), \
1346 support.captured_output('stderr') as stderr:
1347 thread = ThreadRunFail()
1348 thread.start()
1349 thread.join()
1350
1351 self.assertEqual(stderr.getvalue(),
1352 'Exception in threading.excepthook:\n')
1353 self.assertEqual(err_str, 'threading_hook failed')
1354
1355
R David Murray19aeb432013-03-30 17:19:38 -04001356class TimerTests(BaseTestCase):
1357
1358 def setUp(self):
1359 BaseTestCase.setUp(self)
1360 self.callback_args = []
1361 self.callback_event = threading.Event()
1362
1363 def test_init_immutable_default_args(self):
1364 # Issue 17435: constructor defaults were mutable objects, they could be
1365 # mutated via the object attributes and affect other Timer objects.
1366 timer1 = threading.Timer(0.01, self._callback_spy)
1367 timer1.start()
1368 self.callback_event.wait()
1369 timer1.args.append("blah")
1370 timer1.kwargs["foo"] = "bar"
1371 self.callback_event.clear()
1372 timer2 = threading.Timer(0.01, self._callback_spy)
1373 timer2.start()
1374 self.callback_event.wait()
1375 self.assertEqual(len(self.callback_args), 2)
1376 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001377 timer1.join()
1378 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001379
1380 def _callback_spy(self, *args, **kwargs):
1381 self.callback_args.append((args[:], kwargs.copy()))
1382 self.callback_event.set()
1383
Antoine Pitrou557934f2009-11-06 22:41:14 +00001384class LockTests(lock_tests.LockTests):
1385 locktype = staticmethod(threading.Lock)
1386
Antoine Pitrou434736a2009-11-10 18:46:01 +00001387class PyRLockTests(lock_tests.RLockTests):
1388 locktype = staticmethod(threading._PyRLock)
1389
Charles-François Natali6b671b22012-01-28 11:36:04 +01001390@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001391class CRLockTests(lock_tests.RLockTests):
1392 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001393
1394class EventTests(lock_tests.EventTests):
1395 eventtype = staticmethod(threading.Event)
1396
1397class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001398 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001399 locktype = staticmethod(threading.Condition)
1400
1401class ConditionTests(lock_tests.ConditionTests):
1402 condtype = staticmethod(threading.Condition)
1403
1404class SemaphoreTests(lock_tests.SemaphoreTests):
1405 semtype = staticmethod(threading.Semaphore)
1406
1407class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1408 semtype = staticmethod(threading.BoundedSemaphore)
1409
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001410class BarrierTests(lock_tests.BarrierTests):
1411 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001412
Matěj Cepl608876b2019-05-23 22:30:00 +02001413
Martin Panter19e69c52015-11-14 12:46:42 +00001414class MiscTestCase(unittest.TestCase):
1415 def test__all__(self):
1416 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001417 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001418 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001419 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001420
Matěj Cepl608876b2019-05-23 22:30:00 +02001421
1422class InterruptMainTests(unittest.TestCase):
1423 def test_interrupt_main_subthread(self):
1424 # Calling start_new_thread with a function that executes interrupt_main
1425 # should raise KeyboardInterrupt upon completion.
1426 def call_interrupt():
1427 _thread.interrupt_main()
1428 t = threading.Thread(target=call_interrupt)
1429 with self.assertRaises(KeyboardInterrupt):
1430 t.start()
1431 t.join()
1432 t.join()
1433
1434 def test_interrupt_main_mainthread(self):
1435 # Make sure that if interrupt_main is called in main thread that
1436 # KeyboardInterrupt is raised instantly.
1437 with self.assertRaises(KeyboardInterrupt):
1438 _thread.interrupt_main()
1439
1440 def test_interrupt_main_noerror(self):
1441 handler = signal.getsignal(signal.SIGINT)
1442 try:
1443 # No exception should arise.
1444 signal.signal(signal.SIGINT, signal.SIG_IGN)
1445 _thread.interrupt_main()
1446
1447 signal.signal(signal.SIGINT, signal.SIG_DFL)
1448 _thread.interrupt_main()
1449 finally:
1450 # Restore original handler
1451 signal.signal(signal.SIGINT, handler)
1452
1453
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001454class AtexitTests(unittest.TestCase):
1455
1456 def test_atexit_output(self):
1457 rc, out, err = assert_python_ok("-c", """if True:
1458 import threading
1459
1460 def run_last():
1461 print('parrot')
1462
1463 threading._register_atexit(run_last)
1464 """)
1465
1466 self.assertFalse(err)
1467 self.assertEqual(out.strip(), b'parrot')
1468
1469 def test_atexit_called_once(self):
1470 rc, out, err = assert_python_ok("-c", """if True:
1471 import threading
1472 from unittest.mock import Mock
1473
1474 mock = Mock()
1475 threading._register_atexit(mock)
1476 mock.assert_not_called()
1477 # force early shutdown to ensure it was called once
1478 threading._shutdown()
1479 mock.assert_called_once()
1480 """)
1481
1482 self.assertFalse(err)
1483
1484 def test_atexit_after_shutdown(self):
1485 # The only way to do this is by registering an atexit within
1486 # an atexit, which is intended to raise an exception.
1487 rc, out, err = assert_python_ok("-c", """if True:
1488 import threading
1489
1490 def func():
1491 pass
1492
1493 def run_last():
1494 threading._register_atexit(func)
1495
1496 threading._register_atexit(run_last)
1497 """)
1498
1499 self.assertTrue(err)
1500 self.assertIn("RuntimeError: can't register atexit after shutdown",
1501 err.decode())
1502
1503
Tim Peters84d54892005-01-08 06:03:17 +00001504if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001505 unittest.main()