blob: 6ac6e9de7a5d10d41bb619788d046ca7cf7a773e [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 Tesler4959c332019-05-12 10:08:24 -0700107 native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
108 self.assertNotIn(None, native_ids)
109 self.assertEqual(len(native_ids), NUMTASKS + 1)
110
Tim Peters84d54892005-01-08 06:03:17 +0000111 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000113 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200114 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200115 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000116 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200117 self.assertIsNotNone(t.ident)
118 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000119 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000120 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000121 self.assertEqual(numrunning.get(), 0)
122
Benjamin Petersond23f8222009-04-05 19:13:16 +0000123 def test_ident_of_no_threading_threads(self):
124 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200125 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000126 def f():
127 ident.append(threading.currentThread().ident)
128 done.set()
129 done = threading.Event()
130 ident = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700131 with support.wait_threads_exit():
132 tid = _thread.start_new_thread(f, ())
133 done.wait()
134 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000135 # Kill the "immortal" _DummyThread
136 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000137
Victor Stinner8c663fd2017-11-08 14:44:44 -0800138 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 def test_various_ops_small_stack(self):
140 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800141 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 try:
143 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000144 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000145 raise unittest.SkipTest(
146 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000147 self.test_various_ops()
148 threading.stack_size(0)
149
Victor Stinner8c663fd2017-11-08 14:44:44 -0800150 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151 def test_various_ops_large_stack(self):
152 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800153 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154 try:
155 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000156 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000157 raise unittest.SkipTest(
158 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000159 self.test_various_ops()
160 threading.stack_size(0)
161
Tim Peters711906e2005-01-08 07:30:42 +0000162 def test_foreign_thread(self):
163 # Check that a "foreign" thread can use the threading module.
164 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000165 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000166 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000167 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000168 mutex.release()
169
170 mutex = threading.Lock()
171 mutex.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700172 with support.wait_threads_exit():
173 tid = _thread.start_new_thread(f, (mutex,))
174 # Wait for the thread to finish.
175 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000176 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000177 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800178 #Issue 29376
179 self.assertTrue(threading._active[tid].is_alive())
180 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000181 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000182
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000183 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
184 # exposed at the Python level. This test relies on ctypes to get at it.
185 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200186 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000187
188 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200189 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190
191 class AsyncExc(Exception):
192 pass
193
194 exception = ctypes.py_object(AsyncExc)
195
Antoine Pitroube4d8092009-10-18 18:27:17 +0000196 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200197 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200198 self.assertIsInstance(tid, int)
199 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000200
201 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200202 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000203 # The exception is async, so we might have to keep the VM busy until
204 # it notices.
205 while True:
206 pass
207 except AsyncExc:
208 pass
209 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000210 # This code is unreachable but it reflects the intent. If we wanted
211 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000212 self.fail("AsyncExc not raised")
213 try:
214 self.assertEqual(result, 1) # one thread state modified
215 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000216 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000217 pass
218
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000219 # `worker_started` is set by the thread when it's inside a try/except
220 # block waiting to catch the asynchronously set AsyncExc exception.
221 # `worker_saw_exception` is set by the thread upon catching that
222 # exception.
223 worker_started = threading.Event()
224 worker_saw_exception = threading.Event()
225
226 class Worker(threading.Thread):
227 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200228 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000229 self.finished = False
230
231 try:
232 while True:
233 worker_started.set()
234 time.sleep(0.1)
235 except AsyncExc:
236 self.finished = True
237 worker_saw_exception.set()
238
239 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000240 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 t.start()
242 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244
245 # Try a thread id that doesn't make sense.
246 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200248 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000249 self.assertEqual(result, 0) # no thread states modified
250
251 # Now raise an exception in the worker thread.
252 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000253 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000254 ret = worker_started.wait()
255 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000256 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000257 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200258 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000259 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000260 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200261 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000262 self.assertEqual(result, 1) # one thread state modified
263 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000264 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000265 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000266 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000267 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000268 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000269 if t.finished:
270 t.join()
271 # else the thread is still running, and we have no way to kill it
272
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000273 def test_limbo_cleanup(self):
274 # Issue 7481: Failure to start thread should cleanup the limbo map.
275 def fail_new_thread(*args):
276 raise threading.ThreadError()
277 _start_new_thread = threading._start_new_thread
278 threading._start_new_thread = fail_new_thread
279 try:
280 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000281 self.assertRaises(threading.ThreadError, t.start)
282 self.assertFalse(
283 t in threading._limbo,
284 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000285 finally:
286 threading._start_new_thread = _start_new_thread
287
Christian Heimes7d2ff882007-11-30 14:35:04 +0000288 def test_finalize_runnning_thread(self):
289 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
290 # very late on python exit: on deallocation of a running thread for
291 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200292 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000293
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200294 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000295 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000297 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000298 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000299 ready.acquire()
300
Christian Heimes7d2ff882007-11-30 14:35:04 +0000301 # Module globals are cleared before __del__ is run
302 # So we save the functions in class dict
303 class C:
304 ensure = ctypes.pythonapi.PyGILState_Ensure
305 release = ctypes.pythonapi.PyGILState_Release
306 def __del__(self):
307 state = self.ensure()
308 self.release(state)
309
310 def waitingThread():
311 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000312 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000313 time.sleep(100)
314
Georg Brandl2067bfd2008-05-25 13:05:15 +0000315 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000316 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000317 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200318 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000319 self.assertEqual(rc, 42)
320
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000321 def test_finalize_with_trace(self):
322 # Issue1733757
323 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200324 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000325 import sys, threading
326
327 # A deadlock-killer, to prevent the
328 # testsuite to hang forever
329 def killer():
330 import os, time
331 time.sleep(2)
332 print('program blocked; aborting')
333 os._exit(2)
334 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000335 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000336 t.start()
337
338 # This is the trace function
339 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000340 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000341 return func
342
343 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200344 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000345
Antoine Pitrou011bd622009-10-20 21:52:47 +0000346 def test_join_nondaemon_on_shutdown(self):
347 # Issue 1722344
348 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200349 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000350 import threading
351 from time import sleep
352
353 def child():
354 sleep(1)
355 # As a non-daemon thread we SHOULD wake up and nothing
356 # should be torn down yet
357 print("Woke up, sleep function is:", sleep)
358
359 threading.Thread(target=child).start()
360 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200361 """)
362 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000363 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200364 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000365
Christian Heimes1af737c2008-01-23 08:24:23 +0000366 def test_enumerate_after_join(self):
367 # Try hard to trigger #1703448: a thread is still returned in
368 # threading.enumerate() after it has been join()ed.
369 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000370 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000371 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000372 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000373 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000374 t = threading.Thread(target=lambda: None)
375 t.start()
376 t.join()
377 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000378 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000379 "#1703448 triggered after %d trials: %s" % (i, l))
380 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000381 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000382
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000383 def test_no_refcycle_through_target(self):
384 class RunSelfFunction(object):
385 def __init__(self, should_raise):
386 # The links in this refcycle from Thread back to self
387 # should be cleaned up when the thread completes.
388 self.should_raise = should_raise
389 self.thread = threading.Thread(target=self._run,
390 args=(self,),
391 kwargs={'yet_another':self})
392 self.thread.start()
393
394 def _run(self, other_ref, yet_another):
395 if self.should_raise:
396 raise SystemExit
397
398 cyclic_object = RunSelfFunction(should_raise=False)
399 weak_cyclic_object = weakref.ref(cyclic_object)
400 cyclic_object.thread.join()
401 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000402 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000403 msg=('%d references still around' %
404 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000405
406 raising_cyclic_object = RunSelfFunction(should_raise=True)
407 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
408 raising_cyclic_object.thread.join()
409 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000410 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000411 msg=('%d references still around' %
412 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000413
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000414 def test_old_threading_api(self):
415 # Just a quick sanity check to make sure the old method names are
416 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000417 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000418 t.isDaemon()
419 t.setDaemon(True)
420 t.getName()
421 t.setName("name")
Dong-hee Na89669ff2019-01-17 21:14:45 +0900422 with self.assertWarnsRegex(DeprecationWarning, 'use is_alive()'):
423 t.isAlive()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000424 e = threading.Event()
425 e.isSet()
426 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000427
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000428 def test_repr_daemon(self):
429 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200430 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000431 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200432 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000433
luzpaza5293b42017-11-05 07:37:50 -0600434 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000435 t = threading.Thread()
436 self.assertFalse(t.daemon)
437 t = threading.Thread(daemon=False)
438 self.assertFalse(t.daemon)
439 t = threading.Thread(daemon=True)
440 self.assertTrue(t.daemon)
441
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200442 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
443 def test_dummy_thread_after_fork(self):
444 # Issue #14308: a dummy thread in the active list doesn't mess up
445 # the after-fork mechanism.
446 code = """if 1:
447 import _thread, threading, os, time
448
449 def background_thread(evt):
450 # Creates and registers the _DummyThread instance
451 threading.current_thread()
452 evt.set()
453 time.sleep(10)
454
455 evt = threading.Event()
456 _thread.start_new_thread(background_thread, (evt,))
457 evt.wait()
458 assert threading.active_count() == 2, threading.active_count()
459 if os.fork() == 0:
460 assert threading.active_count() == 1, threading.active_count()
461 os._exit(0)
462 else:
463 os.wait()
464 """
465 _, out, err = assert_python_ok("-c", code)
466 self.assertEqual(out, b'')
467 self.assertEqual(err, b'')
468
Charles-François Natali9939cc82013-08-30 23:32:53 +0200469 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
470 def test_is_alive_after_fork(self):
471 # Try hard to trigger #18418: is_alive() could sometimes be True on
472 # threads that vanished after a fork.
473 old_interval = sys.getswitchinterval()
474 self.addCleanup(sys.setswitchinterval, old_interval)
475
476 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100477 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200478
479 for i in range(20):
480 t = threading.Thread(target=lambda: None)
481 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200482 pid = os.fork()
483 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700484 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200485 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700486 t.join()
487
Charles-François Natali9939cc82013-08-30 23:32:53 +0200488 pid, status = os.waitpid(pid, 0)
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700489 self.assertTrue(os.WIFEXITED(status))
490 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200491
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300492 def test_main_thread(self):
493 main = threading.main_thread()
494 self.assertEqual(main.name, 'MainThread')
495 self.assertEqual(main.ident, threading.current_thread().ident)
496 self.assertEqual(main.ident, threading.get_ident())
497
498 def f():
499 self.assertNotEqual(threading.main_thread().ident,
500 threading.current_thread().ident)
501 th = threading.Thread(target=f)
502 th.start()
503 th.join()
504
505 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
506 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
507 def test_main_thread_after_fork(self):
508 code = """if 1:
509 import os, threading
510
511 pid = os.fork()
512 if pid == 0:
513 main = threading.main_thread()
514 print(main.name)
515 print(main.ident == threading.current_thread().ident)
516 print(main.ident == threading.get_ident())
517 else:
518 os.waitpid(pid, 0)
519 """
520 _, out, err = assert_python_ok("-c", code)
521 data = out.decode().replace('\r', '')
522 self.assertEqual(err, b"")
523 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
524
525 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
526 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
527 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
528 def test_main_thread_after_fork_from_nonmain_thread(self):
529 code = """if 1:
530 import os, threading, sys
531
532 def f():
533 pid = os.fork()
534 if pid == 0:
535 main = threading.main_thread()
536 print(main.name)
537 print(main.ident == threading.current_thread().ident)
538 print(main.ident == threading.get_ident())
539 # stdout is fully buffered because not a tty,
540 # we have to flush before exit.
541 sys.stdout.flush()
542 else:
543 os.waitpid(pid, 0)
544
545 th = threading.Thread(target=f)
546 th.start()
547 th.join()
548 """
549 _, out, err = assert_python_ok("-c", code)
550 data = out.decode().replace('\r', '')
551 self.assertEqual(err, b"")
552 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
553
Zackery Spytz65d2f8c2018-10-12 02:31:21 -0600554 @requires_type_collecting
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200555 def test_main_thread_during_shutdown(self):
556 # bpo-31516: current_thread() should still point to the main thread
557 # at shutdown
558 code = """if 1:
559 import gc, threading
560
561 main_thread = threading.current_thread()
562 assert main_thread is threading.main_thread() # sanity check
563
564 class RefCycle:
565 def __init__(self):
566 self.cycle = self
567
568 def __del__(self):
569 print("GC:",
570 threading.current_thread() is main_thread,
571 threading.main_thread() is main_thread,
572 threading.enumerate() == [main_thread])
573
574 RefCycle()
575 gc.collect() # sanity check
576 x = RefCycle()
577 """
578 _, out, err = assert_python_ok("-c", code)
579 data = out.decode()
580 self.assertEqual(err, b"")
581 self.assertEqual(data.splitlines(),
582 ["GC: True True True"] * 2)
583
Antoine Pitrou7b476992013-09-07 23:38:37 +0200584 def test_tstate_lock(self):
585 # Test an implementation detail of Thread objects.
586 started = _thread.allocate_lock()
587 finish = _thread.allocate_lock()
588 started.acquire()
589 finish.acquire()
590 def f():
591 started.release()
592 finish.acquire()
593 time.sleep(0.01)
594 # The tstate lock is None until the thread is started
595 t = threading.Thread(target=f)
596 self.assertIs(t._tstate_lock, None)
597 t.start()
598 started.acquire()
599 self.assertTrue(t.is_alive())
600 # The tstate lock can't be acquired when the thread is running
601 # (or suspended).
602 tstate_lock = t._tstate_lock
603 self.assertFalse(tstate_lock.acquire(timeout=0), False)
604 finish.release()
605 # When the thread ends, the state_lock can be successfully
606 # acquired.
607 self.assertTrue(tstate_lock.acquire(timeout=5), False)
608 # But is_alive() is still True: we hold _tstate_lock now, which
609 # prevents is_alive() from knowing the thread's end-of-life C code
610 # is done.
611 self.assertTrue(t.is_alive())
612 # Let is_alive() find out the C code is done.
613 tstate_lock.release()
614 self.assertFalse(t.is_alive())
615 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200616 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700617 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200618
Tim Peters72460fa2013-09-09 18:48:24 -0500619 def test_repr_stopped(self):
620 # Verify that "stopped" shows up in repr(Thread) appropriately.
621 started = _thread.allocate_lock()
622 finish = _thread.allocate_lock()
623 started.acquire()
624 finish.acquire()
625 def f():
626 started.release()
627 finish.acquire()
628 t = threading.Thread(target=f)
629 t.start()
630 started.acquire()
631 self.assertIn("started", repr(t))
632 finish.release()
633 # "stopped" should appear in the repr in a reasonable amount of time.
634 # Implementation detail: as of this writing, that's trivially true
635 # if .join() is called, and almost trivially true if .is_alive() is
636 # called. The detail we're testing here is that "stopped" shows up
637 # "all on its own".
638 LOOKING_FOR = "stopped"
639 for i in range(500):
640 if LOOKING_FOR in repr(t):
641 break
642 time.sleep(0.01)
643 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700644 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000645
Tim Peters7634e1c2013-10-08 20:55:51 -0500646 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500647 # BoundedSemaphore should raise ValueError if released too often.
648 for limit in range(1, 10):
649 bs = threading.BoundedSemaphore(limit)
650 threads = [threading.Thread(target=bs.acquire)
651 for _ in range(limit)]
652 for t in threads:
653 t.start()
654 for t in threads:
655 t.join()
656 threads = [threading.Thread(target=bs.release)
657 for _ in range(limit)]
658 for t in threads:
659 t.start()
660 for t in threads:
661 t.join()
662 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500663
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200664 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100665 def test_frame_tstate_tracing(self):
666 # Issue #14432: Crash when a generator is created in a C thread that is
667 # destroyed while the generator is still used. The issue was that a
668 # generator contains a frame, and the frame kept a reference to the
669 # Python state of the destroyed C thread. The crash occurs when a trace
670 # function is setup.
671
672 def noop_trace(frame, event, arg):
673 # no operation
674 return noop_trace
675
676 def generator():
677 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300678 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100679
680 def callback():
681 if callback.gen is None:
682 callback.gen = generator()
683 return next(callback.gen)
684 callback.gen = None
685
686 old_trace = sys.gettrace()
687 sys.settrace(noop_trace)
688 try:
689 # Install a trace function
690 threading.settrace(noop_trace)
691
692 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200693 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100694 _testcapi.call_in_temporary_c_thread(callback)
695
696 # Call the generator in a different Python thread, check that the
697 # generator didn't keep a reference to the destroyed thread state
698 for test in range(3):
699 # The trace function is still called here
700 callback()
701 finally:
702 sys.settrace(old_trace)
703
Victor Stinner45956b92013-11-12 16:37:55 +0100704
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000705class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000706
707 def _run_and_join(self, script):
708 script = """if 1:
709 import sys, os, time, threading
710
711 # a thread, which waits for the main program to terminate
712 def joiningfunc(mainthread):
713 mainthread.join()
714 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000715 # stdout is fully buffered because not a tty, we have to flush
716 # before exit.
717 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000718 \n""" + script
719
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200720 rc, out, err = assert_python_ok("-c", script)
721 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000722 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000723
724 def test_1_join_on_shutdown(self):
725 # The usual case: on exit, wait for a non-daemon thread
726 script = """if 1:
727 import os
728 t = threading.Thread(target=joiningfunc,
729 args=(threading.current_thread(),))
730 t.start()
731 time.sleep(0.1)
732 print('end of main')
733 """
734 self._run_and_join(script)
735
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000736 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200737 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000738 def test_2_join_in_forked_process(self):
739 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000740 script = """if 1:
741 childpid = os.fork()
742 if childpid != 0:
743 os.waitpid(childpid, 0)
744 sys.exit(0)
745
746 t = threading.Thread(target=joiningfunc,
747 args=(threading.current_thread(),))
748 t.start()
749 print('end of main')
750 """
751 self._run_and_join(script)
752
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000753 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200754 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000755 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000756 # Like the test above, but fork() was called from a worker thread
757 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000758
Jesse Nollera8513972008-07-17 16:49:17 +0000759 script = """if 1:
760 main_thread = threading.current_thread()
761 def worker():
762 childpid = os.fork()
763 if childpid != 0:
764 os.waitpid(childpid, 0)
765 sys.exit(0)
766
767 t = threading.Thread(target=joiningfunc,
768 args=(main_thread,))
769 print('end of main')
770 t.start()
771 t.join() # Should not block: main_thread is already stopped
772
773 w = threading.Thread(target=worker)
774 w.start()
775 """
776 self._run_and_join(script)
777
Victor Stinner26d31862011-07-01 14:26:24 +0200778 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500779 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200780 # Check that a daemon thread cannot crash the interpreter on shutdown
781 # by manipulating internal structures that are being disposed of in
782 # the main thread.
783 script = """if True:
784 import os
785 import random
786 import sys
787 import time
788 import threading
789
790 thread_has_run = set()
791
792 def random_io():
793 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200794 while True:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200795 with open(os.__file__, 'rb') as in_f:
796 stuff = in_f.read(200)
797 with open(os.devnull, 'wb') as null_f:
798 null_f.write(stuff)
799 time.sleep(random.random() / 1995)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200800 thread_has_run.add(threading.current_thread())
801
802 def main():
803 count = 0
804 for _ in range(40):
805 new_thread = threading.Thread(target=random_io)
806 new_thread.daemon = True
807 new_thread.start()
808 count += 1
809 while len(thread_has_run) < count:
810 time.sleep(0.001)
811 # Trigger process shutdown
812 sys.exit(0)
813
814 main()
815 """
816 rc, out, err = assert_python_ok('-c', script)
817 self.assertFalse(err)
818
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100819 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100820 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100821 def test_reinit_tls_after_fork(self):
822 # Issue #13817: fork() would deadlock in a multithreaded program with
823 # the ad-hoc TLS implementation.
824
825 def do_fork_and_wait():
826 # just fork a child process and wait it
827 pid = os.fork()
828 if pid > 0:
829 os.waitpid(pid, 0)
830 else:
831 os._exit(0)
832
833 # start a bunch of threads that will fork() child processes
834 threads = []
835 for i in range(16):
836 t = threading.Thread(target=do_fork_and_wait)
837 threads.append(t)
838 t.start()
839
840 for t in threads:
841 t.join()
842
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200843 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
844 def test_clear_threads_states_after_fork(self):
845 # Issue #17094: check that threads states are cleared after fork()
846
847 # start a bunch of threads
848 threads = []
849 for i in range(16):
850 t = threading.Thread(target=lambda : time.sleep(0.3))
851 threads.append(t)
852 t.start()
853
854 pid = os.fork()
855 if pid == 0:
856 # check that threads states have been cleared
857 if len(sys._current_frames()) == 1:
858 os._exit(0)
859 else:
860 os._exit(1)
861 else:
862 _, status = os.waitpid(pid, 0)
863 self.assertEqual(0, status)
864
865 for t in threads:
866 t.join()
867
Jesse Nollera8513972008-07-17 16:49:17 +0000868
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200869class SubinterpThreadingTests(BaseTestCase):
870
871 def test_threads_join(self):
872 # Non-daemon threads should be joined at subinterpreter shutdown
873 # (issue #18808)
874 r, w = os.pipe()
875 self.addCleanup(os.close, r)
876 self.addCleanup(os.close, w)
877 code = r"""if 1:
878 import os
879 import threading
880 import time
881
882 def f():
883 # Sleep a bit so that the thread is still running when
884 # Py_EndInterpreter is called.
885 time.sleep(0.05)
886 os.write(%d, b"x")
887 threading.Thread(target=f).start()
888 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100889 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200890 self.assertEqual(ret, 0)
891 # The thread was joined properly.
892 self.assertEqual(os.read(r, 1), b"x")
893
Antoine Pitrou7b476992013-09-07 23:38:37 +0200894 def test_threads_join_2(self):
895 # Same as above, but a delay gets introduced after the thread's
896 # Python code returned but before the thread state is deleted.
897 # To achieve this, we register a thread-local object which sleeps
898 # a bit when deallocated.
899 r, w = os.pipe()
900 self.addCleanup(os.close, r)
901 self.addCleanup(os.close, w)
902 code = r"""if 1:
903 import os
904 import threading
905 import time
906
907 class Sleeper:
908 def __del__(self):
909 time.sleep(0.05)
910
911 tls = threading.local()
912
913 def f():
914 # Sleep a bit so that the thread is still running when
915 # Py_EndInterpreter is called.
916 time.sleep(0.05)
917 tls.x = Sleeper()
918 os.write(%d, b"x")
919 threading.Thread(target=f).start()
920 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100921 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200922 self.assertEqual(ret, 0)
923 # The thread was joined properly.
924 self.assertEqual(os.read(r, 1), b"x")
925
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200926 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200927 def test_daemon_threads_fatal_error(self):
928 subinterp_code = r"""if 1:
929 import os
930 import threading
931 import time
932
933 def f():
934 # Make sure the daemon thread is still running when
935 # Py_EndInterpreter is called.
936 time.sleep(10)
937 threading.Thread(target=f, daemon=True).start()
938 """
939 script = r"""if 1:
940 import _testcapi
941
942 _testcapi.run_in_subinterp(%r)
943 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200944 with test.support.SuppressCrashReport():
945 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200946 self.assertIn("Fatal Python error: Py_EndInterpreter: "
947 "not the last thread", err.decode())
948
949
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000950class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000951 # A RuntimeError should be raised if Thread.start() is called
952 # multiple times.
953 def test_start_thread_again(self):
954 thread = threading.Thread()
955 thread.start()
956 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700957 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000958
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000959 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000960 current_thread = threading.current_thread()
961 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000962
963 def test_joining_inactive_thread(self):
964 thread = threading.Thread()
965 self.assertRaises(RuntimeError, thread.join)
966
967 def test_daemonize_active_thread(self):
968 thread = threading.Thread()
969 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000970 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700971 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000972
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000973 def test_releasing_unacquired_lock(self):
974 lock = threading.Lock()
975 self.assertRaises(RuntimeError, lock.release)
976
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400977 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
978 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700979 def test_recursion_limit(self):
980 # Issue 9670
981 # test that excessive recursion within a non-main thread causes
982 # an exception rather than crashing the interpreter on platforms
983 # like Mac OS X or FreeBSD which have small default stack sizes
984 # for threads
985 script = """if True:
986 import threading
987
988 def recurse():
989 return recurse()
990
991 def outer():
992 try:
993 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400994 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700995 pass
996
997 w = threading.Thread(target=outer)
998 w.start()
999 w.join()
1000 print('end of main thread')
1001 """
1002 expected_output = "end of main thread\n"
1003 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001004 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001005 stdout, stderr = p.communicate()
1006 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001007 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001008 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001009
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001010 def test_print_exception(self):
1011 script = r"""if True:
1012 import threading
1013 import time
1014
1015 running = False
1016 def run():
1017 global running
1018 running = True
1019 while running:
1020 time.sleep(0.01)
1021 1/0
1022 t = threading.Thread(target=run)
1023 t.start()
1024 while not running:
1025 time.sleep(0.01)
1026 running = False
1027 t.join()
1028 """
1029 rc, out, err = assert_python_ok("-c", script)
1030 self.assertEqual(out, b'')
1031 err = err.decode()
1032 self.assertIn("Exception in thread", err)
1033 self.assertIn("Traceback (most recent call last):", err)
1034 self.assertIn("ZeroDivisionError", err)
1035 self.assertNotIn("Unhandled exception", err)
1036
Serhiy Storchakaa7930372016-07-03 22:27:26 +03001037 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001038 def test_print_exception_stderr_is_none_1(self):
1039 script = r"""if True:
1040 import sys
1041 import threading
1042 import time
1043
1044 running = False
1045 def run():
1046 global running
1047 running = True
1048 while running:
1049 time.sleep(0.01)
1050 1/0
1051 t = threading.Thread(target=run)
1052 t.start()
1053 while not running:
1054 time.sleep(0.01)
1055 sys.stderr = None
1056 running = False
1057 t.join()
1058 """
1059 rc, out, err = assert_python_ok("-c", script)
1060 self.assertEqual(out, b'')
1061 err = err.decode()
1062 self.assertIn("Exception in thread", err)
1063 self.assertIn("Traceback (most recent call last):", err)
1064 self.assertIn("ZeroDivisionError", err)
1065 self.assertNotIn("Unhandled exception", err)
1066
1067 def test_print_exception_stderr_is_none_2(self):
1068 script = r"""if True:
1069 import sys
1070 import threading
1071 import time
1072
1073 running = False
1074 def run():
1075 global running
1076 running = True
1077 while running:
1078 time.sleep(0.01)
1079 1/0
1080 sys.stderr = None
1081 t = threading.Thread(target=run)
1082 t.start()
1083 while not running:
1084 time.sleep(0.01)
1085 running = False
1086 t.join()
1087 """
1088 rc, out, err = assert_python_ok("-c", script)
1089 self.assertEqual(out, b'')
1090 self.assertNotIn("Unhandled exception", err.decode())
1091
Victor Stinnereec93312016-08-18 18:13:10 +02001092 def test_bare_raise_in_brand_new_thread(self):
1093 def bare_raise():
1094 raise
1095
1096 class Issue27558(threading.Thread):
1097 exc = None
1098
1099 def run(self):
1100 try:
1101 bare_raise()
1102 except Exception as exc:
1103 self.exc = exc
1104
1105 thread = Issue27558()
1106 thread.start()
1107 thread.join()
1108 self.assertIsNotNone(thread.exc)
1109 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001110 # explicitly break the reference cycle to not leak a dangling thread
1111 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001112
R David Murray19aeb432013-03-30 17:19:38 -04001113class TimerTests(BaseTestCase):
1114
1115 def setUp(self):
1116 BaseTestCase.setUp(self)
1117 self.callback_args = []
1118 self.callback_event = threading.Event()
1119
1120 def test_init_immutable_default_args(self):
1121 # Issue 17435: constructor defaults were mutable objects, they could be
1122 # mutated via the object attributes and affect other Timer objects.
1123 timer1 = threading.Timer(0.01, self._callback_spy)
1124 timer1.start()
1125 self.callback_event.wait()
1126 timer1.args.append("blah")
1127 timer1.kwargs["foo"] = "bar"
1128 self.callback_event.clear()
1129 timer2 = threading.Timer(0.01, self._callback_spy)
1130 timer2.start()
1131 self.callback_event.wait()
1132 self.assertEqual(len(self.callback_args), 2)
1133 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001134 timer1.join()
1135 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001136
1137 def _callback_spy(self, *args, **kwargs):
1138 self.callback_args.append((args[:], kwargs.copy()))
1139 self.callback_event.set()
1140
Antoine Pitrou557934f2009-11-06 22:41:14 +00001141class LockTests(lock_tests.LockTests):
1142 locktype = staticmethod(threading.Lock)
1143
Antoine Pitrou434736a2009-11-10 18:46:01 +00001144class PyRLockTests(lock_tests.RLockTests):
1145 locktype = staticmethod(threading._PyRLock)
1146
Charles-François Natali6b671b22012-01-28 11:36:04 +01001147@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001148class CRLockTests(lock_tests.RLockTests):
1149 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001150
1151class EventTests(lock_tests.EventTests):
1152 eventtype = staticmethod(threading.Event)
1153
1154class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001155 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001156 locktype = staticmethod(threading.Condition)
1157
1158class ConditionTests(lock_tests.ConditionTests):
1159 condtype = staticmethod(threading.Condition)
1160
1161class SemaphoreTests(lock_tests.SemaphoreTests):
1162 semtype = staticmethod(threading.Semaphore)
1163
1164class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1165 semtype = staticmethod(threading.BoundedSemaphore)
1166
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001167class BarrierTests(lock_tests.BarrierTests):
1168 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001169
Martin Panter19e69c52015-11-14 12:46:42 +00001170class MiscTestCase(unittest.TestCase):
1171 def test__all__(self):
1172 extra = {"ThreadError"}
1173 blacklist = {'currentThread', 'activeCount'}
1174 support.check__all__(self, threading, ('threading', '_thread'),
1175 extra=extra, blacklist=blacklist)
1176
Tim Peters84d54892005-01-08 06:03:17 +00001177if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001178 unittest.main()