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