blob: a99b8eca2be785eb8ebd172bd52190a9739e2ce2 [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
Serhiy Storchakaa7930372016-07-03 22:27:26 +03006from test.support import (verbose, import_module, cpython_only,
7 requires_type_collecting)
Berker Peksagce643912015-05-06 06:33:17 +03008from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02009
Skip Montanaro4533f602001-08-20 20:28:48 +000010import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020012import _thread
13import threading
Skip Montanaro4533f602001-08-20 20:28:48 +000014import time
Tim Peters84d54892005-01-08 06:03:17 +000015import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000016import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000017import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000018import subprocess
Matěj Cepl608876b2019-05-23 22:30:00 +020019import signal
Victor Stinner066e5b12019-06-14 18:55:22 +020020import textwrap
Skip Montanaro4533f602001-08-20 20:28:48 +000021
Antoine Pitrou557934f2009-11-06 22:41:14 +000022from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000023from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000024
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030025
26# Between fork() and exec(), only async-safe functions are allowed (issues
27# #12316 and #11870), and fork() from a worker thread is known to trigger
28# problems with some operating systems (issue #3863): skip problematic tests
29# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010030platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030031
32
Tim Peters84d54892005-01-08 06:03:17 +000033# A trivial mutable counter.
34class Counter(object):
35 def __init__(self):
36 self.value = 0
37 def inc(self):
38 self.value += 1
39 def dec(self):
40 self.value -= 1
41 def get(self):
42 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000043
44class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000045 def __init__(self, name, testcase, sema, mutex, nrunning):
46 threading.Thread.__init__(self, name=name)
47 self.testcase = testcase
48 self.sema = sema
49 self.mutex = mutex
50 self.nrunning = nrunning
51
Skip Montanaro4533f602001-08-20 20:28:48 +000052 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000054 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000055 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000056 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000057
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 with self.sema:
59 with self.mutex:
60 self.nrunning.inc()
61 if verbose:
62 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020063 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000064
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 time.sleep(delay)
66 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000067 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000068
Christian Heimes4fbc72b2008-03-22 00:47:35 +000069 with self.mutex:
70 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020071 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000072 if verbose:
73 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000074 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000075
Skip Montanaro4533f602001-08-20 20:28:48 +000076
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000077class BaseTestCase(unittest.TestCase):
78 def setUp(self):
79 self._threads = test.support.threading_setup()
80
81 def tearDown(self):
82 test.support.threading_cleanup(*self._threads)
83 test.support.reap_children()
84
85
86class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000087
Tim Peters84d54892005-01-08 06:03:17 +000088 # Create a bunch of threads, let each do some work, wait until all are
89 # done.
90 def test_various_ops(self):
91 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
92 # times about 1 second per clump).
93 NUMTASKS = 10
94
95 # no more than 3 of the 10 can run at once
96 sema = threading.BoundedSemaphore(value=3)
97 mutex = threading.RLock()
98 numrunning = Counter()
99
100 threads = []
101
102 for i in range(NUMTASKS):
103 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
104 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200105 self.assertIsNone(t.ident)
106 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000107 t.start()
108
Jake Teslerb121f632019-05-22 08:43:17 -0700109 if hasattr(threading, 'get_native_id'):
110 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
111 self.assertNotIn(None, native_ids)
112 self.assertEqual(len(native_ids), NUMTASKS + 1)
113
Tim Peters84d54892005-01-08 06:03:17 +0000114 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000115 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000116 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200117 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200118 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000119 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200120 self.assertIsNotNone(t.ident)
121 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000122 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000124 self.assertEqual(numrunning.get(), 0)
125
Benjamin Petersond23f8222009-04-05 19:13:16 +0000126 def test_ident_of_no_threading_threads(self):
127 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200128 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000129 def f():
130 ident.append(threading.currentThread().ident)
131 done.set()
132 done = threading.Event()
133 ident = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700134 with support.wait_threads_exit():
135 tid = _thread.start_new_thread(f, ())
136 done.wait()
137 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000138 # Kill the "immortal" _DummyThread
139 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000140
Victor Stinner8c663fd2017-11-08 14:44:44 -0800141 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 def test_various_ops_small_stack(self):
143 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800144 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 try:
146 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000147 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000148 raise unittest.SkipTest(
149 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 self.test_various_ops()
151 threading.stack_size(0)
152
Victor Stinner8c663fd2017-11-08 14:44:44 -0800153 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154 def test_various_ops_large_stack(self):
155 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800156 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157 try:
158 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000159 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000160 raise unittest.SkipTest(
161 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162 self.test_various_ops()
163 threading.stack_size(0)
164
Tim Peters711906e2005-01-08 07:30:42 +0000165 def test_foreign_thread(self):
166 # Check that a "foreign" thread can use the threading module.
167 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000168 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000169 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000170 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000171 mutex.release()
172
173 mutex = threading.Lock()
174 mutex.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700175 with support.wait_threads_exit():
176 tid = _thread.start_new_thread(f, (mutex,))
177 # Wait for the thread to finish.
178 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000179 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000180 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800181 #Issue 29376
182 self.assertTrue(threading._active[tid].is_alive())
183 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000184 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000185
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000186 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
187 # exposed at the Python level. This test relies on ctypes to get at it.
188 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200189 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190
191 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200192 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193
194 class AsyncExc(Exception):
195 pass
196
197 exception = ctypes.py_object(AsyncExc)
198
Antoine Pitroube4d8092009-10-18 18:27:17 +0000199 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200200 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200201 self.assertIsInstance(tid, int)
202 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000203
204 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200205 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000206 # The exception is async, so we might have to keep the VM busy until
207 # it notices.
208 while True:
209 pass
210 except AsyncExc:
211 pass
212 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000213 # This code is unreachable but it reflects the intent. If we wanted
214 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000215 self.fail("AsyncExc not raised")
216 try:
217 self.assertEqual(result, 1) # one thread state modified
218 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000219 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000220 pass
221
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000222 # `worker_started` is set by the thread when it's inside a try/except
223 # block waiting to catch the asynchronously set AsyncExc exception.
224 # `worker_saw_exception` is set by the thread upon catching that
225 # exception.
226 worker_started = threading.Event()
227 worker_saw_exception = threading.Event()
228
229 class Worker(threading.Thread):
230 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200231 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 self.finished = False
233
234 try:
235 while True:
236 worker_started.set()
237 time.sleep(0.1)
238 except AsyncExc:
239 self.finished = True
240 worker_saw_exception.set()
241
242 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000243 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 t.start()
245 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000246 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247
248 # Try a thread id that doesn't make sense.
249 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200251 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000252 self.assertEqual(result, 0) # no thread states modified
253
254 # Now raise an exception in the worker thread.
255 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000256 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000257 ret = worker_started.wait()
258 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000259 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000260 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200261 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000262 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000263 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200264 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000265 self.assertEqual(result, 1) # one thread state modified
266 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000267 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000268 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000270 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000271 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000272 if t.finished:
273 t.join()
274 # else the thread is still running, and we have no way to kill it
275
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000276 def test_limbo_cleanup(self):
277 # Issue 7481: Failure to start thread should cleanup the limbo map.
278 def fail_new_thread(*args):
279 raise threading.ThreadError()
280 _start_new_thread = threading._start_new_thread
281 threading._start_new_thread = fail_new_thread
282 try:
283 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000284 self.assertRaises(threading.ThreadError, t.start)
285 self.assertFalse(
286 t in threading._limbo,
287 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000288 finally:
289 threading._start_new_thread = _start_new_thread
290
Min ho Kimc4cacc82019-07-31 08:16:13 +1000291 def test_finalize_running_thread(self):
Christian Heimes7d2ff882007-11-30 14:35:04 +0000292 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
293 # very late on python exit: on deallocation of a running thread for
294 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200295 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200297 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000298 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000299
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000300 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000301 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000302 ready.acquire()
303
Christian Heimes7d2ff882007-11-30 14:35:04 +0000304 # Module globals are cleared before __del__ is run
305 # So we save the functions in class dict
306 class C:
307 ensure = ctypes.pythonapi.PyGILState_Ensure
308 release = ctypes.pythonapi.PyGILState_Release
309 def __del__(self):
310 state = self.ensure()
311 self.release(state)
312
313 def waitingThread():
314 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000315 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000316 time.sleep(100)
317
Georg Brandl2067bfd2008-05-25 13:05:15 +0000318 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000319 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000320 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200321 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000322 self.assertEqual(rc, 42)
323
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324 def test_finalize_with_trace(self):
325 # Issue1733757
326 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200327 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000328 import sys, threading
329
330 # A deadlock-killer, to prevent the
331 # testsuite to hang forever
332 def killer():
333 import os, time
334 time.sleep(2)
335 print('program blocked; aborting')
336 os._exit(2)
337 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000338 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000339 t.start()
340
341 # This is the trace function
342 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000343 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000344 return func
345
346 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200347 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000348
Antoine Pitrou011bd622009-10-20 21:52:47 +0000349 def test_join_nondaemon_on_shutdown(self):
350 # Issue 1722344
351 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200352 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000353 import threading
354 from time import sleep
355
356 def child():
357 sleep(1)
358 # As a non-daemon thread we SHOULD wake up and nothing
359 # should be torn down yet
360 print("Woke up, sleep function is:", sleep)
361
362 threading.Thread(target=child).start()
363 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200364 """)
365 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000366 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200367 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000368
Christian Heimes1af737c2008-01-23 08:24:23 +0000369 def test_enumerate_after_join(self):
370 # Try hard to trigger #1703448: a thread is still returned in
371 # threading.enumerate() after it has been join()ed.
372 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000373 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000374 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000375 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000376 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000377 t = threading.Thread(target=lambda: None)
378 t.start()
379 t.join()
380 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000381 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000382 "#1703448 triggered after %d trials: %s" % (i, l))
383 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000384 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000385
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000386 def test_no_refcycle_through_target(self):
387 class RunSelfFunction(object):
388 def __init__(self, should_raise):
389 # The links in this refcycle from Thread back to self
390 # should be cleaned up when the thread completes.
391 self.should_raise = should_raise
392 self.thread = threading.Thread(target=self._run,
393 args=(self,),
394 kwargs={'yet_another':self})
395 self.thread.start()
396
397 def _run(self, other_ref, yet_another):
398 if self.should_raise:
399 raise SystemExit
400
401 cyclic_object = RunSelfFunction(should_raise=False)
402 weak_cyclic_object = weakref.ref(cyclic_object)
403 cyclic_object.thread.join()
404 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000405 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000406 msg=('%d references still around' %
407 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000408
409 raising_cyclic_object = RunSelfFunction(should_raise=True)
410 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
411 raising_cyclic_object.thread.join()
412 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000413 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000414 msg=('%d references still around' %
415 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000416
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000417 def test_old_threading_api(self):
418 # Just a quick sanity check to make sure the old method names are
419 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000420 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000421 t.isDaemon()
422 t.setDaemon(True)
423 t.getName()
424 t.setName("name")
Dong-hee Na89669ff2019-01-17 21:14:45 +0900425 with self.assertWarnsRegex(DeprecationWarning, 'use is_alive()'):
426 t.isAlive()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000427 e = threading.Event()
428 e.isSet()
429 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000430
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000431 def test_repr_daemon(self):
432 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200433 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000434 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200435 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000436
luzpaza5293b42017-11-05 07:37:50 -0600437 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000438 t = threading.Thread()
439 self.assertFalse(t.daemon)
440 t = threading.Thread(daemon=False)
441 self.assertFalse(t.daemon)
442 t = threading.Thread(daemon=True)
443 self.assertTrue(t.daemon)
444
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200445 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
446 def test_dummy_thread_after_fork(self):
447 # Issue #14308: a dummy thread in the active list doesn't mess up
448 # the after-fork mechanism.
449 code = """if 1:
450 import _thread, threading, os, time
451
452 def background_thread(evt):
453 # Creates and registers the _DummyThread instance
454 threading.current_thread()
455 evt.set()
456 time.sleep(10)
457
458 evt = threading.Event()
459 _thread.start_new_thread(background_thread, (evt,))
460 evt.wait()
461 assert threading.active_count() == 2, threading.active_count()
462 if os.fork() == 0:
463 assert threading.active_count() == 1, threading.active_count()
464 os._exit(0)
465 else:
466 os.wait()
467 """
468 _, out, err = assert_python_ok("-c", code)
469 self.assertEqual(out, b'')
470 self.assertEqual(err, b'')
471
Charles-François Natali9939cc82013-08-30 23:32:53 +0200472 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
473 def test_is_alive_after_fork(self):
474 # Try hard to trigger #18418: is_alive() could sometimes be True on
475 # threads that vanished after a fork.
476 old_interval = sys.getswitchinterval()
477 self.addCleanup(sys.setswitchinterval, old_interval)
478
479 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100480 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200481
482 for i in range(20):
483 t = threading.Thread(target=lambda: None)
484 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200485 pid = os.fork()
486 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700487 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200488 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700489 t.join()
490
Charles-François Natali9939cc82013-08-30 23:32:53 +0200491 pid, status = os.waitpid(pid, 0)
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700492 self.assertTrue(os.WIFEXITED(status))
493 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200494
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300495 def test_main_thread(self):
496 main = threading.main_thread()
497 self.assertEqual(main.name, 'MainThread')
498 self.assertEqual(main.ident, threading.current_thread().ident)
499 self.assertEqual(main.ident, threading.get_ident())
500
501 def f():
502 self.assertNotEqual(threading.main_thread().ident,
503 threading.current_thread().ident)
504 th = threading.Thread(target=f)
505 th.start()
506 th.join()
507
508 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
509 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
510 def test_main_thread_after_fork(self):
511 code = """if 1:
512 import os, threading
513
514 pid = os.fork()
515 if pid == 0:
516 main = threading.main_thread()
517 print(main.name)
518 print(main.ident == threading.current_thread().ident)
519 print(main.ident == threading.get_ident())
520 else:
521 os.waitpid(pid, 0)
522 """
523 _, out, err = assert_python_ok("-c", code)
524 data = out.decode().replace('\r', '')
525 self.assertEqual(err, b"")
526 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
527
528 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
529 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
530 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
531 def test_main_thread_after_fork_from_nonmain_thread(self):
532 code = """if 1:
533 import os, threading, sys
534
535 def f():
536 pid = os.fork()
537 if pid == 0:
538 main = threading.main_thread()
539 print(main.name)
540 print(main.ident == threading.current_thread().ident)
541 print(main.ident == threading.get_ident())
542 # stdout is fully buffered because not a tty,
543 # we have to flush before exit.
544 sys.stdout.flush()
545 else:
546 os.waitpid(pid, 0)
547
548 th = threading.Thread(target=f)
549 th.start()
550 th.join()
551 """
552 _, out, err = assert_python_ok("-c", code)
553 data = out.decode().replace('\r', '')
554 self.assertEqual(err, b"")
555 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
556
Zackery Spytz65d2f8c2018-10-12 02:31:21 -0600557 @requires_type_collecting
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200558 def test_main_thread_during_shutdown(self):
559 # bpo-31516: current_thread() should still point to the main thread
560 # at shutdown
561 code = """if 1:
562 import gc, threading
563
564 main_thread = threading.current_thread()
565 assert main_thread is threading.main_thread() # sanity check
566
567 class RefCycle:
568 def __init__(self):
569 self.cycle = self
570
571 def __del__(self):
572 print("GC:",
573 threading.current_thread() is main_thread,
574 threading.main_thread() is main_thread,
575 threading.enumerate() == [main_thread])
576
577 RefCycle()
578 gc.collect() # sanity check
579 x = RefCycle()
580 """
581 _, out, err = assert_python_ok("-c", code)
582 data = out.decode()
583 self.assertEqual(err, b"")
584 self.assertEqual(data.splitlines(),
585 ["GC: True True True"] * 2)
586
Victor Stinner468e5fe2019-06-13 01:30:17 +0200587 def test_finalization_shutdown(self):
588 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
589 # until Python thread states of all non-daemon threads get deleted.
590 #
591 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
592 # test the finalization of the main interpreter.
593 code = """if 1:
594 import os
595 import threading
596 import time
597 import random
598
599 def random_sleep():
600 seconds = random.random() * 0.010
601 time.sleep(seconds)
602
603 class Sleeper:
604 def __del__(self):
605 random_sleep()
606
607 tls = threading.local()
608
609 def f():
610 # Sleep a bit so that the thread is still running when
611 # Py_Finalize() is called.
612 random_sleep()
613 tls.x = Sleeper()
614 random_sleep()
615
616 threading.Thread(target=f).start()
617 random_sleep()
618 """
619 rc, out, err = assert_python_ok("-c", code)
620 self.assertEqual(err, b"")
621
Antoine Pitrou7b476992013-09-07 23:38:37 +0200622 def test_tstate_lock(self):
623 # Test an implementation detail of Thread objects.
624 started = _thread.allocate_lock()
625 finish = _thread.allocate_lock()
626 started.acquire()
627 finish.acquire()
628 def f():
629 started.release()
630 finish.acquire()
631 time.sleep(0.01)
632 # The tstate lock is None until the thread is started
633 t = threading.Thread(target=f)
634 self.assertIs(t._tstate_lock, None)
635 t.start()
636 started.acquire()
637 self.assertTrue(t.is_alive())
638 # The tstate lock can't be acquired when the thread is running
639 # (or suspended).
640 tstate_lock = t._tstate_lock
641 self.assertFalse(tstate_lock.acquire(timeout=0), False)
642 finish.release()
643 # When the thread ends, the state_lock can be successfully
644 # acquired.
645 self.assertTrue(tstate_lock.acquire(timeout=5), False)
646 # But is_alive() is still True: we hold _tstate_lock now, which
647 # prevents is_alive() from knowing the thread's end-of-life C code
648 # is done.
649 self.assertTrue(t.is_alive())
650 # Let is_alive() find out the C code is done.
651 tstate_lock.release()
652 self.assertFalse(t.is_alive())
653 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200654 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700655 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200656
Tim Peters72460fa2013-09-09 18:48:24 -0500657 def test_repr_stopped(self):
658 # Verify that "stopped" shows up in repr(Thread) appropriately.
659 started = _thread.allocate_lock()
660 finish = _thread.allocate_lock()
661 started.acquire()
662 finish.acquire()
663 def f():
664 started.release()
665 finish.acquire()
666 t = threading.Thread(target=f)
667 t.start()
668 started.acquire()
669 self.assertIn("started", repr(t))
670 finish.release()
671 # "stopped" should appear in the repr in a reasonable amount of time.
672 # Implementation detail: as of this writing, that's trivially true
673 # if .join() is called, and almost trivially true if .is_alive() is
674 # called. The detail we're testing here is that "stopped" shows up
675 # "all on its own".
676 LOOKING_FOR = "stopped"
677 for i in range(500):
678 if LOOKING_FOR in repr(t):
679 break
680 time.sleep(0.01)
681 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700682 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000683
Tim Peters7634e1c2013-10-08 20:55:51 -0500684 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500685 # BoundedSemaphore should raise ValueError if released too often.
686 for limit in range(1, 10):
687 bs = threading.BoundedSemaphore(limit)
688 threads = [threading.Thread(target=bs.acquire)
689 for _ in range(limit)]
690 for t in threads:
691 t.start()
692 for t in threads:
693 t.join()
694 threads = [threading.Thread(target=bs.release)
695 for _ in range(limit)]
696 for t in threads:
697 t.start()
698 for t in threads:
699 t.join()
700 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500701
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200702 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100703 def test_frame_tstate_tracing(self):
704 # Issue #14432: Crash when a generator is created in a C thread that is
705 # destroyed while the generator is still used. The issue was that a
706 # generator contains a frame, and the frame kept a reference to the
707 # Python state of the destroyed C thread. The crash occurs when a trace
708 # function is setup.
709
710 def noop_trace(frame, event, arg):
711 # no operation
712 return noop_trace
713
714 def generator():
715 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300716 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100717
718 def callback():
719 if callback.gen is None:
720 callback.gen = generator()
721 return next(callback.gen)
722 callback.gen = None
723
724 old_trace = sys.gettrace()
725 sys.settrace(noop_trace)
726 try:
727 # Install a trace function
728 threading.settrace(noop_trace)
729
730 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200731 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100732 _testcapi.call_in_temporary_c_thread(callback)
733
734 # Call the generator in a different Python thread, check that the
735 # generator didn't keep a reference to the destroyed thread state
736 for test in range(3):
737 # The trace function is still called here
738 callback()
739 finally:
740 sys.settrace(old_trace)
741
Victor Stinner6f75c872019-06-13 12:06:24 +0200742 @cpython_only
743 def test_shutdown_locks(self):
744 for daemon in (False, True):
745 with self.subTest(daemon=daemon):
746 event = threading.Event()
747 thread = threading.Thread(target=event.wait, daemon=daemon)
748
749 # Thread.start() must add lock to _shutdown_locks,
750 # but only for non-daemon thread
751 thread.start()
752 tstate_lock = thread._tstate_lock
753 if not daemon:
754 self.assertIn(tstate_lock, threading._shutdown_locks)
755 else:
756 self.assertNotIn(tstate_lock, threading._shutdown_locks)
757
758 # unblock the thread and join it
759 event.set()
760 thread.join()
761
762 # Thread._stop() must remove tstate_lock from _shutdown_locks.
763 # Daemon threads must never add it to _shutdown_locks.
764 self.assertNotIn(tstate_lock, threading._shutdown_locks)
765
Victor Stinner45956b92013-11-12 16:37:55 +0100766
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000767class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000768
769 def _run_and_join(self, script):
770 script = """if 1:
771 import sys, os, time, threading
772
773 # a thread, which waits for the main program to terminate
774 def joiningfunc(mainthread):
775 mainthread.join()
776 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000777 # stdout is fully buffered because not a tty, we have to flush
778 # before exit.
779 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000780 \n""" + script
781
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200782 rc, out, err = assert_python_ok("-c", script)
783 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000784 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000785
786 def test_1_join_on_shutdown(self):
787 # The usual case: on exit, wait for a non-daemon thread
788 script = """if 1:
789 import os
790 t = threading.Thread(target=joiningfunc,
791 args=(threading.current_thread(),))
792 t.start()
793 time.sleep(0.1)
794 print('end of main')
795 """
796 self._run_and_join(script)
797
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000798 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200799 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000800 def test_2_join_in_forked_process(self):
801 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000802 script = """if 1:
803 childpid = os.fork()
804 if childpid != 0:
805 os.waitpid(childpid, 0)
806 sys.exit(0)
807
808 t = threading.Thread(target=joiningfunc,
809 args=(threading.current_thread(),))
810 t.start()
811 print('end of main')
812 """
813 self._run_and_join(script)
814
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000815 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200816 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000817 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000818 # Like the test above, but fork() was called from a worker thread
819 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000820
Jesse Nollera8513972008-07-17 16:49:17 +0000821 script = """if 1:
822 main_thread = threading.current_thread()
823 def worker():
824 childpid = os.fork()
825 if childpid != 0:
826 os.waitpid(childpid, 0)
827 sys.exit(0)
828
829 t = threading.Thread(target=joiningfunc,
830 args=(main_thread,))
831 print('end of main')
832 t.start()
833 t.join() # Should not block: main_thread is already stopped
834
835 w = threading.Thread(target=worker)
836 w.start()
837 """
838 self._run_and_join(script)
839
Victor Stinner26d31862011-07-01 14:26:24 +0200840 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500841 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200842 # Check that a daemon thread cannot crash the interpreter on shutdown
843 # by manipulating internal structures that are being disposed of in
844 # the main thread.
845 script = """if True:
846 import os
847 import random
848 import sys
849 import time
850 import threading
851
852 thread_has_run = set()
853
854 def random_io():
855 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200856 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200857 with open(os.__file__, 'rb') as in_f:
858 stuff = in_f.read(200)
859 with open(os.devnull, 'wb') as null_f:
860 null_f.write(stuff)
861 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200862 thread_has_run.add(threading.current_thread())
863
864 def main():
865 count = 0
866 for _ in range(40):
867 new_thread = threading.Thread(target=random_io)
868 new_thread.daemon = True
869 new_thread.start()
870 count += 1
871 while len(thread_has_run) < count:
872 time.sleep(0.001)
873 # Trigger process shutdown
874 sys.exit(0)
875
876 main()
877 """
878 rc, out, err = assert_python_ok('-c', script)
879 self.assertFalse(err)
880
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100881 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100882 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100883 def test_reinit_tls_after_fork(self):
884 # Issue #13817: fork() would deadlock in a multithreaded program with
885 # the ad-hoc TLS implementation.
886
887 def do_fork_and_wait():
888 # just fork a child process and wait it
889 pid = os.fork()
890 if pid > 0:
891 os.waitpid(pid, 0)
892 else:
893 os._exit(0)
894
895 # start a bunch of threads that will fork() child processes
896 threads = []
897 for i in range(16):
898 t = threading.Thread(target=do_fork_and_wait)
899 threads.append(t)
900 t.start()
901
902 for t in threads:
903 t.join()
904
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200905 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
906 def test_clear_threads_states_after_fork(self):
907 # Issue #17094: check that threads states are cleared after fork()
908
909 # start a bunch of threads
910 threads = []
911 for i in range(16):
912 t = threading.Thread(target=lambda : time.sleep(0.3))
913 threads.append(t)
914 t.start()
915
916 pid = os.fork()
917 if pid == 0:
918 # check that threads states have been cleared
919 if len(sys._current_frames()) == 1:
920 os._exit(0)
921 else:
922 os._exit(1)
923 else:
924 _, status = os.waitpid(pid, 0)
925 self.assertEqual(0, status)
926
927 for t in threads:
928 t.join()
929
Jesse Nollera8513972008-07-17 16:49:17 +0000930
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200931class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +0200932 def pipe(self):
933 r, w = os.pipe()
934 self.addCleanup(os.close, r)
935 self.addCleanup(os.close, w)
936 if hasattr(os, 'set_blocking'):
937 os.set_blocking(r, False)
938 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200939
940 def test_threads_join(self):
941 # Non-daemon threads should be joined at subinterpreter shutdown
942 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +0200943 r, w = self.pipe()
944 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200945 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200946 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200947 import threading
948 import time
949
Victor Stinner468e5fe2019-06-13 01:30:17 +0200950 def random_sleep():
951 seconds = random.random() * 0.010
952 time.sleep(seconds)
953
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200954 def f():
955 # Sleep a bit so that the thread is still running when
956 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200957 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200958 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200959
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200960 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200961 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200962 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100963 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200964 self.assertEqual(ret, 0)
965 # The thread was joined properly.
966 self.assertEqual(os.read(r, 1), b"x")
967
Antoine Pitrou7b476992013-09-07 23:38:37 +0200968 def test_threads_join_2(self):
969 # Same as above, but a delay gets introduced after the thread's
970 # Python code returned but before the thread state is deleted.
971 # To achieve this, we register a thread-local object which sleeps
972 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +0200973 r, w = self.pipe()
974 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +0200975 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200976 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +0200977 import threading
978 import time
979
Victor Stinner468e5fe2019-06-13 01:30:17 +0200980 def random_sleep():
981 seconds = random.random() * 0.010
982 time.sleep(seconds)
983
Antoine Pitrou7b476992013-09-07 23:38:37 +0200984 class Sleeper:
985 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +0200986 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200987
988 tls = threading.local()
989
990 def f():
991 # Sleep a bit so that the thread is still running when
992 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200993 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200994 tls.x = Sleeper()
995 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200996
Antoine Pitrou7b476992013-09-07 23:38:37 +0200997 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200998 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200999 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001000 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +02001001 self.assertEqual(ret, 0)
1002 # The thread was joined properly.
1003 self.assertEqual(os.read(r, 1), b"x")
1004
Victor Stinner066e5b12019-06-14 18:55:22 +02001005 def test_daemon_thread(self):
1006 r, w = self.pipe()
1007 code = textwrap.dedent(f"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001008 import threading
Victor Stinner066e5b12019-06-14 18:55:22 +02001009 import sys
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001010
Victor Stinner066e5b12019-06-14 18:55:22 +02001011 channel = open({w}, "w", closefd=False)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001012
Victor Stinner066e5b12019-06-14 18:55:22 +02001013 def func():
1014 pass
1015
1016 thread = threading.Thread(target=func, daemon=True)
1017 try:
1018 thread.start()
1019 except RuntimeError as exc:
1020 print("ok: %s" % exc, file=channel, flush=True)
1021 else:
1022 thread.join()
1023 print("fail: RuntimeError not raised", file=channel, flush=True)
1024 """)
1025 ret = test.support.run_in_subinterp(code)
1026 self.assertEqual(ret, 0)
1027
1028 msg = os.read(r, 100).decode().rstrip()
1029 self.assertEqual("ok: daemon thread are not supported "
1030 "in subinterpreters", msg)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001031
1032
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001033class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001034 # A RuntimeError should be raised if Thread.start() is called
1035 # multiple times.
1036 def test_start_thread_again(self):
1037 thread = threading.Thread()
1038 thread.start()
1039 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001040 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001041
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001042 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001043 current_thread = threading.current_thread()
1044 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001045
1046 def test_joining_inactive_thread(self):
1047 thread = threading.Thread()
1048 self.assertRaises(RuntimeError, thread.join)
1049
1050 def test_daemonize_active_thread(self):
1051 thread = threading.Thread()
1052 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001053 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001054 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001055
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001056 def test_releasing_unacquired_lock(self):
1057 lock = threading.Lock()
1058 self.assertRaises(RuntimeError, lock.release)
1059
Benjamin Petersond541d3f2012-10-13 11:46:44 -04001060 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
1061 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -07001062 def test_recursion_limit(self):
1063 # Issue 9670
1064 # test that excessive recursion within a non-main thread causes
1065 # an exception rather than crashing the interpreter on platforms
1066 # like Mac OS X or FreeBSD which have small default stack sizes
1067 # for threads
1068 script = """if True:
1069 import threading
1070
1071 def recurse():
1072 return recurse()
1073
1074 def outer():
1075 try:
1076 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001077 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001078 pass
1079
1080 w = threading.Thread(target=outer)
1081 w.start()
1082 w.join()
1083 print('end of main thread')
1084 """
1085 expected_output = "end of main thread\n"
1086 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001087 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001088 stdout, stderr = p.communicate()
1089 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001090 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001091 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001092
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001093 def test_print_exception(self):
1094 script = r"""if True:
1095 import threading
1096 import time
1097
1098 running = False
1099 def run():
1100 global running
1101 running = True
1102 while running:
1103 time.sleep(0.01)
1104 1/0
1105 t = threading.Thread(target=run)
1106 t.start()
1107 while not running:
1108 time.sleep(0.01)
1109 running = False
1110 t.join()
1111 """
1112 rc, out, err = assert_python_ok("-c", script)
1113 self.assertEqual(out, b'')
1114 err = err.decode()
1115 self.assertIn("Exception in thread", err)
1116 self.assertIn("Traceback (most recent call last):", err)
1117 self.assertIn("ZeroDivisionError", err)
1118 self.assertNotIn("Unhandled exception", err)
1119
Serhiy Storchakaa7930372016-07-03 22:27:26 +03001120 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001121 def test_print_exception_stderr_is_none_1(self):
1122 script = r"""if True:
1123 import sys
1124 import threading
1125 import time
1126
1127 running = False
1128 def run():
1129 global running
1130 running = True
1131 while running:
1132 time.sleep(0.01)
1133 1/0
1134 t = threading.Thread(target=run)
1135 t.start()
1136 while not running:
1137 time.sleep(0.01)
1138 sys.stderr = None
1139 running = False
1140 t.join()
1141 """
1142 rc, out, err = assert_python_ok("-c", script)
1143 self.assertEqual(out, b'')
1144 err = err.decode()
1145 self.assertIn("Exception in thread", err)
1146 self.assertIn("Traceback (most recent call last):", err)
1147 self.assertIn("ZeroDivisionError", err)
1148 self.assertNotIn("Unhandled exception", err)
1149
1150 def test_print_exception_stderr_is_none_2(self):
1151 script = r"""if True:
1152 import sys
1153 import threading
1154 import time
1155
1156 running = False
1157 def run():
1158 global running
1159 running = True
1160 while running:
1161 time.sleep(0.01)
1162 1/0
1163 sys.stderr = None
1164 t = threading.Thread(target=run)
1165 t.start()
1166 while not running:
1167 time.sleep(0.01)
1168 running = False
1169 t.join()
1170 """
1171 rc, out, err = assert_python_ok("-c", script)
1172 self.assertEqual(out, b'')
1173 self.assertNotIn("Unhandled exception", err.decode())
1174
Victor Stinnereec93312016-08-18 18:13:10 +02001175 def test_bare_raise_in_brand_new_thread(self):
1176 def bare_raise():
1177 raise
1178
1179 class Issue27558(threading.Thread):
1180 exc = None
1181
1182 def run(self):
1183 try:
1184 bare_raise()
1185 except Exception as exc:
1186 self.exc = exc
1187
1188 thread = Issue27558()
1189 thread.start()
1190 thread.join()
1191 self.assertIsNotNone(thread.exc)
1192 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001193 # explicitly break the reference cycle to not leak a dangling thread
1194 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001195
Victor Stinnercd590a72019-05-28 00:39:52 +02001196
1197class ThreadRunFail(threading.Thread):
1198 def run(self):
1199 raise ValueError("run failed")
1200
1201
1202class ExceptHookTests(BaseTestCase):
1203 def test_excepthook(self):
1204 with support.captured_output("stderr") as stderr:
1205 thread = ThreadRunFail(name="excepthook thread")
1206 thread.start()
1207 thread.join()
1208
1209 stderr = stderr.getvalue().strip()
1210 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1211 self.assertIn('Traceback (most recent call last):\n', stderr)
1212 self.assertIn(' raise ValueError("run failed")', stderr)
1213 self.assertIn('ValueError: run failed', stderr)
1214
1215 @support.cpython_only
1216 def test_excepthook_thread_None(self):
1217 # threading.excepthook called with thread=None: log the thread
1218 # identifier in this case.
1219 with support.captured_output("stderr") as stderr:
1220 try:
1221 raise ValueError("bug")
1222 except Exception as exc:
1223 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001224 try:
1225 threading.excepthook(args)
1226 finally:
1227 # Explicitly break a reference cycle
1228 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001229
1230 stderr = stderr.getvalue().strip()
1231 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1232 self.assertIn('Traceback (most recent call last):\n', stderr)
1233 self.assertIn(' raise ValueError("bug")', stderr)
1234 self.assertIn('ValueError: bug', stderr)
1235
1236 def test_system_exit(self):
1237 class ThreadExit(threading.Thread):
1238 def run(self):
1239 sys.exit(1)
1240
1241 # threading.excepthook() silently ignores SystemExit
1242 with support.captured_output("stderr") as stderr:
1243 thread = ThreadExit()
1244 thread.start()
1245 thread.join()
1246
1247 self.assertEqual(stderr.getvalue(), '')
1248
1249 def test_custom_excepthook(self):
1250 args = None
1251
1252 def hook(hook_args):
1253 nonlocal args
1254 args = hook_args
1255
1256 try:
1257 with support.swap_attr(threading, 'excepthook', hook):
1258 thread = ThreadRunFail()
1259 thread.start()
1260 thread.join()
1261
1262 self.assertEqual(args.exc_type, ValueError)
1263 self.assertEqual(str(args.exc_value), 'run failed')
1264 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1265 self.assertIs(args.thread, thread)
1266 finally:
1267 # Break reference cycle
1268 args = None
1269
1270 def test_custom_excepthook_fail(self):
1271 def threading_hook(args):
1272 raise ValueError("threading_hook failed")
1273
1274 err_str = None
1275
1276 def sys_hook(exc_type, exc_value, exc_traceback):
1277 nonlocal err_str
1278 err_str = str(exc_value)
1279
1280 with support.swap_attr(threading, 'excepthook', threading_hook), \
1281 support.swap_attr(sys, 'excepthook', sys_hook), \
1282 support.captured_output('stderr') as stderr:
1283 thread = ThreadRunFail()
1284 thread.start()
1285 thread.join()
1286
1287 self.assertEqual(stderr.getvalue(),
1288 'Exception in threading.excepthook:\n')
1289 self.assertEqual(err_str, 'threading_hook failed')
1290
1291
R David Murray19aeb432013-03-30 17:19:38 -04001292class TimerTests(BaseTestCase):
1293
1294 def setUp(self):
1295 BaseTestCase.setUp(self)
1296 self.callback_args = []
1297 self.callback_event = threading.Event()
1298
1299 def test_init_immutable_default_args(self):
1300 # Issue 17435: constructor defaults were mutable objects, they could be
1301 # mutated via the object attributes and affect other Timer objects.
1302 timer1 = threading.Timer(0.01, self._callback_spy)
1303 timer1.start()
1304 self.callback_event.wait()
1305 timer1.args.append("blah")
1306 timer1.kwargs["foo"] = "bar"
1307 self.callback_event.clear()
1308 timer2 = threading.Timer(0.01, self._callback_spy)
1309 timer2.start()
1310 self.callback_event.wait()
1311 self.assertEqual(len(self.callback_args), 2)
1312 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001313 timer1.join()
1314 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001315
1316 def _callback_spy(self, *args, **kwargs):
1317 self.callback_args.append((args[:], kwargs.copy()))
1318 self.callback_event.set()
1319
Antoine Pitrou557934f2009-11-06 22:41:14 +00001320class LockTests(lock_tests.LockTests):
1321 locktype = staticmethod(threading.Lock)
1322
Antoine Pitrou434736a2009-11-10 18:46:01 +00001323class PyRLockTests(lock_tests.RLockTests):
1324 locktype = staticmethod(threading._PyRLock)
1325
Charles-François Natali6b671b22012-01-28 11:36:04 +01001326@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001327class CRLockTests(lock_tests.RLockTests):
1328 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001329
1330class EventTests(lock_tests.EventTests):
1331 eventtype = staticmethod(threading.Event)
1332
1333class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001334 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001335 locktype = staticmethod(threading.Condition)
1336
1337class ConditionTests(lock_tests.ConditionTests):
1338 condtype = staticmethod(threading.Condition)
1339
1340class SemaphoreTests(lock_tests.SemaphoreTests):
1341 semtype = staticmethod(threading.Semaphore)
1342
1343class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1344 semtype = staticmethod(threading.BoundedSemaphore)
1345
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001346class BarrierTests(lock_tests.BarrierTests):
1347 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001348
Matěj Cepl608876b2019-05-23 22:30:00 +02001349
Martin Panter19e69c52015-11-14 12:46:42 +00001350class MiscTestCase(unittest.TestCase):
1351 def test__all__(self):
1352 extra = {"ThreadError"}
1353 blacklist = {'currentThread', 'activeCount'}
1354 support.check__all__(self, threading, ('threading', '_thread'),
1355 extra=extra, blacklist=blacklist)
1356
Matěj Cepl608876b2019-05-23 22:30:00 +02001357
1358class InterruptMainTests(unittest.TestCase):
1359 def test_interrupt_main_subthread(self):
1360 # Calling start_new_thread with a function that executes interrupt_main
1361 # should raise KeyboardInterrupt upon completion.
1362 def call_interrupt():
1363 _thread.interrupt_main()
1364 t = threading.Thread(target=call_interrupt)
1365 with self.assertRaises(KeyboardInterrupt):
1366 t.start()
1367 t.join()
1368 t.join()
1369
1370 def test_interrupt_main_mainthread(self):
1371 # Make sure that if interrupt_main is called in main thread that
1372 # KeyboardInterrupt is raised instantly.
1373 with self.assertRaises(KeyboardInterrupt):
1374 _thread.interrupt_main()
1375
1376 def test_interrupt_main_noerror(self):
1377 handler = signal.getsignal(signal.SIGINT)
1378 try:
1379 # No exception should arise.
1380 signal.signal(signal.SIGINT, signal.SIG_IGN)
1381 _thread.interrupt_main()
1382
1383 signal.signal(signal.SIGINT, signal.SIG_DFL)
1384 _thread.interrupt_main()
1385 finally:
1386 # Restore original handler
1387 signal.signal(signal.SIGINT, handler)
1388
1389
Tim Peters84d54892005-01-08 06:03:17 +00001390if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001391 unittest.main()