blob: 33a25f3b9d235d8043422bca88d2d36ecff38138 [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
Skip Montanaro4533f602001-08-20 20:28:48 +000019
Antoine Pitrou557934f2009-11-06 22:41:14 +000020from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000021from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000022
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030023
24# Between fork() and exec(), only async-safe functions are allowed (issues
25# #12316 and #11870), and fork() from a worker thread is known to trigger
26# problems with some operating systems (issue #3863): skip problematic tests
27# on platforms known to behave badly.
Victor Stinner13ff2452018-01-22 18:32:50 +010028platforms_to_skip = ('netbsd5', 'hp-ux11')
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030029
30
Tim Peters84d54892005-01-08 06:03:17 +000031# A trivial mutable counter.
32class Counter(object):
33 def __init__(self):
34 self.value = 0
35 def inc(self):
36 self.value += 1
37 def dec(self):
38 self.value -= 1
39 def get(self):
40 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000041
42class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000043 def __init__(self, name, testcase, sema, mutex, nrunning):
44 threading.Thread.__init__(self, name=name)
45 self.testcase = testcase
46 self.sema = sema
47 self.mutex = mutex
48 self.nrunning = nrunning
49
Skip Montanaro4533f602001-08-20 20:28:48 +000050 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000051 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000052 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000053 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000054 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000055
Christian Heimes4fbc72b2008-03-22 00:47:35 +000056 with self.sema:
57 with self.mutex:
58 self.nrunning.inc()
59 if verbose:
60 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020061 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000062
Christian Heimes4fbc72b2008-03-22 00:47:35 +000063 time.sleep(delay)
64 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000065 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000066
Christian Heimes4fbc72b2008-03-22 00:47:35 +000067 with self.mutex:
68 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020069 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000070 if verbose:
71 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000072 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000073
Skip Montanaro4533f602001-08-20 20:28:48 +000074
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000075class BaseTestCase(unittest.TestCase):
76 def setUp(self):
77 self._threads = test.support.threading_setup()
78
79 def tearDown(self):
80 test.support.threading_cleanup(*self._threads)
81 test.support.reap_children()
82
83
84class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000085
Tim Peters84d54892005-01-08 06:03:17 +000086 # Create a bunch of threads, let each do some work, wait until all are
87 # done.
88 def test_various_ops(self):
89 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
90 # times about 1 second per clump).
91 NUMTASKS = 10
92
93 # no more than 3 of the 10 can run at once
94 sema = threading.BoundedSemaphore(value=3)
95 mutex = threading.RLock()
96 numrunning = Counter()
97
98 threads = []
99
100 for i in range(NUMTASKS):
101 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
102 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200103 self.assertIsNone(t.ident)
104 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000105 t.start()
106
Jake Teslerb121f632019-05-22 08:43:17 -0700107 if hasattr(threading, 'get_native_id'):
108 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
109 self.assertNotIn(None, native_ids)
110 self.assertEqual(len(native_ids), NUMTASKS + 1)
111
Tim Peters84d54892005-01-08 06:03:17 +0000112 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000113 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000114 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200115 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200116 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000117 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200118 self.assertIsNotNone(t.ident)
119 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000120 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000121 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000122 self.assertEqual(numrunning.get(), 0)
123
Benjamin Petersond23f8222009-04-05 19:13:16 +0000124 def test_ident_of_no_threading_threads(self):
125 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200126 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000127 def f():
128 ident.append(threading.currentThread().ident)
129 done.set()
130 done = threading.Event()
131 ident = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700132 with support.wait_threads_exit():
133 tid = _thread.start_new_thread(f, ())
134 done.wait()
135 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000136 # Kill the "immortal" _DummyThread
137 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000138
Victor Stinner8c663fd2017-11-08 14:44:44 -0800139 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140 def test_various_ops_small_stack(self):
141 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800142 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 try:
144 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000145 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000146 raise unittest.SkipTest(
147 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148 self.test_various_ops()
149 threading.stack_size(0)
150
Victor Stinner8c663fd2017-11-08 14:44:44 -0800151 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000152 def test_various_ops_large_stack(self):
153 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800154 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 try:
156 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000157 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000158 raise unittest.SkipTest(
159 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160 self.test_various_ops()
161 threading.stack_size(0)
162
Tim Peters711906e2005-01-08 07:30:42 +0000163 def test_foreign_thread(self):
164 # Check that a "foreign" thread can use the threading module.
165 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000166 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000167 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000168 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000169 mutex.release()
170
171 mutex = threading.Lock()
172 mutex.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700173 with support.wait_threads_exit():
174 tid = _thread.start_new_thread(f, (mutex,))
175 # Wait for the thread to finish.
176 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000177 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000178 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800179 #Issue 29376
180 self.assertTrue(threading._active[tid].is_alive())
181 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000182 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000183
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000184 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
185 # exposed at the Python level. This test relies on ctypes to get at it.
186 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200187 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000188
189 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200190 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191
192 class AsyncExc(Exception):
193 pass
194
195 exception = ctypes.py_object(AsyncExc)
196
Antoine Pitroube4d8092009-10-18 18:27:17 +0000197 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200198 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200199 self.assertIsInstance(tid, int)
200 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000201
202 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200203 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000204 # The exception is async, so we might have to keep the VM busy until
205 # it notices.
206 while True:
207 pass
208 except AsyncExc:
209 pass
210 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000211 # This code is unreachable but it reflects the intent. If we wanted
212 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000213 self.fail("AsyncExc not raised")
214 try:
215 self.assertEqual(result, 1) # one thread state modified
216 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000217 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000218 pass
219
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220 # `worker_started` is set by the thread when it's inside a try/except
221 # block waiting to catch the asynchronously set AsyncExc exception.
222 # `worker_saw_exception` is set by the thread upon catching that
223 # exception.
224 worker_started = threading.Event()
225 worker_saw_exception = threading.Event()
226
227 class Worker(threading.Thread):
228 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200229 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000230 self.finished = False
231
232 try:
233 while True:
234 worker_started.set()
235 time.sleep(0.1)
236 except AsyncExc:
237 self.finished = True
238 worker_saw_exception.set()
239
240 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000241 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000242 t.start()
243 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245
246 # Try a thread id that doesn't make sense.
247 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000248 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200249 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000250 self.assertEqual(result, 0) # no thread states modified
251
252 # Now raise an exception in the worker thread.
253 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000254 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000255 ret = worker_started.wait()
256 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000257 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000258 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200259 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000260 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000261 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200262 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000263 self.assertEqual(result, 1) # one thread state modified
264 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000265 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000266 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000268 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000269 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000270 if t.finished:
271 t.join()
272 # else the thread is still running, and we have no way to kill it
273
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000274 def test_limbo_cleanup(self):
275 # Issue 7481: Failure to start thread should cleanup the limbo map.
276 def fail_new_thread(*args):
277 raise threading.ThreadError()
278 _start_new_thread = threading._start_new_thread
279 threading._start_new_thread = fail_new_thread
280 try:
281 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000282 self.assertRaises(threading.ThreadError, t.start)
283 self.assertFalse(
284 t in threading._limbo,
285 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000286 finally:
287 threading._start_new_thread = _start_new_thread
288
Christian Heimes7d2ff882007-11-30 14:35:04 +0000289 def test_finalize_runnning_thread(self):
290 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
291 # very late on python exit: on deallocation of a running thread for
292 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200293 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000294
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200295 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000296 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000297
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000298 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000299 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000300 ready.acquire()
301
Christian Heimes7d2ff882007-11-30 14:35:04 +0000302 # Module globals are cleared before __del__ is run
303 # So we save the functions in class dict
304 class C:
305 ensure = ctypes.pythonapi.PyGILState_Ensure
306 release = ctypes.pythonapi.PyGILState_Release
307 def __del__(self):
308 state = self.ensure()
309 self.release(state)
310
311 def waitingThread():
312 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000313 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000314 time.sleep(100)
315
Georg Brandl2067bfd2008-05-25 13:05:15 +0000316 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000317 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000318 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200319 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000320 self.assertEqual(rc, 42)
321
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000322 def test_finalize_with_trace(self):
323 # Issue1733757
324 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200325 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000326 import sys, threading
327
328 # A deadlock-killer, to prevent the
329 # testsuite to hang forever
330 def killer():
331 import os, time
332 time.sleep(2)
333 print('program blocked; aborting')
334 os._exit(2)
335 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000336 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000337 t.start()
338
339 # This is the trace function
340 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000341 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000342 return func
343
344 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200345 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000346
Antoine Pitrou011bd622009-10-20 21:52:47 +0000347 def test_join_nondaemon_on_shutdown(self):
348 # Issue 1722344
349 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200350 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000351 import threading
352 from time import sleep
353
354 def child():
355 sleep(1)
356 # As a non-daemon thread we SHOULD wake up and nothing
357 # should be torn down yet
358 print("Woke up, sleep function is:", sleep)
359
360 threading.Thread(target=child).start()
361 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200362 """)
363 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000364 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200365 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000366
Christian Heimes1af737c2008-01-23 08:24:23 +0000367 def test_enumerate_after_join(self):
368 # Try hard to trigger #1703448: a thread is still returned in
369 # threading.enumerate() after it has been join()ed.
370 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000371 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000372 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000373 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000374 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000375 t = threading.Thread(target=lambda: None)
376 t.start()
377 t.join()
378 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000379 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000380 "#1703448 triggered after %d trials: %s" % (i, l))
381 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000382 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000383
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000384 def test_no_refcycle_through_target(self):
385 class RunSelfFunction(object):
386 def __init__(self, should_raise):
387 # The links in this refcycle from Thread back to self
388 # should be cleaned up when the thread completes.
389 self.should_raise = should_raise
390 self.thread = threading.Thread(target=self._run,
391 args=(self,),
392 kwargs={'yet_another':self})
393 self.thread.start()
394
395 def _run(self, other_ref, yet_another):
396 if self.should_raise:
397 raise SystemExit
398
399 cyclic_object = RunSelfFunction(should_raise=False)
400 weak_cyclic_object = weakref.ref(cyclic_object)
401 cyclic_object.thread.join()
402 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000403 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000404 msg=('%d references still around' %
405 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000406
407 raising_cyclic_object = RunSelfFunction(should_raise=True)
408 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
409 raising_cyclic_object.thread.join()
410 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000411 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000412 msg=('%d references still around' %
413 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000414
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000415 def test_old_threading_api(self):
416 # Just a quick sanity check to make sure the old method names are
417 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000418 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000419 t.isDaemon()
420 t.setDaemon(True)
421 t.getName()
422 t.setName("name")
Dong-hee Na89669ff2019-01-17 21:14:45 +0900423 with self.assertWarnsRegex(DeprecationWarning, 'use is_alive()'):
424 t.isAlive()
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
Antoine Pitrou7b476992013-09-07 23:38:37 +0200585 def test_tstate_lock(self):
586 # Test an implementation detail of Thread objects.
587 started = _thread.allocate_lock()
588 finish = _thread.allocate_lock()
589 started.acquire()
590 finish.acquire()
591 def f():
592 started.release()
593 finish.acquire()
594 time.sleep(0.01)
595 # The tstate lock is None until the thread is started
596 t = threading.Thread(target=f)
597 self.assertIs(t._tstate_lock, None)
598 t.start()
599 started.acquire()
600 self.assertTrue(t.is_alive())
601 # The tstate lock can't be acquired when the thread is running
602 # (or suspended).
603 tstate_lock = t._tstate_lock
604 self.assertFalse(tstate_lock.acquire(timeout=0), False)
605 finish.release()
606 # When the thread ends, the state_lock can be successfully
607 # acquired.
608 self.assertTrue(tstate_lock.acquire(timeout=5), False)
609 # But is_alive() is still True: we hold _tstate_lock now, which
610 # prevents is_alive() from knowing the thread's end-of-life C code
611 # is done.
612 self.assertTrue(t.is_alive())
613 # Let is_alive() find out the C code is done.
614 tstate_lock.release()
615 self.assertFalse(t.is_alive())
616 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200617 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700618 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200619
Tim Peters72460fa2013-09-09 18:48:24 -0500620 def test_repr_stopped(self):
621 # Verify that "stopped" shows up in repr(Thread) appropriately.
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 t = threading.Thread(target=f)
630 t.start()
631 started.acquire()
632 self.assertIn("started", repr(t))
633 finish.release()
634 # "stopped" should appear in the repr in a reasonable amount of time.
635 # Implementation detail: as of this writing, that's trivially true
636 # if .join() is called, and almost trivially true if .is_alive() is
637 # called. The detail we're testing here is that "stopped" shows up
638 # "all on its own".
639 LOOKING_FOR = "stopped"
640 for i in range(500):
641 if LOOKING_FOR in repr(t):
642 break
643 time.sleep(0.01)
644 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700645 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000646
Tim Peters7634e1c2013-10-08 20:55:51 -0500647 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500648 # BoundedSemaphore should raise ValueError if released too often.
649 for limit in range(1, 10):
650 bs = threading.BoundedSemaphore(limit)
651 threads = [threading.Thread(target=bs.acquire)
652 for _ in range(limit)]
653 for t in threads:
654 t.start()
655 for t in threads:
656 t.join()
657 threads = [threading.Thread(target=bs.release)
658 for _ in range(limit)]
659 for t in threads:
660 t.start()
661 for t in threads:
662 t.join()
663 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500664
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200665 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100666 def test_frame_tstate_tracing(self):
667 # Issue #14432: Crash when a generator is created in a C thread that is
668 # destroyed while the generator is still used. The issue was that a
669 # generator contains a frame, and the frame kept a reference to the
670 # Python state of the destroyed C thread. The crash occurs when a trace
671 # function is setup.
672
673 def noop_trace(frame, event, arg):
674 # no operation
675 return noop_trace
676
677 def generator():
678 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300679 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100680
681 def callback():
682 if callback.gen is None:
683 callback.gen = generator()
684 return next(callback.gen)
685 callback.gen = None
686
687 old_trace = sys.gettrace()
688 sys.settrace(noop_trace)
689 try:
690 # Install a trace function
691 threading.settrace(noop_trace)
692
693 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200694 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100695 _testcapi.call_in_temporary_c_thread(callback)
696
697 # Call the generator in a different Python thread, check that the
698 # generator didn't keep a reference to the destroyed thread state
699 for test in range(3):
700 # The trace function is still called here
701 callback()
702 finally:
703 sys.settrace(old_trace)
704
Victor Stinner45956b92013-11-12 16:37:55 +0100705
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000706class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000707
708 def _run_and_join(self, script):
709 script = """if 1:
710 import sys, os, time, threading
711
712 # a thread, which waits for the main program to terminate
713 def joiningfunc(mainthread):
714 mainthread.join()
715 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000716 # stdout is fully buffered because not a tty, we have to flush
717 # before exit.
718 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000719 \n""" + script
720
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200721 rc, out, err = assert_python_ok("-c", script)
722 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000723 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000724
725 def test_1_join_on_shutdown(self):
726 # The usual case: on exit, wait for a non-daemon thread
727 script = """if 1:
728 import os
729 t = threading.Thread(target=joiningfunc,
730 args=(threading.current_thread(),))
731 t.start()
732 time.sleep(0.1)
733 print('end of main')
734 """
735 self._run_and_join(script)
736
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000737 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200738 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000739 def test_2_join_in_forked_process(self):
740 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000741 script = """if 1:
742 childpid = os.fork()
743 if childpid != 0:
744 os.waitpid(childpid, 0)
745 sys.exit(0)
746
747 t = threading.Thread(target=joiningfunc,
748 args=(threading.current_thread(),))
749 t.start()
750 print('end of main')
751 """
752 self._run_and_join(script)
753
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000754 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200755 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000756 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000757 # Like the test above, but fork() was called from a worker thread
758 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000759
Jesse Nollera8513972008-07-17 16:49:17 +0000760 script = """if 1:
761 main_thread = threading.current_thread()
762 def worker():
763 childpid = os.fork()
764 if childpid != 0:
765 os.waitpid(childpid, 0)
766 sys.exit(0)
767
768 t = threading.Thread(target=joiningfunc,
769 args=(main_thread,))
770 print('end of main')
771 t.start()
772 t.join() # Should not block: main_thread is already stopped
773
774 w = threading.Thread(target=worker)
775 w.start()
776 """
777 self._run_and_join(script)
778
Victor Stinner26d31862011-07-01 14:26:24 +0200779 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500780 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200781 # Check that a daemon thread cannot crash the interpreter on shutdown
782 # by manipulating internal structures that are being disposed of in
783 # the main thread.
784 script = """if True:
785 import os
786 import random
787 import sys
788 import time
789 import threading
790
791 thread_has_run = set()
792
793 def random_io():
794 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200795 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200796 with open(os.__file__, 'rb') as in_f:
797 stuff = in_f.read(200)
798 with open(os.devnull, 'wb') as null_f:
799 null_f.write(stuff)
800 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200801 thread_has_run.add(threading.current_thread())
802
803 def main():
804 count = 0
805 for _ in range(40):
806 new_thread = threading.Thread(target=random_io)
807 new_thread.daemon = True
808 new_thread.start()
809 count += 1
810 while len(thread_has_run) < count:
811 time.sleep(0.001)
812 # Trigger process shutdown
813 sys.exit(0)
814
815 main()
816 """
817 rc, out, err = assert_python_ok('-c', script)
818 self.assertFalse(err)
819
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100820 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100821 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100822 def test_reinit_tls_after_fork(self):
823 # Issue #13817: fork() would deadlock in a multithreaded program with
824 # the ad-hoc TLS implementation.
825
826 def do_fork_and_wait():
827 # just fork a child process and wait it
828 pid = os.fork()
829 if pid > 0:
830 os.waitpid(pid, 0)
831 else:
832 os._exit(0)
833
834 # start a bunch of threads that will fork() child processes
835 threads = []
836 for i in range(16):
837 t = threading.Thread(target=do_fork_and_wait)
838 threads.append(t)
839 t.start()
840
841 for t in threads:
842 t.join()
843
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200844 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
845 def test_clear_threads_states_after_fork(self):
846 # Issue #17094: check that threads states are cleared after fork()
847
848 # start a bunch of threads
849 threads = []
850 for i in range(16):
851 t = threading.Thread(target=lambda : time.sleep(0.3))
852 threads.append(t)
853 t.start()
854
855 pid = os.fork()
856 if pid == 0:
857 # check that threads states have been cleared
858 if len(sys._current_frames()) == 1:
859 os._exit(0)
860 else:
861 os._exit(1)
862 else:
863 _, status = os.waitpid(pid, 0)
864 self.assertEqual(0, status)
865
866 for t in threads:
867 t.join()
868
Jesse Nollera8513972008-07-17 16:49:17 +0000869
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200870class SubinterpThreadingTests(BaseTestCase):
871
872 def test_threads_join(self):
873 # Non-daemon threads should be joined at subinterpreter shutdown
874 # (issue #18808)
875 r, w = os.pipe()
876 self.addCleanup(os.close, r)
877 self.addCleanup(os.close, w)
878 code = r"""if 1:
879 import os
880 import threading
881 import time
882
883 def f():
884 # Sleep a bit so that the thread is still running when
885 # Py_EndInterpreter is called.
886 time.sleep(0.05)
887 os.write(%d, b"x")
888 threading.Thread(target=f).start()
889 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100890 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200891 self.assertEqual(ret, 0)
892 # The thread was joined properly.
893 self.assertEqual(os.read(r, 1), b"x")
894
Antoine Pitrou7b476992013-09-07 23:38:37 +0200895 def test_threads_join_2(self):
896 # Same as above, but a delay gets introduced after the thread's
897 # Python code returned but before the thread state is deleted.
898 # To achieve this, we register a thread-local object which sleeps
899 # a bit when deallocated.
900 r, w = os.pipe()
901 self.addCleanup(os.close, r)
902 self.addCleanup(os.close, w)
903 code = r"""if 1:
904 import os
905 import threading
906 import time
907
908 class Sleeper:
909 def __del__(self):
910 time.sleep(0.05)
911
912 tls = threading.local()
913
914 def f():
915 # Sleep a bit so that the thread is still running when
916 # Py_EndInterpreter is called.
917 time.sleep(0.05)
918 tls.x = Sleeper()
919 os.write(%d, b"x")
920 threading.Thread(target=f).start()
921 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100922 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200923 self.assertEqual(ret, 0)
924 # The thread was joined properly.
925 self.assertEqual(os.read(r, 1), b"x")
926
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200927 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200928 def test_daemon_threads_fatal_error(self):
929 subinterp_code = r"""if 1:
930 import os
931 import threading
932 import time
933
934 def f():
935 # Make sure the daemon thread is still running when
936 # Py_EndInterpreter is called.
937 time.sleep(10)
938 threading.Thread(target=f, daemon=True).start()
939 """
940 script = r"""if 1:
941 import _testcapi
942
943 _testcapi.run_in_subinterp(%r)
944 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200945 with test.support.SuppressCrashReport():
946 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200947 self.assertIn("Fatal Python error: Py_EndInterpreter: "
948 "not the last thread", err.decode())
949
950
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000951class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000952 # A RuntimeError should be raised if Thread.start() is called
953 # multiple times.
954 def test_start_thread_again(self):
955 thread = threading.Thread()
956 thread.start()
957 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700958 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000959
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000960 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000961 current_thread = threading.current_thread()
962 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000963
964 def test_joining_inactive_thread(self):
965 thread = threading.Thread()
966 self.assertRaises(RuntimeError, thread.join)
967
968 def test_daemonize_active_thread(self):
969 thread = threading.Thread()
970 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000971 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700972 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000973
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000974 def test_releasing_unacquired_lock(self):
975 lock = threading.Lock()
976 self.assertRaises(RuntimeError, lock.release)
977
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400978 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
979 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700980 def test_recursion_limit(self):
981 # Issue 9670
982 # test that excessive recursion within a non-main thread causes
983 # an exception rather than crashing the interpreter on platforms
984 # like Mac OS X or FreeBSD which have small default stack sizes
985 # for threads
986 script = """if True:
987 import threading
988
989 def recurse():
990 return recurse()
991
992 def outer():
993 try:
994 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400995 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700996 pass
997
998 w = threading.Thread(target=outer)
999 w.start()
1000 w.join()
1001 print('end of main thread')
1002 """
1003 expected_output = "end of main thread\n"
1004 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001005 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001006 stdout, stderr = p.communicate()
1007 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001008 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001009 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001010
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001011 def test_print_exception(self):
1012 script = r"""if True:
1013 import threading
1014 import time
1015
1016 running = False
1017 def run():
1018 global running
1019 running = True
1020 while running:
1021 time.sleep(0.01)
1022 1/0
1023 t = threading.Thread(target=run)
1024 t.start()
1025 while not running:
1026 time.sleep(0.01)
1027 running = False
1028 t.join()
1029 """
1030 rc, out, err = assert_python_ok("-c", script)
1031 self.assertEqual(out, b'')
1032 err = err.decode()
1033 self.assertIn("Exception in thread", err)
1034 self.assertIn("Traceback (most recent call last):", err)
1035 self.assertIn("ZeroDivisionError", err)
1036 self.assertNotIn("Unhandled exception", err)
1037
Serhiy Storchakaa7930372016-07-03 22:27:26 +03001038 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001039 def test_print_exception_stderr_is_none_1(self):
1040 script = r"""if True:
1041 import sys
1042 import threading
1043 import time
1044
1045 running = False
1046 def run():
1047 global running
1048 running = True
1049 while running:
1050 time.sleep(0.01)
1051 1/0
1052 t = threading.Thread(target=run)
1053 t.start()
1054 while not running:
1055 time.sleep(0.01)
1056 sys.stderr = None
1057 running = False
1058 t.join()
1059 """
1060 rc, out, err = assert_python_ok("-c", script)
1061 self.assertEqual(out, b'')
1062 err = err.decode()
1063 self.assertIn("Exception in thread", err)
1064 self.assertIn("Traceback (most recent call last):", err)
1065 self.assertIn("ZeroDivisionError", err)
1066 self.assertNotIn("Unhandled exception", err)
1067
1068 def test_print_exception_stderr_is_none_2(self):
1069 script = r"""if True:
1070 import sys
1071 import threading
1072 import time
1073
1074 running = False
1075 def run():
1076 global running
1077 running = True
1078 while running:
1079 time.sleep(0.01)
1080 1/0
1081 sys.stderr = None
1082 t = threading.Thread(target=run)
1083 t.start()
1084 while not running:
1085 time.sleep(0.01)
1086 running = False
1087 t.join()
1088 """
1089 rc, out, err = assert_python_ok("-c", script)
1090 self.assertEqual(out, b'')
1091 self.assertNotIn("Unhandled exception", err.decode())
1092
Victor Stinnereec93312016-08-18 18:13:10 +02001093 def test_bare_raise_in_brand_new_thread(self):
1094 def bare_raise():
1095 raise
1096
1097 class Issue27558(threading.Thread):
1098 exc = None
1099
1100 def run(self):
1101 try:
1102 bare_raise()
1103 except Exception as exc:
1104 self.exc = exc
1105
1106 thread = Issue27558()
1107 thread.start()
1108 thread.join()
1109 self.assertIsNotNone(thread.exc)
1110 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001111 # explicitly break the reference cycle to not leak a dangling thread
1112 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001113
R David Murray19aeb432013-03-30 17:19:38 -04001114class TimerTests(BaseTestCase):
1115
1116 def setUp(self):
1117 BaseTestCase.setUp(self)
1118 self.callback_args = []
1119 self.callback_event = threading.Event()
1120
1121 def test_init_immutable_default_args(self):
1122 # Issue 17435: constructor defaults were mutable objects, they could be
1123 # mutated via the object attributes and affect other Timer objects.
1124 timer1 = threading.Timer(0.01, self._callback_spy)
1125 timer1.start()
1126 self.callback_event.wait()
1127 timer1.args.append("blah")
1128 timer1.kwargs["foo"] = "bar"
1129 self.callback_event.clear()
1130 timer2 = threading.Timer(0.01, self._callback_spy)
1131 timer2.start()
1132 self.callback_event.wait()
1133 self.assertEqual(len(self.callback_args), 2)
1134 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001135 timer1.join()
1136 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001137
1138 def _callback_spy(self, *args, **kwargs):
1139 self.callback_args.append((args[:], kwargs.copy()))
1140 self.callback_event.set()
1141
Antoine Pitrou557934f2009-11-06 22:41:14 +00001142class LockTests(lock_tests.LockTests):
1143 locktype = staticmethod(threading.Lock)
1144
Antoine Pitrou434736a2009-11-10 18:46:01 +00001145class PyRLockTests(lock_tests.RLockTests):
1146 locktype = staticmethod(threading._PyRLock)
1147
Charles-François Natali6b671b22012-01-28 11:36:04 +01001148@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001149class CRLockTests(lock_tests.RLockTests):
1150 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001151
1152class EventTests(lock_tests.EventTests):
1153 eventtype = staticmethod(threading.Event)
1154
1155class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001156 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001157 locktype = staticmethod(threading.Condition)
1158
1159class ConditionTests(lock_tests.ConditionTests):
1160 condtype = staticmethod(threading.Condition)
1161
1162class SemaphoreTests(lock_tests.SemaphoreTests):
1163 semtype = staticmethod(threading.Semaphore)
1164
1165class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1166 semtype = staticmethod(threading.BoundedSemaphore)
1167
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001168class BarrierTests(lock_tests.BarrierTests):
1169 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001170
Martin Panter19e69c52015-11-14 12:46:42 +00001171class MiscTestCase(unittest.TestCase):
1172 def test__all__(self):
1173 extra = {"ThreadError"}
1174 blacklist = {'currentThread', 'activeCount'}
1175 support.check__all__(self, threading, ('threading', '_thread'),
1176 extra=extra, blacklist=blacklist)
1177
Tim Peters84d54892005-01-08 06:03:17 +00001178if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001179 unittest.main()