blob: 49a4af8365afced36bdc7b175b6eedc4aee44adb [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.
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700157 self.assertIsNotNone(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000158 def f():
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700159 ident.append(threading.current_thread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000160 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()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700450 with self.assertWarnsRegex(DeprecationWarning,
451 r'get the daemon attribute'):
452 t.isDaemon()
453 with self.assertWarnsRegex(DeprecationWarning,
454 r'set the daemon attribute'):
455 t.setDaemon(True)
456 with self.assertWarnsRegex(DeprecationWarning,
457 r'get the name attribute'):
458 t.getName()
459 with self.assertWarnsRegex(DeprecationWarning,
460 r'set the name attribute'):
461 t.setName("name")
462
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000463 e = threading.Event()
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -0700464 with self.assertWarnsRegex(DeprecationWarning, 'use is_set()'):
465 e.isSet()
466
467 cond = threading.Condition()
468 cond.acquire()
469 with self.assertWarnsRegex(DeprecationWarning, 'use notify_all()'):
470 cond.notifyAll()
471
472 with self.assertWarnsRegex(DeprecationWarning, 'use active_count()'):
473 threading.activeCount()
474 with self.assertWarnsRegex(DeprecationWarning, 'use current_thread()'):
475 threading.currentThread()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000476
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000477 def test_repr_daemon(self):
478 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200479 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000480 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200481 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000482
luzpaza5293b42017-11-05 07:37:50 -0600483 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000484 t = threading.Thread()
485 self.assertFalse(t.daemon)
486 t = threading.Thread(daemon=False)
487 self.assertFalse(t.daemon)
488 t = threading.Thread(daemon=True)
489 self.assertTrue(t.daemon)
490
Victor Stinner5909a492020-11-16 15:20:34 +0100491 @unittest.skipUnless(hasattr(os, 'fork'), 'needs os.fork()')
492 def test_fork_at_exit(self):
493 # bpo-42350: Calling os.fork() after threading._shutdown() must
494 # not log an error.
495 code = textwrap.dedent("""
496 import atexit
497 import os
498 import sys
499 from test.support import wait_process
500
501 # Import the threading module to register its "at fork" callback
502 import threading
503
504 def exit_handler():
505 pid = os.fork()
506 if not pid:
507 print("child process ok", file=sys.stderr, flush=True)
508 # child process
Victor Stinner5909a492020-11-16 15:20:34 +0100509 else:
510 wait_process(pid, exitcode=0)
511
512 # exit_handler() will be called after threading._shutdown()
513 atexit.register(exit_handler)
514 """)
515 _, out, err = assert_python_ok("-c", code)
516 self.assertEqual(out, b'')
517 self.assertEqual(err.rstrip(), b'child process ok')
518
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200519 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
520 def test_dummy_thread_after_fork(self):
521 # Issue #14308: a dummy thread in the active list doesn't mess up
522 # the after-fork mechanism.
523 code = """if 1:
524 import _thread, threading, os, time
525
526 def background_thread(evt):
527 # Creates and registers the _DummyThread instance
528 threading.current_thread()
529 evt.set()
530 time.sleep(10)
531
532 evt = threading.Event()
533 _thread.start_new_thread(background_thread, (evt,))
534 evt.wait()
535 assert threading.active_count() == 2, threading.active_count()
536 if os.fork() == 0:
537 assert threading.active_count() == 1, threading.active_count()
538 os._exit(0)
539 else:
540 os.wait()
541 """
542 _, out, err = assert_python_ok("-c", code)
543 self.assertEqual(out, b'')
544 self.assertEqual(err, b'')
545
Charles-François Natali9939cc82013-08-30 23:32:53 +0200546 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
547 def test_is_alive_after_fork(self):
548 # Try hard to trigger #18418: is_alive() could sometimes be True on
549 # threads that vanished after a fork.
550 old_interval = sys.getswitchinterval()
551 self.addCleanup(sys.setswitchinterval, old_interval)
552
553 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100554 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200555
556 for i in range(20):
557 t = threading.Thread(target=lambda: None)
558 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200559 pid = os.fork()
560 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700561 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200562 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700563 t.join()
564
Victor Stinnera9f96872020-03-31 21:49:44 +0200565 support.wait_process(pid, exitcode=10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200566
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300567 def test_main_thread(self):
568 main = threading.main_thread()
569 self.assertEqual(main.name, 'MainThread')
570 self.assertEqual(main.ident, threading.current_thread().ident)
571 self.assertEqual(main.ident, threading.get_ident())
572
573 def f():
574 self.assertNotEqual(threading.main_thread().ident,
575 threading.current_thread().ident)
576 th = threading.Thread(target=f)
577 th.start()
578 th.join()
579
580 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
581 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
582 def test_main_thread_after_fork(self):
583 code = """if 1:
584 import os, threading
Victor Stinnera9f96872020-03-31 21:49:44 +0200585 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300586
587 pid = os.fork()
588 if pid == 0:
589 main = threading.main_thread()
590 print(main.name)
591 print(main.ident == threading.current_thread().ident)
592 print(main.ident == threading.get_ident())
593 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200594 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300595 """
596 _, out, err = assert_python_ok("-c", code)
597 data = out.decode().replace('\r', '')
598 self.assertEqual(err, b"")
599 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
600
601 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
602 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
603 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
604 def test_main_thread_after_fork_from_nonmain_thread(self):
605 code = """if 1:
606 import os, threading, sys
Victor Stinnera9f96872020-03-31 21:49:44 +0200607 from test import support
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300608
Victor Stinner98c16c92020-09-23 23:21:19 +0200609 def func():
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300610 pid = os.fork()
611 if pid == 0:
612 main = threading.main_thread()
613 print(main.name)
614 print(main.ident == threading.current_thread().ident)
615 print(main.ident == threading.get_ident())
616 # stdout is fully buffered because not a tty,
617 # we have to flush before exit.
618 sys.stdout.flush()
619 else:
Victor Stinnera9f96872020-03-31 21:49:44 +0200620 support.wait_process(pid, exitcode=0)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300621
Victor Stinner98c16c92020-09-23 23:21:19 +0200622 th = threading.Thread(target=func)
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300623 th.start()
624 th.join()
625 """
626 _, out, err = assert_python_ok("-c", code)
627 data = out.decode().replace('\r', '')
628 self.assertEqual(err, b"")
Victor Stinner98c16c92020-09-23 23:21:19 +0200629 self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300630
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200631 def test_main_thread_during_shutdown(self):
632 # bpo-31516: current_thread() should still point to the main thread
633 # at shutdown
634 code = """if 1:
635 import gc, threading
636
637 main_thread = threading.current_thread()
638 assert main_thread is threading.main_thread() # sanity check
639
640 class RefCycle:
641 def __init__(self):
642 self.cycle = self
643
644 def __del__(self):
645 print("GC:",
646 threading.current_thread() is main_thread,
647 threading.main_thread() is main_thread,
648 threading.enumerate() == [main_thread])
649
650 RefCycle()
651 gc.collect() # sanity check
652 x = RefCycle()
653 """
654 _, out, err = assert_python_ok("-c", code)
655 data = out.decode()
656 self.assertEqual(err, b"")
657 self.assertEqual(data.splitlines(),
658 ["GC: True True True"] * 2)
659
Victor Stinner468e5fe2019-06-13 01:30:17 +0200660 def test_finalization_shutdown(self):
661 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
662 # until Python thread states of all non-daemon threads get deleted.
663 #
664 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
665 # test the finalization of the main interpreter.
666 code = """if 1:
667 import os
668 import threading
669 import time
670 import random
671
672 def random_sleep():
673 seconds = random.random() * 0.010
674 time.sleep(seconds)
675
676 class Sleeper:
677 def __del__(self):
678 random_sleep()
679
680 tls = threading.local()
681
682 def f():
683 # Sleep a bit so that the thread is still running when
684 # Py_Finalize() is called.
685 random_sleep()
686 tls.x = Sleeper()
687 random_sleep()
688
689 threading.Thread(target=f).start()
690 random_sleep()
691 """
692 rc, out, err = assert_python_ok("-c", code)
693 self.assertEqual(err, b"")
694
Antoine Pitrou7b476992013-09-07 23:38:37 +0200695 def test_tstate_lock(self):
696 # Test an implementation detail of Thread objects.
697 started = _thread.allocate_lock()
698 finish = _thread.allocate_lock()
699 started.acquire()
700 finish.acquire()
701 def f():
702 started.release()
703 finish.acquire()
704 time.sleep(0.01)
705 # The tstate lock is None until the thread is started
706 t = threading.Thread(target=f)
707 self.assertIs(t._tstate_lock, None)
708 t.start()
709 started.acquire()
710 self.assertTrue(t.is_alive())
711 # The tstate lock can't be acquired when the thread is running
712 # (or suspended).
713 tstate_lock = t._tstate_lock
714 self.assertFalse(tstate_lock.acquire(timeout=0), False)
715 finish.release()
716 # When the thread ends, the state_lock can be successfully
717 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100718 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200719 # But is_alive() is still True: we hold _tstate_lock now, which
720 # prevents is_alive() from knowing the thread's end-of-life C code
721 # is done.
722 self.assertTrue(t.is_alive())
723 # Let is_alive() find out the C code is done.
724 tstate_lock.release()
725 self.assertFalse(t.is_alive())
726 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200727 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700728 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200729
Tim Peters72460fa2013-09-09 18:48:24 -0500730 def test_repr_stopped(self):
731 # Verify that "stopped" shows up in repr(Thread) appropriately.
732 started = _thread.allocate_lock()
733 finish = _thread.allocate_lock()
734 started.acquire()
735 finish.acquire()
736 def f():
737 started.release()
738 finish.acquire()
739 t = threading.Thread(target=f)
740 t.start()
741 started.acquire()
742 self.assertIn("started", repr(t))
743 finish.release()
744 # "stopped" should appear in the repr in a reasonable amount of time.
745 # Implementation detail: as of this writing, that's trivially true
746 # if .join() is called, and almost trivially true if .is_alive() is
747 # called. The detail we're testing here is that "stopped" shows up
748 # "all on its own".
749 LOOKING_FOR = "stopped"
750 for i in range(500):
751 if LOOKING_FOR in repr(t):
752 break
753 time.sleep(0.01)
754 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700755 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000756
Tim Peters7634e1c2013-10-08 20:55:51 -0500757 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500758 # BoundedSemaphore should raise ValueError if released too often.
759 for limit in range(1, 10):
760 bs = threading.BoundedSemaphore(limit)
761 threads = [threading.Thread(target=bs.acquire)
762 for _ in range(limit)]
763 for t in threads:
764 t.start()
765 for t in threads:
766 t.join()
767 threads = [threading.Thread(target=bs.release)
768 for _ in range(limit)]
769 for t in threads:
770 t.start()
771 for t in threads:
772 t.join()
773 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500774
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200775 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100776 def test_frame_tstate_tracing(self):
777 # Issue #14432: Crash when a generator is created in a C thread that is
778 # destroyed while the generator is still used. The issue was that a
779 # generator contains a frame, and the frame kept a reference to the
780 # Python state of the destroyed C thread. The crash occurs when a trace
781 # function is setup.
782
783 def noop_trace(frame, event, arg):
784 # no operation
785 return noop_trace
786
787 def generator():
788 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300789 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100790
791 def callback():
792 if callback.gen is None:
793 callback.gen = generator()
794 return next(callback.gen)
795 callback.gen = None
796
797 old_trace = sys.gettrace()
798 sys.settrace(noop_trace)
799 try:
800 # Install a trace function
801 threading.settrace(noop_trace)
802
803 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200804 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100805 _testcapi.call_in_temporary_c_thread(callback)
806
807 # Call the generator in a different Python thread, check that the
808 # generator didn't keep a reference to the destroyed thread state
809 for test in range(3):
810 # The trace function is still called here
811 callback()
812 finally:
813 sys.settrace(old_trace)
814
Mario Corchero0001a1b2020-11-04 10:27:43 +0100815 def test_gettrace(self):
816 def noop_trace(frame, event, arg):
817 # no operation
818 return noop_trace
819 old_trace = threading.gettrace()
820 try:
821 threading.settrace(noop_trace)
822 trace_func = threading.gettrace()
823 self.assertEqual(noop_trace,trace_func)
824 finally:
825 threading.settrace(old_trace)
826
827 def test_getprofile(self):
828 def fn(*args): pass
829 old_profile = threading.getprofile()
830 try:
831 threading.setprofile(fn)
832 self.assertEqual(fn, threading.getprofile())
833 finally:
834 threading.setprofile(old_profile)
835
Victor Stinner6f75c872019-06-13 12:06:24 +0200836 @cpython_only
837 def test_shutdown_locks(self):
838 for daemon in (False, True):
839 with self.subTest(daemon=daemon):
840 event = threading.Event()
841 thread = threading.Thread(target=event.wait, daemon=daemon)
842
843 # Thread.start() must add lock to _shutdown_locks,
844 # but only for non-daemon thread
845 thread.start()
846 tstate_lock = thread._tstate_lock
847 if not daemon:
848 self.assertIn(tstate_lock, threading._shutdown_locks)
849 else:
850 self.assertNotIn(tstate_lock, threading._shutdown_locks)
851
852 # unblock the thread and join it
853 event.set()
854 thread.join()
855
856 # Thread._stop() must remove tstate_lock from _shutdown_locks.
857 # Daemon threads must never add it to _shutdown_locks.
858 self.assertNotIn(tstate_lock, threading._shutdown_locks)
859
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100860 def test_locals_at_exit(self):
861 # bpo-19466: thread locals must not be deleted before destructors
862 # are called
863 rc, out, err = assert_python_ok("-c", """if 1:
864 import threading
865
866 class Atexit:
867 def __del__(self):
868 print("thread_dict.atexit = %r" % thread_dict.atexit)
869
870 thread_dict = threading.local()
871 thread_dict.atexit = "value"
872
873 atexit = Atexit()
874 """)
875 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
876
BarneyStratford01c4fdd2021-02-02 20:24:24 +0000877 def test_boolean_target(self):
878 # bpo-41149: A thread that had a boolean value of False would not
879 # run, regardless of whether it was callable. The correct behaviour
880 # is for a thread to do nothing if its target is None, and to call
881 # the target otherwise.
882 class BooleanTarget(object):
883 def __init__(self):
884 self.ran = False
885 def __bool__(self):
886 return False
887 def __call__(self):
888 self.ran = True
889
890 target = BooleanTarget()
891 thread = threading.Thread(target=target)
892 thread.start()
893 thread.join()
894 self.assertTrue(target.ran)
895
896
Victor Stinner45956b92013-11-12 16:37:55 +0100897
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000898class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000899
900 def _run_and_join(self, script):
901 script = """if 1:
902 import sys, os, time, threading
903
904 # a thread, which waits for the main program to terminate
905 def joiningfunc(mainthread):
906 mainthread.join()
907 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000908 # stdout is fully buffered because not a tty, we have to flush
909 # before exit.
910 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000911 \n""" + script
912
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200913 rc, out, err = assert_python_ok("-c", script)
914 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000915 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000916
917 def test_1_join_on_shutdown(self):
918 # The usual case: on exit, wait for a non-daemon thread
919 script = """if 1:
920 import os
921 t = threading.Thread(target=joiningfunc,
922 args=(threading.current_thread(),))
923 t.start()
924 time.sleep(0.1)
925 print('end of main')
926 """
927 self._run_and_join(script)
928
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000929 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200930 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000931 def test_2_join_in_forked_process(self):
932 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000933 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200934 from test import support
935
Jesse Nollera8513972008-07-17 16:49:17 +0000936 childpid = os.fork()
937 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200938 # parent process
939 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000940 sys.exit(0)
941
Victor Stinnera9f96872020-03-31 21:49:44 +0200942 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000943 t = threading.Thread(target=joiningfunc,
944 args=(threading.current_thread(),))
945 t.start()
946 print('end of main')
947 """
948 self._run_and_join(script)
949
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000950 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200951 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000952 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000953 # Like the test above, but fork() was called from a worker thread
954 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000955
Jesse Nollera8513972008-07-17 16:49:17 +0000956 script = """if 1:
Victor Stinnera9f96872020-03-31 21:49:44 +0200957 from test import support
958
Jesse Nollera8513972008-07-17 16:49:17 +0000959 main_thread = threading.current_thread()
960 def worker():
961 childpid = os.fork()
962 if childpid != 0:
Victor Stinnera9f96872020-03-31 21:49:44 +0200963 # parent process
964 support.wait_process(childpid, exitcode=0)
Jesse Nollera8513972008-07-17 16:49:17 +0000965 sys.exit(0)
966
Victor Stinnera9f96872020-03-31 21:49:44 +0200967 # child process
Jesse Nollera8513972008-07-17 16:49:17 +0000968 t = threading.Thread(target=joiningfunc,
969 args=(main_thread,))
970 print('end of main')
971 t.start()
972 t.join() # Should not block: main_thread is already stopped
973
974 w = threading.Thread(target=worker)
975 w.start()
976 """
977 self._run_and_join(script)
978
Victor Stinner26d31862011-07-01 14:26:24 +0200979 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500980 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200981 # Check that a daemon thread cannot crash the interpreter on shutdown
982 # by manipulating internal structures that are being disposed of in
983 # the main thread.
984 script = """if True:
985 import os
986 import random
987 import sys
988 import time
989 import threading
990
991 thread_has_run = set()
992
993 def random_io():
994 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200995 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200996 with open(os.__file__, 'rb') as in_f:
997 stuff = in_f.read(200)
998 with open(os.devnull, 'wb') as null_f:
999 null_f.write(stuff)
1000 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +02001001 thread_has_run.add(threading.current_thread())
1002
1003 def main():
1004 count = 0
1005 for _ in range(40):
1006 new_thread = threading.Thread(target=random_io)
1007 new_thread.daemon = True
1008 new_thread.start()
1009 count += 1
1010 while len(thread_has_run) < count:
1011 time.sleep(0.001)
1012 # Trigger process shutdown
1013 sys.exit(0)
1014
1015 main()
1016 """
1017 rc, out, err = assert_python_ok('-c', script)
1018 self.assertFalse(err)
1019
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001020 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +01001021 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001022 def test_reinit_tls_after_fork(self):
1023 # Issue #13817: fork() would deadlock in a multithreaded program with
1024 # the ad-hoc TLS implementation.
1025
1026 def do_fork_and_wait():
1027 # just fork a child process and wait it
1028 pid = os.fork()
1029 if pid > 0:
Victor Stinnera9f96872020-03-31 21:49:44 +02001030 support.wait_process(pid, exitcode=50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001031 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001032 os._exit(50)
Charles-François Natali6d0d24e2012-02-02 20:31:42 +01001033
1034 # start a bunch of threads that will fork() child processes
1035 threads = []
1036 for i in range(16):
1037 t = threading.Thread(target=do_fork_and_wait)
1038 threads.append(t)
1039 t.start()
1040
1041 for t in threads:
1042 t.join()
1043
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001044 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
1045 def test_clear_threads_states_after_fork(self):
1046 # Issue #17094: check that threads states are cleared after fork()
1047
1048 # start a bunch of threads
1049 threads = []
1050 for i in range(16):
1051 t = threading.Thread(target=lambda : time.sleep(0.3))
1052 threads.append(t)
1053 t.start()
1054
1055 pid = os.fork()
1056 if pid == 0:
1057 # check that threads states have been cleared
1058 if len(sys._current_frames()) == 1:
Victor Stinnera9f96872020-03-31 21:49:44 +02001059 os._exit(51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001060 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001061 os._exit(52)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001062 else:
Victor Stinnera9f96872020-03-31 21:49:44 +02001063 support.wait_process(pid, exitcode=51)
Antoine Pitrou8408cea2013-05-05 23:47:09 +02001064
1065 for t in threads:
1066 t.join()
1067
Jesse Nollera8513972008-07-17 16:49:17 +00001068
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001069class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +02001070 def pipe(self):
1071 r, w = os.pipe()
1072 self.addCleanup(os.close, r)
1073 self.addCleanup(os.close, w)
1074 if hasattr(os, 'set_blocking'):
1075 os.set_blocking(r, False)
1076 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001077
1078 def test_threads_join(self):
1079 # Non-daemon threads should be joined at subinterpreter shutdown
1080 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +02001081 r, w = self.pipe()
1082 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001083 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001084 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001085 import threading
1086 import time
1087
Victor Stinner468e5fe2019-06-13 01:30:17 +02001088 def random_sleep():
1089 seconds = random.random() * 0.010
1090 time.sleep(seconds)
1091
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001092 def f():
1093 # Sleep a bit so that the thread is still running when
1094 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001095 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001096 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001097
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001098 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001099 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001100 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001101 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001102 self.assertEqual(ret, 0)
1103 # The thread was joined properly.
1104 self.assertEqual(os.read(r, 1), b"x")
1105
Antoine Pitrou7b476992013-09-07 23:38:37 +02001106 def test_threads_join_2(self):
1107 # Same as above, but a delay gets introduced after the thread's
1108 # Python code returned but before the thread state is deleted.
1109 # To achieve this, we register a thread-local object which sleeps
1110 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +02001111 r, w = self.pipe()
1112 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +02001113 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +02001114 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +02001115 import threading
1116 import time
1117
Victor Stinner468e5fe2019-06-13 01:30:17 +02001118 def random_sleep():
1119 seconds = random.random() * 0.010
1120 time.sleep(seconds)
1121
Antoine Pitrou7b476992013-09-07 23:38:37 +02001122 class Sleeper:
1123 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +02001124 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001125
1126 tls = threading.local()
1127
1128 def f():
1129 # Sleep a bit so that the thread is still running when
1130 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +02001131 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +02001132 tls.x = Sleeper()
1133 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +02001134
Antoine Pitrou7b476992013-09-07 23:38:37 +02001135 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +02001136 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +02001137 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001138 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001139 self.assertEqual(ret, 0)
1140 # The thread was joined properly.
1141 self.assertEqual(os.read(r, 1), b"x")
1142
Victor Stinner14d53312020-04-12 23:45:09 +02001143 @cpython_only
1144 def test_daemon_threads_fatal_error(self):
1145 subinterp_code = f"""if 1:
1146 import os
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001147 import threading
Victor Stinner14d53312020-04-12 23:45:09 +02001148 import time
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001149
Victor Stinner14d53312020-04-12 23:45:09 +02001150 def f():
1151 # Make sure the daemon thread is still running when
1152 # Py_EndInterpreter is called.
1153 time.sleep({test.support.SHORT_TIMEOUT})
1154 threading.Thread(target=f, daemon=True).start()
1155 """
1156 script = r"""if 1:
1157 import _testcapi
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001158
Victor Stinner14d53312020-04-12 23:45:09 +02001159 _testcapi.run_in_subinterp(%r)
1160 """ % (subinterp_code,)
1161 with test.support.SuppressCrashReport():
1162 rc, out, err = assert_python_failure("-c", script)
1163 self.assertIn("Fatal Python error: Py_EndInterpreter: "
1164 "not the last thread", err.decode())
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001165
1166
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001167class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001168 # A RuntimeError should be raised if Thread.start() is called
1169 # multiple times.
1170 def test_start_thread_again(self):
1171 thread = threading.Thread()
1172 thread.start()
1173 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001174 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001175
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001176 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001177 current_thread = threading.current_thread()
1178 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001179
1180 def test_joining_inactive_thread(self):
1181 thread = threading.Thread()
1182 self.assertRaises(RuntimeError, thread.join)
1183
1184 def test_daemonize_active_thread(self):
1185 thread = threading.Thread()
1186 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001187 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001188 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001189
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001190 def test_releasing_unacquired_lock(self):
1191 lock = threading.Lock()
1192 self.assertRaises(RuntimeError, lock.release)
1193
Ned Deily9a7c5242011-05-28 00:19:56 -07001194 def test_recursion_limit(self):
1195 # Issue 9670
1196 # test that excessive recursion within a non-main thread causes
1197 # an exception rather than crashing the interpreter on platforms
1198 # like Mac OS X or FreeBSD which have small default stack sizes
1199 # for threads
1200 script = """if True:
1201 import threading
1202
1203 def recurse():
1204 return recurse()
1205
1206 def outer():
1207 try:
1208 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001209 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001210 pass
1211
1212 w = threading.Thread(target=outer)
1213 w.start()
1214 w.join()
1215 print('end of main thread')
1216 """
1217 expected_output = "end of main thread\n"
1218 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001219 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001220 stdout, stderr = p.communicate()
1221 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001222 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001223 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001224
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001225 def test_print_exception(self):
1226 script = r"""if True:
1227 import threading
1228 import time
1229
1230 running = False
1231 def run():
1232 global running
1233 running = True
1234 while running:
1235 time.sleep(0.01)
1236 1/0
1237 t = threading.Thread(target=run)
1238 t.start()
1239 while not running:
1240 time.sleep(0.01)
1241 running = False
1242 t.join()
1243 """
1244 rc, out, err = assert_python_ok("-c", script)
1245 self.assertEqual(out, b'')
1246 err = err.decode()
1247 self.assertIn("Exception in thread", err)
1248 self.assertIn("Traceback (most recent call last):", err)
1249 self.assertIn("ZeroDivisionError", err)
1250 self.assertNotIn("Unhandled exception", err)
1251
1252 def test_print_exception_stderr_is_none_1(self):
1253 script = r"""if True:
1254 import sys
1255 import threading
1256 import time
1257
1258 running = False
1259 def run():
1260 global running
1261 running = True
1262 while running:
1263 time.sleep(0.01)
1264 1/0
1265 t = threading.Thread(target=run)
1266 t.start()
1267 while not running:
1268 time.sleep(0.01)
1269 sys.stderr = None
1270 running = False
1271 t.join()
1272 """
1273 rc, out, err = assert_python_ok("-c", script)
1274 self.assertEqual(out, b'')
1275 err = err.decode()
1276 self.assertIn("Exception in thread", err)
1277 self.assertIn("Traceback (most recent call last):", err)
1278 self.assertIn("ZeroDivisionError", err)
1279 self.assertNotIn("Unhandled exception", err)
1280
1281 def test_print_exception_stderr_is_none_2(self):
1282 script = r"""if True:
1283 import sys
1284 import threading
1285 import time
1286
1287 running = False
1288 def run():
1289 global running
1290 running = True
1291 while running:
1292 time.sleep(0.01)
1293 1/0
1294 sys.stderr = None
1295 t = threading.Thread(target=run)
1296 t.start()
1297 while not running:
1298 time.sleep(0.01)
1299 running = False
1300 t.join()
1301 """
1302 rc, out, err = assert_python_ok("-c", script)
1303 self.assertEqual(out, b'')
1304 self.assertNotIn("Unhandled exception", err.decode())
1305
Victor Stinnereec93312016-08-18 18:13:10 +02001306 def test_bare_raise_in_brand_new_thread(self):
1307 def bare_raise():
1308 raise
1309
1310 class Issue27558(threading.Thread):
1311 exc = None
1312
1313 def run(self):
1314 try:
1315 bare_raise()
1316 except Exception as exc:
1317 self.exc = exc
1318
1319 thread = Issue27558()
1320 thread.start()
1321 thread.join()
1322 self.assertIsNotNone(thread.exc)
1323 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001324 # explicitly break the reference cycle to not leak a dangling thread
1325 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001326
Victor Stinnercd590a72019-05-28 00:39:52 +02001327
1328class ThreadRunFail(threading.Thread):
1329 def run(self):
1330 raise ValueError("run failed")
1331
1332
1333class ExceptHookTests(BaseTestCase):
1334 def test_excepthook(self):
1335 with support.captured_output("stderr") as stderr:
1336 thread = ThreadRunFail(name="excepthook thread")
1337 thread.start()
1338 thread.join()
1339
1340 stderr = stderr.getvalue().strip()
1341 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1342 self.assertIn('Traceback (most recent call last):\n', stderr)
1343 self.assertIn(' raise ValueError("run failed")', stderr)
1344 self.assertIn('ValueError: run failed', stderr)
1345
1346 @support.cpython_only
1347 def test_excepthook_thread_None(self):
1348 # threading.excepthook called with thread=None: log the thread
1349 # identifier in this case.
1350 with support.captured_output("stderr") as stderr:
1351 try:
1352 raise ValueError("bug")
1353 except Exception as exc:
1354 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001355 try:
1356 threading.excepthook(args)
1357 finally:
1358 # Explicitly break a reference cycle
1359 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001360
1361 stderr = stderr.getvalue().strip()
1362 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1363 self.assertIn('Traceback (most recent call last):\n', stderr)
1364 self.assertIn(' raise ValueError("bug")', stderr)
1365 self.assertIn('ValueError: bug', stderr)
1366
1367 def test_system_exit(self):
1368 class ThreadExit(threading.Thread):
1369 def run(self):
1370 sys.exit(1)
1371
1372 # threading.excepthook() silently ignores SystemExit
1373 with support.captured_output("stderr") as stderr:
1374 thread = ThreadExit()
1375 thread.start()
1376 thread.join()
1377
1378 self.assertEqual(stderr.getvalue(), '')
1379
1380 def test_custom_excepthook(self):
1381 args = None
1382
1383 def hook(hook_args):
1384 nonlocal args
1385 args = hook_args
1386
1387 try:
1388 with support.swap_attr(threading, 'excepthook', hook):
1389 thread = ThreadRunFail()
1390 thread.start()
1391 thread.join()
1392
1393 self.assertEqual(args.exc_type, ValueError)
1394 self.assertEqual(str(args.exc_value), 'run failed')
1395 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1396 self.assertIs(args.thread, thread)
1397 finally:
1398 # Break reference cycle
1399 args = None
1400
1401 def test_custom_excepthook_fail(self):
1402 def threading_hook(args):
1403 raise ValueError("threading_hook failed")
1404
1405 err_str = None
1406
1407 def sys_hook(exc_type, exc_value, exc_traceback):
1408 nonlocal err_str
1409 err_str = str(exc_value)
1410
1411 with support.swap_attr(threading, 'excepthook', threading_hook), \
1412 support.swap_attr(sys, 'excepthook', sys_hook), \
1413 support.captured_output('stderr') as stderr:
1414 thread = ThreadRunFail()
1415 thread.start()
1416 thread.join()
1417
1418 self.assertEqual(stderr.getvalue(),
1419 'Exception in threading.excepthook:\n')
1420 self.assertEqual(err_str, 'threading_hook failed')
1421
Mario Corchero750c5ab2020-11-12 18:27:44 +01001422 def test_original_excepthook(self):
1423 def run_thread():
1424 with support.captured_output("stderr") as output:
1425 thread = ThreadRunFail(name="excepthook thread")
1426 thread.start()
1427 thread.join()
1428 return output.getvalue()
1429
1430 def threading_hook(args):
1431 print("Running a thread failed", file=sys.stderr)
1432
1433 default_output = run_thread()
1434 with support.swap_attr(threading, 'excepthook', threading_hook):
1435 custom_hook_output = run_thread()
1436 threading.excepthook = threading.__excepthook__
1437 recovered_output = run_thread()
1438
1439 self.assertEqual(default_output, recovered_output)
1440 self.assertNotEqual(default_output, custom_hook_output)
1441 self.assertEqual(custom_hook_output, "Running a thread failed\n")
1442
Victor Stinnercd590a72019-05-28 00:39:52 +02001443
R David Murray19aeb432013-03-30 17:19:38 -04001444class TimerTests(BaseTestCase):
1445
1446 def setUp(self):
1447 BaseTestCase.setUp(self)
1448 self.callback_args = []
1449 self.callback_event = threading.Event()
1450
1451 def test_init_immutable_default_args(self):
1452 # Issue 17435: constructor defaults were mutable objects, they could be
1453 # mutated via the object attributes and affect other Timer objects.
1454 timer1 = threading.Timer(0.01, self._callback_spy)
1455 timer1.start()
1456 self.callback_event.wait()
1457 timer1.args.append("blah")
1458 timer1.kwargs["foo"] = "bar"
1459 self.callback_event.clear()
1460 timer2 = threading.Timer(0.01, self._callback_spy)
1461 timer2.start()
1462 self.callback_event.wait()
1463 self.assertEqual(len(self.callback_args), 2)
1464 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001465 timer1.join()
1466 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001467
1468 def _callback_spy(self, *args, **kwargs):
1469 self.callback_args.append((args[:], kwargs.copy()))
1470 self.callback_event.set()
1471
Antoine Pitrou557934f2009-11-06 22:41:14 +00001472class LockTests(lock_tests.LockTests):
1473 locktype = staticmethod(threading.Lock)
1474
Antoine Pitrou434736a2009-11-10 18:46:01 +00001475class PyRLockTests(lock_tests.RLockTests):
1476 locktype = staticmethod(threading._PyRLock)
1477
Charles-François Natali6b671b22012-01-28 11:36:04 +01001478@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001479class CRLockTests(lock_tests.RLockTests):
1480 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001481
1482class EventTests(lock_tests.EventTests):
1483 eventtype = staticmethod(threading.Event)
1484
1485class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001486 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001487 locktype = staticmethod(threading.Condition)
1488
1489class ConditionTests(lock_tests.ConditionTests):
1490 condtype = staticmethod(threading.Condition)
1491
1492class SemaphoreTests(lock_tests.SemaphoreTests):
1493 semtype = staticmethod(threading.Semaphore)
1494
1495class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1496 semtype = staticmethod(threading.BoundedSemaphore)
1497
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001498class BarrierTests(lock_tests.BarrierTests):
1499 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001500
Matěj Cepl608876b2019-05-23 22:30:00 +02001501
Martin Panter19e69c52015-11-14 12:46:42 +00001502class MiscTestCase(unittest.TestCase):
1503 def test__all__(self):
1504 extra = {"ThreadError"}
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001505 not_exported = {'currentThread', 'activeCount'}
Martin Panter19e69c52015-11-14 12:46:42 +00001506 support.check__all__(self, threading, ('threading', '_thread'),
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001507 extra=extra, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001508
Matěj Cepl608876b2019-05-23 22:30:00 +02001509
1510class InterruptMainTests(unittest.TestCase):
Antoine Pitrouba251c22021-03-11 23:35:45 +01001511 def check_interrupt_main_with_signal_handler(self, signum):
1512 def handler(signum, frame):
1513 1/0
1514
1515 old_handler = signal.signal(signum, handler)
1516 self.addCleanup(signal.signal, signum, old_handler)
1517
1518 with self.assertRaises(ZeroDivisionError):
1519 _thread.interrupt_main()
1520
1521 def check_interrupt_main_noerror(self, signum):
1522 handler = signal.getsignal(signum)
1523 try:
1524 # No exception should arise.
1525 signal.signal(signum, signal.SIG_IGN)
1526 _thread.interrupt_main(signum)
1527
1528 signal.signal(signum, signal.SIG_DFL)
1529 _thread.interrupt_main(signum)
1530 finally:
1531 # Restore original handler
1532 signal.signal(signum, handler)
1533
Matěj Cepl608876b2019-05-23 22:30:00 +02001534 def test_interrupt_main_subthread(self):
1535 # Calling start_new_thread with a function that executes interrupt_main
1536 # should raise KeyboardInterrupt upon completion.
1537 def call_interrupt():
1538 _thread.interrupt_main()
1539 t = threading.Thread(target=call_interrupt)
1540 with self.assertRaises(KeyboardInterrupt):
1541 t.start()
1542 t.join()
1543 t.join()
1544
1545 def test_interrupt_main_mainthread(self):
1546 # Make sure that if interrupt_main is called in main thread that
1547 # KeyboardInterrupt is raised instantly.
1548 with self.assertRaises(KeyboardInterrupt):
1549 _thread.interrupt_main()
1550
Antoine Pitrouba251c22021-03-11 23:35:45 +01001551 def test_interrupt_main_with_signal_handler(self):
1552 self.check_interrupt_main_with_signal_handler(signal.SIGINT)
1553 self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
Matěj Cepl608876b2019-05-23 22:30:00 +02001554
Antoine Pitrouba251c22021-03-11 23:35:45 +01001555 def test_interrupt_main_noerror(self):
1556 self.check_interrupt_main_noerror(signal.SIGINT)
1557 self.check_interrupt_main_noerror(signal.SIGTERM)
1558
1559 def test_interrupt_main_invalid_signal(self):
1560 self.assertRaises(ValueError, _thread.interrupt_main, -1)
1561 self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
1562 self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
Matěj Cepl608876b2019-05-23 22:30:00 +02001563
1564
Kyle Stanleyb61b8182020-03-27 15:31:22 -04001565class AtexitTests(unittest.TestCase):
1566
1567 def test_atexit_output(self):
1568 rc, out, err = assert_python_ok("-c", """if True:
1569 import threading
1570
1571 def run_last():
1572 print('parrot')
1573
1574 threading._register_atexit(run_last)
1575 """)
1576
1577 self.assertFalse(err)
1578 self.assertEqual(out.strip(), b'parrot')
1579
1580 def test_atexit_called_once(self):
1581 rc, out, err = assert_python_ok("-c", """if True:
1582 import threading
1583 from unittest.mock import Mock
1584
1585 mock = Mock()
1586 threading._register_atexit(mock)
1587 mock.assert_not_called()
1588 # force early shutdown to ensure it was called once
1589 threading._shutdown()
1590 mock.assert_called_once()
1591 """)
1592
1593 self.assertFalse(err)
1594
1595 def test_atexit_after_shutdown(self):
1596 # The only way to do this is by registering an atexit within
1597 # an atexit, which is intended to raise an exception.
1598 rc, out, err = assert_python_ok("-c", """if True:
1599 import threading
1600
1601 def func():
1602 pass
1603
1604 def run_last():
1605 threading._register_atexit(func)
1606
1607 threading._register_atexit(run_last)
1608 """)
1609
1610 self.assertTrue(err)
1611 self.assertIn("RuntimeError: can't register atexit after shutdown",
1612 err.decode())
1613
1614
Tim Peters84d54892005-01-08 06:03:17 +00001615if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001616 unittest.main()