blob: 62f2d54ad0a8efa943334e0f2f197c0715f9494d [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")
Victor Stinner0d63bac2019-12-11 11:30:03 +0100268 worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
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")
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000425 e = threading.Event()
426 e.isSet()
427 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000428
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000429 def test_repr_daemon(self):
430 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200431 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000432 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200433 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000434
luzpaza5293b42017-11-05 07:37:50 -0600435 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000436 t = threading.Thread()
437 self.assertFalse(t.daemon)
438 t = threading.Thread(daemon=False)
439 self.assertFalse(t.daemon)
440 t = threading.Thread(daemon=True)
441 self.assertTrue(t.daemon)
442
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200443 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
444 def test_dummy_thread_after_fork(self):
445 # Issue #14308: a dummy thread in the active list doesn't mess up
446 # the after-fork mechanism.
447 code = """if 1:
448 import _thread, threading, os, time
449
450 def background_thread(evt):
451 # Creates and registers the _DummyThread instance
452 threading.current_thread()
453 evt.set()
454 time.sleep(10)
455
456 evt = threading.Event()
457 _thread.start_new_thread(background_thread, (evt,))
458 evt.wait()
459 assert threading.active_count() == 2, threading.active_count()
460 if os.fork() == 0:
461 assert threading.active_count() == 1, threading.active_count()
462 os._exit(0)
463 else:
464 os.wait()
465 """
466 _, out, err = assert_python_ok("-c", code)
467 self.assertEqual(out, b'')
468 self.assertEqual(err, b'')
469
Charles-François Natali9939cc82013-08-30 23:32:53 +0200470 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
471 def test_is_alive_after_fork(self):
472 # Try hard to trigger #18418: is_alive() could sometimes be True on
473 # threads that vanished after a fork.
474 old_interval = sys.getswitchinterval()
475 self.addCleanup(sys.setswitchinterval, old_interval)
476
477 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100478 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200479
480 for i in range(20):
481 t = threading.Thread(target=lambda: None)
482 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200483 pid = os.fork()
484 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700485 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200486 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700487 t.join()
488
Charles-François Natali9939cc82013-08-30 23:32:53 +0200489 pid, status = os.waitpid(pid, 0)
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700490 self.assertTrue(os.WIFEXITED(status))
491 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200492
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300493 def test_main_thread(self):
494 main = threading.main_thread()
495 self.assertEqual(main.name, 'MainThread')
496 self.assertEqual(main.ident, threading.current_thread().ident)
497 self.assertEqual(main.ident, threading.get_ident())
498
499 def f():
500 self.assertNotEqual(threading.main_thread().ident,
501 threading.current_thread().ident)
502 th = threading.Thread(target=f)
503 th.start()
504 th.join()
505
506 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
507 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
508 def test_main_thread_after_fork(self):
509 code = """if 1:
510 import os, threading
511
512 pid = os.fork()
513 if pid == 0:
514 main = threading.main_thread()
515 print(main.name)
516 print(main.ident == threading.current_thread().ident)
517 print(main.ident == threading.get_ident())
518 else:
519 os.waitpid(pid, 0)
520 """
521 _, out, err = assert_python_ok("-c", code)
522 data = out.decode().replace('\r', '')
523 self.assertEqual(err, b"")
524 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
525
526 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
527 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
528 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
529 def test_main_thread_after_fork_from_nonmain_thread(self):
530 code = """if 1:
531 import os, threading, sys
532
533 def f():
534 pid = os.fork()
535 if pid == 0:
536 main = threading.main_thread()
537 print(main.name)
538 print(main.ident == threading.current_thread().ident)
539 print(main.ident == threading.get_ident())
540 # stdout is fully buffered because not a tty,
541 # we have to flush before exit.
542 sys.stdout.flush()
543 else:
544 os.waitpid(pid, 0)
545
546 th = threading.Thread(target=f)
547 th.start()
548 th.join()
549 """
550 _, out, err = assert_python_ok("-c", code)
551 data = out.decode().replace('\r', '')
552 self.assertEqual(err, b"")
553 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
554
Zackery Spytz65d2f8c2018-10-12 02:31:21 -0600555 @requires_type_collecting
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200556 def test_main_thread_during_shutdown(self):
557 # bpo-31516: current_thread() should still point to the main thread
558 # at shutdown
559 code = """if 1:
560 import gc, threading
561
562 main_thread = threading.current_thread()
563 assert main_thread is threading.main_thread() # sanity check
564
565 class RefCycle:
566 def __init__(self):
567 self.cycle = self
568
569 def __del__(self):
570 print("GC:",
571 threading.current_thread() is main_thread,
572 threading.main_thread() is main_thread,
573 threading.enumerate() == [main_thread])
574
575 RefCycle()
576 gc.collect() # sanity check
577 x = RefCycle()
578 """
579 _, out, err = assert_python_ok("-c", code)
580 data = out.decode()
581 self.assertEqual(err, b"")
582 self.assertEqual(data.splitlines(),
583 ["GC: True True True"] * 2)
584
Victor Stinner468e5fe2019-06-13 01:30:17 +0200585 def test_finalization_shutdown(self):
586 # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
587 # until Python thread states of all non-daemon threads get deleted.
588 #
589 # Test similar to SubinterpThreadingTests.test_threads_join_2(), but
590 # test the finalization of the main interpreter.
591 code = """if 1:
592 import os
593 import threading
594 import time
595 import random
596
597 def random_sleep():
598 seconds = random.random() * 0.010
599 time.sleep(seconds)
600
601 class Sleeper:
602 def __del__(self):
603 random_sleep()
604
605 tls = threading.local()
606
607 def f():
608 # Sleep a bit so that the thread is still running when
609 # Py_Finalize() is called.
610 random_sleep()
611 tls.x = Sleeper()
612 random_sleep()
613
614 threading.Thread(target=f).start()
615 random_sleep()
616 """
617 rc, out, err = assert_python_ok("-c", code)
618 self.assertEqual(err, b"")
619
Antoine Pitrou7b476992013-09-07 23:38:37 +0200620 def test_tstate_lock(self):
621 # Test an implementation detail of Thread objects.
622 started = _thread.allocate_lock()
623 finish = _thread.allocate_lock()
624 started.acquire()
625 finish.acquire()
626 def f():
627 started.release()
628 finish.acquire()
629 time.sleep(0.01)
630 # The tstate lock is None until the thread is started
631 t = threading.Thread(target=f)
632 self.assertIs(t._tstate_lock, None)
633 t.start()
634 started.acquire()
635 self.assertTrue(t.is_alive())
636 # The tstate lock can't be acquired when the thread is running
637 # (or suspended).
638 tstate_lock = t._tstate_lock
639 self.assertFalse(tstate_lock.acquire(timeout=0), False)
640 finish.release()
641 # When the thread ends, the state_lock can be successfully
642 # acquired.
Victor Stinner0d63bac2019-12-11 11:30:03 +0100643 self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200644 # But is_alive() is still True: we hold _tstate_lock now, which
645 # prevents is_alive() from knowing the thread's end-of-life C code
646 # is done.
647 self.assertTrue(t.is_alive())
648 # Let is_alive() find out the C code is done.
649 tstate_lock.release()
650 self.assertFalse(t.is_alive())
651 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200652 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700653 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200654
Tim Peters72460fa2013-09-09 18:48:24 -0500655 def test_repr_stopped(self):
656 # Verify that "stopped" shows up in repr(Thread) appropriately.
657 started = _thread.allocate_lock()
658 finish = _thread.allocate_lock()
659 started.acquire()
660 finish.acquire()
661 def f():
662 started.release()
663 finish.acquire()
664 t = threading.Thread(target=f)
665 t.start()
666 started.acquire()
667 self.assertIn("started", repr(t))
668 finish.release()
669 # "stopped" should appear in the repr in a reasonable amount of time.
670 # Implementation detail: as of this writing, that's trivially true
671 # if .join() is called, and almost trivially true if .is_alive() is
672 # called. The detail we're testing here is that "stopped" shows up
673 # "all on its own".
674 LOOKING_FOR = "stopped"
675 for i in range(500):
676 if LOOKING_FOR in repr(t):
677 break
678 time.sleep(0.01)
679 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700680 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000681
Tim Peters7634e1c2013-10-08 20:55:51 -0500682 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500683 # BoundedSemaphore should raise ValueError if released too often.
684 for limit in range(1, 10):
685 bs = threading.BoundedSemaphore(limit)
686 threads = [threading.Thread(target=bs.acquire)
687 for _ in range(limit)]
688 for t in threads:
689 t.start()
690 for t in threads:
691 t.join()
692 threads = [threading.Thread(target=bs.release)
693 for _ in range(limit)]
694 for t in threads:
695 t.start()
696 for t in threads:
697 t.join()
698 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500699
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200700 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100701 def test_frame_tstate_tracing(self):
702 # Issue #14432: Crash when a generator is created in a C thread that is
703 # destroyed while the generator is still used. The issue was that a
704 # generator contains a frame, and the frame kept a reference to the
705 # Python state of the destroyed C thread. The crash occurs when a trace
706 # function is setup.
707
708 def noop_trace(frame, event, arg):
709 # no operation
710 return noop_trace
711
712 def generator():
713 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300714 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100715
716 def callback():
717 if callback.gen is None:
718 callback.gen = generator()
719 return next(callback.gen)
720 callback.gen = None
721
722 old_trace = sys.gettrace()
723 sys.settrace(noop_trace)
724 try:
725 # Install a trace function
726 threading.settrace(noop_trace)
727
728 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200729 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100730 _testcapi.call_in_temporary_c_thread(callback)
731
732 # Call the generator in a different Python thread, check that the
733 # generator didn't keep a reference to the destroyed thread state
734 for test in range(3):
735 # The trace function is still called here
736 callback()
737 finally:
738 sys.settrace(old_trace)
739
Victor Stinner6f75c872019-06-13 12:06:24 +0200740 @cpython_only
741 def test_shutdown_locks(self):
742 for daemon in (False, True):
743 with self.subTest(daemon=daemon):
744 event = threading.Event()
745 thread = threading.Thread(target=event.wait, daemon=daemon)
746
747 # Thread.start() must add lock to _shutdown_locks,
748 # but only for non-daemon thread
749 thread.start()
750 tstate_lock = thread._tstate_lock
751 if not daemon:
752 self.assertIn(tstate_lock, threading._shutdown_locks)
753 else:
754 self.assertNotIn(tstate_lock, threading._shutdown_locks)
755
756 # unblock the thread and join it
757 event.set()
758 thread.join()
759
760 # Thread._stop() must remove tstate_lock from _shutdown_locks.
761 # Daemon threads must never add it to _shutdown_locks.
762 self.assertNotIn(tstate_lock, threading._shutdown_locks)
763
Victor Stinner45956b92013-11-12 16:37:55 +0100764
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000765class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000766
767 def _run_and_join(self, script):
768 script = """if 1:
769 import sys, os, time, threading
770
771 # a thread, which waits for the main program to terminate
772 def joiningfunc(mainthread):
773 mainthread.join()
774 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000775 # stdout is fully buffered because not a tty, we have to flush
776 # before exit.
777 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000778 \n""" + script
779
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200780 rc, out, err = assert_python_ok("-c", script)
781 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000782 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000783
784 def test_1_join_on_shutdown(self):
785 # The usual case: on exit, wait for a non-daemon thread
786 script = """if 1:
787 import os
788 t = threading.Thread(target=joiningfunc,
789 args=(threading.current_thread(),))
790 t.start()
791 time.sleep(0.1)
792 print('end of main')
793 """
794 self._run_and_join(script)
795
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000796 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200797 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000798 def test_2_join_in_forked_process(self):
799 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000800 script = """if 1:
801 childpid = os.fork()
802 if childpid != 0:
803 os.waitpid(childpid, 0)
804 sys.exit(0)
805
806 t = threading.Thread(target=joiningfunc,
807 args=(threading.current_thread(),))
808 t.start()
809 print('end of main')
810 """
811 self._run_and_join(script)
812
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000813 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200814 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000815 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000816 # Like the test above, but fork() was called from a worker thread
817 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000818
Jesse Nollera8513972008-07-17 16:49:17 +0000819 script = """if 1:
820 main_thread = threading.current_thread()
821 def worker():
822 childpid = os.fork()
823 if childpid != 0:
824 os.waitpid(childpid, 0)
825 sys.exit(0)
826
827 t = threading.Thread(target=joiningfunc,
828 args=(main_thread,))
829 print('end of main')
830 t.start()
831 t.join() # Should not block: main_thread is already stopped
832
833 w = threading.Thread(target=worker)
834 w.start()
835 """
836 self._run_and_join(script)
837
Victor Stinner26d31862011-07-01 14:26:24 +0200838 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500839 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200840 # Check that a daemon thread cannot crash the interpreter on shutdown
841 # by manipulating internal structures that are being disposed of in
842 # the main thread.
843 script = """if True:
844 import os
845 import random
846 import sys
847 import time
848 import threading
849
850 thread_has_run = set()
851
852 def random_io():
853 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200854 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200855 with open(os.__file__, 'rb') as in_f:
856 stuff = in_f.read(200)
857 with open(os.devnull, 'wb') as null_f:
858 null_f.write(stuff)
859 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200860 thread_has_run.add(threading.current_thread())
861
862 def main():
863 count = 0
864 for _ in range(40):
865 new_thread = threading.Thread(target=random_io)
866 new_thread.daemon = True
867 new_thread.start()
868 count += 1
869 while len(thread_has_run) < count:
870 time.sleep(0.001)
871 # Trigger process shutdown
872 sys.exit(0)
873
874 main()
875 """
876 rc, out, err = assert_python_ok('-c', script)
877 self.assertFalse(err)
878
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100879 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100880 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100881 def test_reinit_tls_after_fork(self):
882 # Issue #13817: fork() would deadlock in a multithreaded program with
883 # the ad-hoc TLS implementation.
884
885 def do_fork_and_wait():
886 # just fork a child process and wait it
887 pid = os.fork()
888 if pid > 0:
889 os.waitpid(pid, 0)
890 else:
891 os._exit(0)
892
893 # start a bunch of threads that will fork() child processes
894 threads = []
895 for i in range(16):
896 t = threading.Thread(target=do_fork_and_wait)
897 threads.append(t)
898 t.start()
899
900 for t in threads:
901 t.join()
902
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200903 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
904 def test_clear_threads_states_after_fork(self):
905 # Issue #17094: check that threads states are cleared after fork()
906
907 # start a bunch of threads
908 threads = []
909 for i in range(16):
910 t = threading.Thread(target=lambda : time.sleep(0.3))
911 threads.append(t)
912 t.start()
913
914 pid = os.fork()
915 if pid == 0:
916 # check that threads states have been cleared
917 if len(sys._current_frames()) == 1:
918 os._exit(0)
919 else:
920 os._exit(1)
921 else:
922 _, status = os.waitpid(pid, 0)
923 self.assertEqual(0, status)
924
925 for t in threads:
926 t.join()
927
Jesse Nollera8513972008-07-17 16:49:17 +0000928
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200929class SubinterpThreadingTests(BaseTestCase):
Victor Stinner066e5b12019-06-14 18:55:22 +0200930 def pipe(self):
931 r, w = os.pipe()
932 self.addCleanup(os.close, r)
933 self.addCleanup(os.close, w)
934 if hasattr(os, 'set_blocking'):
935 os.set_blocking(r, False)
936 return (r, w)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200937
938 def test_threads_join(self):
939 # Non-daemon threads should be joined at subinterpreter shutdown
940 # (issue #18808)
Victor Stinner066e5b12019-06-14 18:55:22 +0200941 r, w = self.pipe()
942 code = textwrap.dedent(r"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200943 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200944 import random
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200945 import threading
946 import time
947
Victor Stinner468e5fe2019-06-13 01:30:17 +0200948 def random_sleep():
949 seconds = random.random() * 0.010
950 time.sleep(seconds)
951
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200952 def f():
953 # Sleep a bit so that the thread is still running when
954 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200955 random_sleep()
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200956 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200957
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200958 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200959 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200960 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100961 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200962 self.assertEqual(ret, 0)
963 # The thread was joined properly.
964 self.assertEqual(os.read(r, 1), b"x")
965
Antoine Pitrou7b476992013-09-07 23:38:37 +0200966 def test_threads_join_2(self):
967 # Same as above, but a delay gets introduced after the thread's
968 # Python code returned but before the thread state is deleted.
969 # To achieve this, we register a thread-local object which sleeps
970 # a bit when deallocated.
Victor Stinner066e5b12019-06-14 18:55:22 +0200971 r, w = self.pipe()
972 code = textwrap.dedent(r"""
Antoine Pitrou7b476992013-09-07 23:38:37 +0200973 import os
Victor Stinner468e5fe2019-06-13 01:30:17 +0200974 import random
Antoine Pitrou7b476992013-09-07 23:38:37 +0200975 import threading
976 import time
977
Victor Stinner468e5fe2019-06-13 01:30:17 +0200978 def random_sleep():
979 seconds = random.random() * 0.010
980 time.sleep(seconds)
981
Antoine Pitrou7b476992013-09-07 23:38:37 +0200982 class Sleeper:
983 def __del__(self):
Victor Stinner468e5fe2019-06-13 01:30:17 +0200984 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200985
986 tls = threading.local()
987
988 def f():
989 # Sleep a bit so that the thread is still running when
990 # Py_EndInterpreter is called.
Victor Stinner468e5fe2019-06-13 01:30:17 +0200991 random_sleep()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200992 tls.x = Sleeper()
993 os.write(%d, b"x")
Victor Stinner468e5fe2019-06-13 01:30:17 +0200994
Antoine Pitrou7b476992013-09-07 23:38:37 +0200995 threading.Thread(target=f).start()
Victor Stinner468e5fe2019-06-13 01:30:17 +0200996 random_sleep()
Victor Stinner066e5b12019-06-14 18:55:22 +0200997 """ % (w,))
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100998 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200999 self.assertEqual(ret, 0)
1000 # The thread was joined properly.
1001 self.assertEqual(os.read(r, 1), b"x")
1002
Victor Stinner066e5b12019-06-14 18:55:22 +02001003 def test_daemon_thread(self):
1004 r, w = self.pipe()
1005 code = textwrap.dedent(f"""
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001006 import threading
Victor Stinner066e5b12019-06-14 18:55:22 +02001007 import sys
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001008
Victor Stinner066e5b12019-06-14 18:55:22 +02001009 channel = open({w}, "w", closefd=False)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001010
Victor Stinner066e5b12019-06-14 18:55:22 +02001011 def func():
1012 pass
1013
1014 thread = threading.Thread(target=func, daemon=True)
1015 try:
1016 thread.start()
1017 except RuntimeError as exc:
1018 print("ok: %s" % exc, file=channel, flush=True)
1019 else:
1020 thread.join()
1021 print("fail: RuntimeError not raised", file=channel, flush=True)
1022 """)
1023 ret = test.support.run_in_subinterp(code)
1024 self.assertEqual(ret, 0)
1025
1026 msg = os.read(r, 100).decode().rstrip()
1027 self.assertEqual("ok: daemon thread are not supported "
1028 "in subinterpreters", msg)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +02001029
1030
Antoine Pitroub0e9bd42009-10-27 20:05:26 +00001031class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001032 # A RuntimeError should be raised if Thread.start() is called
1033 # multiple times.
1034 def test_start_thread_again(self):
1035 thread = threading.Thread()
1036 thread.start()
1037 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001038 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001039
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001040 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +00001041 current_thread = threading.current_thread()
1042 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001043
1044 def test_joining_inactive_thread(self):
1045 thread = threading.Thread()
1046 self.assertRaises(RuntimeError, thread.join)
1047
1048 def test_daemonize_active_thread(self):
1049 thread = threading.Thread()
1050 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +00001051 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -07001052 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001053
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001054 def test_releasing_unacquired_lock(self):
1055 lock = threading.Lock()
1056 self.assertRaises(RuntimeError, lock.release)
1057
Ned Deily9a7c5242011-05-28 00:19:56 -07001058 def test_recursion_limit(self):
1059 # Issue 9670
1060 # test that excessive recursion within a non-main thread causes
1061 # an exception rather than crashing the interpreter on platforms
1062 # like Mac OS X or FreeBSD which have small default stack sizes
1063 # for threads
1064 script = """if True:
1065 import threading
1066
1067 def recurse():
1068 return recurse()
1069
1070 def outer():
1071 try:
1072 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001073 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -07001074 pass
1075
1076 w = threading.Thread(target=outer)
1077 w.start()
1078 w.join()
1079 print('end of main thread')
1080 """
1081 expected_output = "end of main thread\n"
1082 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001083 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001084 stdout, stderr = p.communicate()
1085 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001086 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001087 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001088
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001089 def test_print_exception(self):
1090 script = r"""if True:
1091 import threading
1092 import time
1093
1094 running = False
1095 def run():
1096 global running
1097 running = True
1098 while running:
1099 time.sleep(0.01)
1100 1/0
1101 t = threading.Thread(target=run)
1102 t.start()
1103 while not running:
1104 time.sleep(0.01)
1105 running = False
1106 t.join()
1107 """
1108 rc, out, err = assert_python_ok("-c", script)
1109 self.assertEqual(out, b'')
1110 err = err.decode()
1111 self.assertIn("Exception in thread", err)
1112 self.assertIn("Traceback (most recent call last):", err)
1113 self.assertIn("ZeroDivisionError", err)
1114 self.assertNotIn("Unhandled exception", err)
1115
Serhiy Storchakaa7930372016-07-03 22:27:26 +03001116 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001117 def test_print_exception_stderr_is_none_1(self):
1118 script = r"""if True:
1119 import sys
1120 import threading
1121 import time
1122
1123 running = False
1124 def run():
1125 global running
1126 running = True
1127 while running:
1128 time.sleep(0.01)
1129 1/0
1130 t = threading.Thread(target=run)
1131 t.start()
1132 while not running:
1133 time.sleep(0.01)
1134 sys.stderr = None
1135 running = False
1136 t.join()
1137 """
1138 rc, out, err = assert_python_ok("-c", script)
1139 self.assertEqual(out, b'')
1140 err = err.decode()
1141 self.assertIn("Exception in thread", err)
1142 self.assertIn("Traceback (most recent call last):", err)
1143 self.assertIn("ZeroDivisionError", err)
1144 self.assertNotIn("Unhandled exception", err)
1145
1146 def test_print_exception_stderr_is_none_2(self):
1147 script = r"""if True:
1148 import sys
1149 import threading
1150 import time
1151
1152 running = False
1153 def run():
1154 global running
1155 running = True
1156 while running:
1157 time.sleep(0.01)
1158 1/0
1159 sys.stderr = None
1160 t = threading.Thread(target=run)
1161 t.start()
1162 while not running:
1163 time.sleep(0.01)
1164 running = False
1165 t.join()
1166 """
1167 rc, out, err = assert_python_ok("-c", script)
1168 self.assertEqual(out, b'')
1169 self.assertNotIn("Unhandled exception", err.decode())
1170
Victor Stinnereec93312016-08-18 18:13:10 +02001171 def test_bare_raise_in_brand_new_thread(self):
1172 def bare_raise():
1173 raise
1174
1175 class Issue27558(threading.Thread):
1176 exc = None
1177
1178 def run(self):
1179 try:
1180 bare_raise()
1181 except Exception as exc:
1182 self.exc = exc
1183
1184 thread = Issue27558()
1185 thread.start()
1186 thread.join()
1187 self.assertIsNotNone(thread.exc)
1188 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001189 # explicitly break the reference cycle to not leak a dangling thread
1190 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001191
Victor Stinnercd590a72019-05-28 00:39:52 +02001192
1193class ThreadRunFail(threading.Thread):
1194 def run(self):
1195 raise ValueError("run failed")
1196
1197
1198class ExceptHookTests(BaseTestCase):
1199 def test_excepthook(self):
1200 with support.captured_output("stderr") as stderr:
1201 thread = ThreadRunFail(name="excepthook thread")
1202 thread.start()
1203 thread.join()
1204
1205 stderr = stderr.getvalue().strip()
1206 self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
1207 self.assertIn('Traceback (most recent call last):\n', stderr)
1208 self.assertIn(' raise ValueError("run failed")', stderr)
1209 self.assertIn('ValueError: run failed', stderr)
1210
1211 @support.cpython_only
1212 def test_excepthook_thread_None(self):
1213 # threading.excepthook called with thread=None: log the thread
1214 # identifier in this case.
1215 with support.captured_output("stderr") as stderr:
1216 try:
1217 raise ValueError("bug")
1218 except Exception as exc:
1219 args = threading.ExceptHookArgs([*sys.exc_info(), None])
Victor Stinnercdce0572019-06-02 23:08:41 +02001220 try:
1221 threading.excepthook(args)
1222 finally:
1223 # Explicitly break a reference cycle
1224 args = None
Victor Stinnercd590a72019-05-28 00:39:52 +02001225
1226 stderr = stderr.getvalue().strip()
1227 self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
1228 self.assertIn('Traceback (most recent call last):\n', stderr)
1229 self.assertIn(' raise ValueError("bug")', stderr)
1230 self.assertIn('ValueError: bug', stderr)
1231
1232 def test_system_exit(self):
1233 class ThreadExit(threading.Thread):
1234 def run(self):
1235 sys.exit(1)
1236
1237 # threading.excepthook() silently ignores SystemExit
1238 with support.captured_output("stderr") as stderr:
1239 thread = ThreadExit()
1240 thread.start()
1241 thread.join()
1242
1243 self.assertEqual(stderr.getvalue(), '')
1244
1245 def test_custom_excepthook(self):
1246 args = None
1247
1248 def hook(hook_args):
1249 nonlocal args
1250 args = hook_args
1251
1252 try:
1253 with support.swap_attr(threading, 'excepthook', hook):
1254 thread = ThreadRunFail()
1255 thread.start()
1256 thread.join()
1257
1258 self.assertEqual(args.exc_type, ValueError)
1259 self.assertEqual(str(args.exc_value), 'run failed')
1260 self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
1261 self.assertIs(args.thread, thread)
1262 finally:
1263 # Break reference cycle
1264 args = None
1265
1266 def test_custom_excepthook_fail(self):
1267 def threading_hook(args):
1268 raise ValueError("threading_hook failed")
1269
1270 err_str = None
1271
1272 def sys_hook(exc_type, exc_value, exc_traceback):
1273 nonlocal err_str
1274 err_str = str(exc_value)
1275
1276 with support.swap_attr(threading, 'excepthook', threading_hook), \
1277 support.swap_attr(sys, 'excepthook', sys_hook), \
1278 support.captured_output('stderr') as stderr:
1279 thread = ThreadRunFail()
1280 thread.start()
1281 thread.join()
1282
1283 self.assertEqual(stderr.getvalue(),
1284 'Exception in threading.excepthook:\n')
1285 self.assertEqual(err_str, 'threading_hook failed')
1286
1287
R David Murray19aeb432013-03-30 17:19:38 -04001288class TimerTests(BaseTestCase):
1289
1290 def setUp(self):
1291 BaseTestCase.setUp(self)
1292 self.callback_args = []
1293 self.callback_event = threading.Event()
1294
1295 def test_init_immutable_default_args(self):
1296 # Issue 17435: constructor defaults were mutable objects, they could be
1297 # mutated via the object attributes and affect other Timer objects.
1298 timer1 = threading.Timer(0.01, self._callback_spy)
1299 timer1.start()
1300 self.callback_event.wait()
1301 timer1.args.append("blah")
1302 timer1.kwargs["foo"] = "bar"
1303 self.callback_event.clear()
1304 timer2 = threading.Timer(0.01, self._callback_spy)
1305 timer2.start()
1306 self.callback_event.wait()
1307 self.assertEqual(len(self.callback_args), 2)
1308 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001309 timer1.join()
1310 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001311
1312 def _callback_spy(self, *args, **kwargs):
1313 self.callback_args.append((args[:], kwargs.copy()))
1314 self.callback_event.set()
1315
Antoine Pitrou557934f2009-11-06 22:41:14 +00001316class LockTests(lock_tests.LockTests):
1317 locktype = staticmethod(threading.Lock)
1318
Antoine Pitrou434736a2009-11-10 18:46:01 +00001319class PyRLockTests(lock_tests.RLockTests):
1320 locktype = staticmethod(threading._PyRLock)
1321
Charles-François Natali6b671b22012-01-28 11:36:04 +01001322@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001323class CRLockTests(lock_tests.RLockTests):
1324 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001325
1326class EventTests(lock_tests.EventTests):
1327 eventtype = staticmethod(threading.Event)
1328
1329class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001330 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001331 locktype = staticmethod(threading.Condition)
1332
1333class ConditionTests(lock_tests.ConditionTests):
1334 condtype = staticmethod(threading.Condition)
1335
1336class SemaphoreTests(lock_tests.SemaphoreTests):
1337 semtype = staticmethod(threading.Semaphore)
1338
1339class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1340 semtype = staticmethod(threading.BoundedSemaphore)
1341
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001342class BarrierTests(lock_tests.BarrierTests):
1343 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001344
Matěj Cepl608876b2019-05-23 22:30:00 +02001345
Martin Panter19e69c52015-11-14 12:46:42 +00001346class MiscTestCase(unittest.TestCase):
1347 def test__all__(self):
1348 extra = {"ThreadError"}
1349 blacklist = {'currentThread', 'activeCount'}
1350 support.check__all__(self, threading, ('threading', '_thread'),
1351 extra=extra, blacklist=blacklist)
1352
Matěj Cepl608876b2019-05-23 22:30:00 +02001353
1354class InterruptMainTests(unittest.TestCase):
1355 def test_interrupt_main_subthread(self):
1356 # Calling start_new_thread with a function that executes interrupt_main
1357 # should raise KeyboardInterrupt upon completion.
1358 def call_interrupt():
1359 _thread.interrupt_main()
1360 t = threading.Thread(target=call_interrupt)
1361 with self.assertRaises(KeyboardInterrupt):
1362 t.start()
1363 t.join()
1364 t.join()
1365
1366 def test_interrupt_main_mainthread(self):
1367 # Make sure that if interrupt_main is called in main thread that
1368 # KeyboardInterrupt is raised instantly.
1369 with self.assertRaises(KeyboardInterrupt):
1370 _thread.interrupt_main()
1371
1372 def test_interrupt_main_noerror(self):
1373 handler = signal.getsignal(signal.SIGINT)
1374 try:
1375 # No exception should arise.
1376 signal.signal(signal.SIGINT, signal.SIG_IGN)
1377 _thread.interrupt_main()
1378
1379 signal.signal(signal.SIGINT, signal.SIG_DFL)
1380 _thread.interrupt_main()
1381 finally:
1382 # Restore original handler
1383 signal.signal(signal.SIGINT, handler)
1384
1385
Tim Peters84d54892005-01-08 06:03:17 +00001386if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001387 unittest.main()