blob: 8160a5af0064475e7bab524c5e74d85d595b3204 [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
107 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000109 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200110 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200111 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000112 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200113 self.assertIsNotNone(t.ident)
114 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000115 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000116 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000117 self.assertEqual(numrunning.get(), 0)
118
Benjamin Petersond23f8222009-04-05 19:13:16 +0000119 def test_ident_of_no_threading_threads(self):
120 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200121 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000122 def f():
123 ident.append(threading.currentThread().ident)
124 done.set()
125 done = threading.Event()
126 ident = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700127 with support.wait_threads_exit():
128 tid = _thread.start_new_thread(f, ())
129 done.wait()
130 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000131 # Kill the "immortal" _DummyThread
132 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000133
Victor Stinner8c663fd2017-11-08 14:44:44 -0800134 # run with a small(ish) thread stack size (256 KiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 def test_various_ops_small_stack(self):
136 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800137 print('with 256 KiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 try:
139 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000140 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000141 raise unittest.SkipTest(
142 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 self.test_various_ops()
144 threading.stack_size(0)
145
Victor Stinner8c663fd2017-11-08 14:44:44 -0800146 # run with a large thread stack size (1 MiB)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000147 def test_various_ops_large_stack(self):
148 if verbose:
Victor Stinner8c663fd2017-11-08 14:44:44 -0800149 print('with 1 MiB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 try:
151 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000152 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000153 raise unittest.SkipTest(
154 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 self.test_various_ops()
156 threading.stack_size(0)
157
Tim Peters711906e2005-01-08 07:30:42 +0000158 def test_foreign_thread(self):
159 # Check that a "foreign" thread can use the threading module.
160 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000161 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000162 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000163 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000164 mutex.release()
165
166 mutex = threading.Lock()
167 mutex.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700168 with support.wait_threads_exit():
169 tid = _thread.start_new_thread(f, (mutex,))
170 # Wait for the thread to finish.
171 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000172 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000173 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800174 #Issue 29376
175 self.assertTrue(threading._active[tid].is_alive())
176 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000177 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000178
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000179 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
180 # exposed at the Python level. This test relies on ctypes to get at it.
181 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200182 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000183
184 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200185 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000186
187 class AsyncExc(Exception):
188 pass
189
190 exception = ctypes.py_object(AsyncExc)
191
Antoine Pitroube4d8092009-10-18 18:27:17 +0000192 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200193 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200194 self.assertIsInstance(tid, int)
195 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000196
197 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200198 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000199 # The exception is async, so we might have to keep the VM busy until
200 # it notices.
201 while True:
202 pass
203 except AsyncExc:
204 pass
205 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000206 # This code is unreachable but it reflects the intent. If we wanted
207 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000208 self.fail("AsyncExc not raised")
209 try:
210 self.assertEqual(result, 1) # one thread state modified
211 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000212 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000213 pass
214
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000215 # `worker_started` is set by the thread when it's inside a try/except
216 # block waiting to catch the asynchronously set AsyncExc exception.
217 # `worker_saw_exception` is set by the thread upon catching that
218 # exception.
219 worker_started = threading.Event()
220 worker_saw_exception = threading.Event()
221
222 class Worker(threading.Thread):
223 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200224 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000225 self.finished = False
226
227 try:
228 while True:
229 worker_started.set()
230 time.sleep(0.1)
231 except AsyncExc:
232 self.finished = True
233 worker_saw_exception.set()
234
235 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000236 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000237 t.start()
238 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000240
241 # Try a thread id that doesn't make sense.
242 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200244 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 self.assertEqual(result, 0) # no thread states modified
246
247 # Now raise an exception in the worker thread.
248 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000250 ret = worker_started.wait()
251 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000252 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000253 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200254 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000255 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000256 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200257 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000258 self.assertEqual(result, 1) # one thread state modified
259 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000260 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000261 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000262 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000263 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000264 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000265 if t.finished:
266 t.join()
267 # else the thread is still running, and we have no way to kill it
268
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000269 def test_limbo_cleanup(self):
270 # Issue 7481: Failure to start thread should cleanup the limbo map.
271 def fail_new_thread(*args):
272 raise threading.ThreadError()
273 _start_new_thread = threading._start_new_thread
274 threading._start_new_thread = fail_new_thread
275 try:
276 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000277 self.assertRaises(threading.ThreadError, t.start)
278 self.assertFalse(
279 t in threading._limbo,
280 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000281 finally:
282 threading._start_new_thread = _start_new_thread
283
Christian Heimes7d2ff882007-11-30 14:35:04 +0000284 def test_finalize_runnning_thread(self):
285 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
286 # very late on python exit: on deallocation of a running thread for
287 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200288 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000289
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200290 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000291 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000292
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000293 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000294 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000295 ready.acquire()
296
Christian Heimes7d2ff882007-11-30 14:35:04 +0000297 # Module globals are cleared before __del__ is run
298 # So we save the functions in class dict
299 class C:
300 ensure = ctypes.pythonapi.PyGILState_Ensure
301 release = ctypes.pythonapi.PyGILState_Release
302 def __del__(self):
303 state = self.ensure()
304 self.release(state)
305
306 def waitingThread():
307 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000308 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000309 time.sleep(100)
310
Georg Brandl2067bfd2008-05-25 13:05:15 +0000311 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000312 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000313 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200314 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000315 self.assertEqual(rc, 42)
316
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000317 def test_finalize_with_trace(self):
318 # Issue1733757
319 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200320 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000321 import sys, threading
322
323 # A deadlock-killer, to prevent the
324 # testsuite to hang forever
325 def killer():
326 import os, time
327 time.sleep(2)
328 print('program blocked; aborting')
329 os._exit(2)
330 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000331 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000332 t.start()
333
334 # This is the trace function
335 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000336 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000337 return func
338
339 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200340 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000341
Antoine Pitrou011bd622009-10-20 21:52:47 +0000342 def test_join_nondaemon_on_shutdown(self):
343 # Issue 1722344
344 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200345 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000346 import threading
347 from time import sleep
348
349 def child():
350 sleep(1)
351 # As a non-daemon thread we SHOULD wake up and nothing
352 # should be torn down yet
353 print("Woke up, sleep function is:", sleep)
354
355 threading.Thread(target=child).start()
356 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200357 """)
358 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000359 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200360 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000361
Christian Heimes1af737c2008-01-23 08:24:23 +0000362 def test_enumerate_after_join(self):
363 # Try hard to trigger #1703448: a thread is still returned in
364 # threading.enumerate() after it has been join()ed.
365 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000366 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000367 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000368 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000369 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000370 t = threading.Thread(target=lambda: None)
371 t.start()
372 t.join()
373 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000374 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000375 "#1703448 triggered after %d trials: %s" % (i, l))
376 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000377 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000378
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000379 def test_no_refcycle_through_target(self):
380 class RunSelfFunction(object):
381 def __init__(self, should_raise):
382 # The links in this refcycle from Thread back to self
383 # should be cleaned up when the thread completes.
384 self.should_raise = should_raise
385 self.thread = threading.Thread(target=self._run,
386 args=(self,),
387 kwargs={'yet_another':self})
388 self.thread.start()
389
390 def _run(self, other_ref, yet_another):
391 if self.should_raise:
392 raise SystemExit
393
394 cyclic_object = RunSelfFunction(should_raise=False)
395 weak_cyclic_object = weakref.ref(cyclic_object)
396 cyclic_object.thread.join()
397 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000398 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000399 msg=('%d references still around' %
400 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000401
402 raising_cyclic_object = RunSelfFunction(should_raise=True)
403 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
404 raising_cyclic_object.thread.join()
405 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000406 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000407 msg=('%d references still around' %
408 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000409
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000410 def test_old_threading_api(self):
411 # Just a quick sanity check to make sure the old method names are
412 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000413 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000414 t.isDaemon()
415 t.setDaemon(True)
416 t.getName()
417 t.setName("name")
418 t.isAlive()
419 e = threading.Event()
420 e.isSet()
421 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000422
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000423 def test_repr_daemon(self):
424 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200425 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000426 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200427 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000428
luzpaza5293b42017-11-05 07:37:50 -0600429 def test_daemon_param(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000430 t = threading.Thread()
431 self.assertFalse(t.daemon)
432 t = threading.Thread(daemon=False)
433 self.assertFalse(t.daemon)
434 t = threading.Thread(daemon=True)
435 self.assertTrue(t.daemon)
436
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200437 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
438 def test_dummy_thread_after_fork(self):
439 # Issue #14308: a dummy thread in the active list doesn't mess up
440 # the after-fork mechanism.
441 code = """if 1:
442 import _thread, threading, os, time
443
444 def background_thread(evt):
445 # Creates and registers the _DummyThread instance
446 threading.current_thread()
447 evt.set()
448 time.sleep(10)
449
450 evt = threading.Event()
451 _thread.start_new_thread(background_thread, (evt,))
452 evt.wait()
453 assert threading.active_count() == 2, threading.active_count()
454 if os.fork() == 0:
455 assert threading.active_count() == 1, threading.active_count()
456 os._exit(0)
457 else:
458 os.wait()
459 """
460 _, out, err = assert_python_ok("-c", code)
461 self.assertEqual(out, b'')
462 self.assertEqual(err, b'')
463
Charles-François Natali9939cc82013-08-30 23:32:53 +0200464 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
465 def test_is_alive_after_fork(self):
466 # Try hard to trigger #18418: is_alive() could sometimes be True on
467 # threads that vanished after a fork.
468 old_interval = sys.getswitchinterval()
469 self.addCleanup(sys.setswitchinterval, old_interval)
470
471 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100472 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200473
474 for i in range(20):
475 t = threading.Thread(target=lambda: None)
476 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200477 pid = os.fork()
478 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700479 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200480 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700481 t.join()
482
Charles-François Natali9939cc82013-08-30 23:32:53 +0200483 pid, status = os.waitpid(pid, 0)
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700484 self.assertTrue(os.WIFEXITED(status))
485 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200486
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300487 def test_main_thread(self):
488 main = threading.main_thread()
489 self.assertEqual(main.name, 'MainThread')
490 self.assertEqual(main.ident, threading.current_thread().ident)
491 self.assertEqual(main.ident, threading.get_ident())
492
493 def f():
494 self.assertNotEqual(threading.main_thread().ident,
495 threading.current_thread().ident)
496 th = threading.Thread(target=f)
497 th.start()
498 th.join()
499
500 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
501 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
502 def test_main_thread_after_fork(self):
503 code = """if 1:
504 import os, threading
505
506 pid = os.fork()
507 if pid == 0:
508 main = threading.main_thread()
509 print(main.name)
510 print(main.ident == threading.current_thread().ident)
511 print(main.ident == threading.get_ident())
512 else:
513 os.waitpid(pid, 0)
514 """
515 _, out, err = assert_python_ok("-c", code)
516 data = out.decode().replace('\r', '')
517 self.assertEqual(err, b"")
518 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
519
520 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
521 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
522 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
523 def test_main_thread_after_fork_from_nonmain_thread(self):
524 code = """if 1:
525 import os, threading, sys
526
527 def f():
528 pid = os.fork()
529 if pid == 0:
530 main = threading.main_thread()
531 print(main.name)
532 print(main.ident == threading.current_thread().ident)
533 print(main.ident == threading.get_ident())
534 # stdout is fully buffered because not a tty,
535 # we have to flush before exit.
536 sys.stdout.flush()
537 else:
538 os.waitpid(pid, 0)
539
540 th = threading.Thread(target=f)
541 th.start()
542 th.join()
543 """
544 _, out, err = assert_python_ok("-c", code)
545 data = out.decode().replace('\r', '')
546 self.assertEqual(err, b"")
547 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
548
Zackery Spytz65d2f8c2018-10-12 02:31:21 -0600549 @requires_type_collecting
Antoine Pitrou1023dbb2017-10-02 16:42:15 +0200550 def test_main_thread_during_shutdown(self):
551 # bpo-31516: current_thread() should still point to the main thread
552 # at shutdown
553 code = """if 1:
554 import gc, threading
555
556 main_thread = threading.current_thread()
557 assert main_thread is threading.main_thread() # sanity check
558
559 class RefCycle:
560 def __init__(self):
561 self.cycle = self
562
563 def __del__(self):
564 print("GC:",
565 threading.current_thread() is main_thread,
566 threading.main_thread() is main_thread,
567 threading.enumerate() == [main_thread])
568
569 RefCycle()
570 gc.collect() # sanity check
571 x = RefCycle()
572 """
573 _, out, err = assert_python_ok("-c", code)
574 data = out.decode()
575 self.assertEqual(err, b"")
576 self.assertEqual(data.splitlines(),
577 ["GC: True True True"] * 2)
578
Antoine Pitrou7b476992013-09-07 23:38:37 +0200579 def test_tstate_lock(self):
580 # Test an implementation detail of Thread objects.
581 started = _thread.allocate_lock()
582 finish = _thread.allocate_lock()
583 started.acquire()
584 finish.acquire()
585 def f():
586 started.release()
587 finish.acquire()
588 time.sleep(0.01)
589 # The tstate lock is None until the thread is started
590 t = threading.Thread(target=f)
591 self.assertIs(t._tstate_lock, None)
592 t.start()
593 started.acquire()
594 self.assertTrue(t.is_alive())
595 # The tstate lock can't be acquired when the thread is running
596 # (or suspended).
597 tstate_lock = t._tstate_lock
598 self.assertFalse(tstate_lock.acquire(timeout=0), False)
599 finish.release()
600 # When the thread ends, the state_lock can be successfully
601 # acquired.
602 self.assertTrue(tstate_lock.acquire(timeout=5), False)
603 # But is_alive() is still True: we hold _tstate_lock now, which
604 # prevents is_alive() from knowing the thread's end-of-life C code
605 # is done.
606 self.assertTrue(t.is_alive())
607 # Let is_alive() find out the C code is done.
608 tstate_lock.release()
609 self.assertFalse(t.is_alive())
610 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200611 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700612 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200613
Tim Peters72460fa2013-09-09 18:48:24 -0500614 def test_repr_stopped(self):
615 # Verify that "stopped" shows up in repr(Thread) appropriately.
616 started = _thread.allocate_lock()
617 finish = _thread.allocate_lock()
618 started.acquire()
619 finish.acquire()
620 def f():
621 started.release()
622 finish.acquire()
623 t = threading.Thread(target=f)
624 t.start()
625 started.acquire()
626 self.assertIn("started", repr(t))
627 finish.release()
628 # "stopped" should appear in the repr in a reasonable amount of time.
629 # Implementation detail: as of this writing, that's trivially true
630 # if .join() is called, and almost trivially true if .is_alive() is
631 # called. The detail we're testing here is that "stopped" shows up
632 # "all on its own".
633 LOOKING_FOR = "stopped"
634 for i in range(500):
635 if LOOKING_FOR in repr(t):
636 break
637 time.sleep(0.01)
638 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700639 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000640
Tim Peters7634e1c2013-10-08 20:55:51 -0500641 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500642 # BoundedSemaphore should raise ValueError if released too often.
643 for limit in range(1, 10):
644 bs = threading.BoundedSemaphore(limit)
645 threads = [threading.Thread(target=bs.acquire)
646 for _ in range(limit)]
647 for t in threads:
648 t.start()
649 for t in threads:
650 t.join()
651 threads = [threading.Thread(target=bs.release)
652 for _ in range(limit)]
653 for t in threads:
654 t.start()
655 for t in threads:
656 t.join()
657 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500658
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200659 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100660 def test_frame_tstate_tracing(self):
661 # Issue #14432: Crash when a generator is created in a C thread that is
662 # destroyed while the generator is still used. The issue was that a
663 # generator contains a frame, and the frame kept a reference to the
664 # Python state of the destroyed C thread. The crash occurs when a trace
665 # function is setup.
666
667 def noop_trace(frame, event, arg):
668 # no operation
669 return noop_trace
670
671 def generator():
672 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300673 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100674
675 def callback():
676 if callback.gen is None:
677 callback.gen = generator()
678 return next(callback.gen)
679 callback.gen = None
680
681 old_trace = sys.gettrace()
682 sys.settrace(noop_trace)
683 try:
684 # Install a trace function
685 threading.settrace(noop_trace)
686
687 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200688 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100689 _testcapi.call_in_temporary_c_thread(callback)
690
691 # Call the generator in a different Python thread, check that the
692 # generator didn't keep a reference to the destroyed thread state
693 for test in range(3):
694 # The trace function is still called here
695 callback()
696 finally:
697 sys.settrace(old_trace)
698
Victor Stinner45956b92013-11-12 16:37:55 +0100699
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000700class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000701
702 def _run_and_join(self, script):
703 script = """if 1:
704 import sys, os, time, threading
705
706 # a thread, which waits for the main program to terminate
707 def joiningfunc(mainthread):
708 mainthread.join()
709 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000710 # stdout is fully buffered because not a tty, we have to flush
711 # before exit.
712 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000713 \n""" + script
714
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200715 rc, out, err = assert_python_ok("-c", script)
716 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000717 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000718
719 def test_1_join_on_shutdown(self):
720 # The usual case: on exit, wait for a non-daemon thread
721 script = """if 1:
722 import os
723 t = threading.Thread(target=joiningfunc,
724 args=(threading.current_thread(),))
725 t.start()
726 time.sleep(0.1)
727 print('end of main')
728 """
729 self._run_and_join(script)
730
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000731 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200732 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000733 def test_2_join_in_forked_process(self):
734 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000735 script = """if 1:
736 childpid = os.fork()
737 if childpid != 0:
738 os.waitpid(childpid, 0)
739 sys.exit(0)
740
741 t = threading.Thread(target=joiningfunc,
742 args=(threading.current_thread(),))
743 t.start()
744 print('end of main')
745 """
746 self._run_and_join(script)
747
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000748 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200749 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000750 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000751 # Like the test above, but fork() was called from a worker thread
752 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000753
Jesse Nollera8513972008-07-17 16:49:17 +0000754 script = """if 1:
755 main_thread = threading.current_thread()
756 def worker():
757 childpid = os.fork()
758 if childpid != 0:
759 os.waitpid(childpid, 0)
760 sys.exit(0)
761
762 t = threading.Thread(target=joiningfunc,
763 args=(main_thread,))
764 print('end of main')
765 t.start()
766 t.join() # Should not block: main_thread is already stopped
767
768 w = threading.Thread(target=worker)
769 w.start()
770 """
771 self._run_and_join(script)
772
Victor Stinner26d31862011-07-01 14:26:24 +0200773 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500774 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200775 # Check that a daemon thread cannot crash the interpreter on shutdown
776 # by manipulating internal structures that are being disposed of in
777 # the main thread.
778 script = """if True:
779 import os
780 import random
781 import sys
782 import time
783 import threading
784
785 thread_has_run = set()
786
787 def random_io():
788 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200789 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200790 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200791 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200792 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200793 null_f.write(stuff)
794 time.sleep(random.random() / 1995)
795 null_f.close()
796 in_f.close()
797 thread_has_run.add(threading.current_thread())
798
799 def main():
800 count = 0
801 for _ in range(40):
802 new_thread = threading.Thread(target=random_io)
803 new_thread.daemon = True
804 new_thread.start()
805 count += 1
806 while len(thread_has_run) < count:
807 time.sleep(0.001)
808 # Trigger process shutdown
809 sys.exit(0)
810
811 main()
812 """
813 rc, out, err = assert_python_ok('-c', script)
814 self.assertFalse(err)
815
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100816 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100817 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100818 def test_reinit_tls_after_fork(self):
819 # Issue #13817: fork() would deadlock in a multithreaded program with
820 # the ad-hoc TLS implementation.
821
822 def do_fork_and_wait():
823 # just fork a child process and wait it
824 pid = os.fork()
825 if pid > 0:
826 os.waitpid(pid, 0)
827 else:
828 os._exit(0)
829
830 # start a bunch of threads that will fork() child processes
831 threads = []
832 for i in range(16):
833 t = threading.Thread(target=do_fork_and_wait)
834 threads.append(t)
835 t.start()
836
837 for t in threads:
838 t.join()
839
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200840 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
841 def test_clear_threads_states_after_fork(self):
842 # Issue #17094: check that threads states are cleared after fork()
843
844 # start a bunch of threads
845 threads = []
846 for i in range(16):
847 t = threading.Thread(target=lambda : time.sleep(0.3))
848 threads.append(t)
849 t.start()
850
851 pid = os.fork()
852 if pid == 0:
853 # check that threads states have been cleared
854 if len(sys._current_frames()) == 1:
855 os._exit(0)
856 else:
857 os._exit(1)
858 else:
859 _, status = os.waitpid(pid, 0)
860 self.assertEqual(0, status)
861
862 for t in threads:
863 t.join()
864
Jesse Nollera8513972008-07-17 16:49:17 +0000865
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200866class SubinterpThreadingTests(BaseTestCase):
867
868 def test_threads_join(self):
869 # Non-daemon threads should be joined at subinterpreter shutdown
870 # (issue #18808)
871 r, w = os.pipe()
872 self.addCleanup(os.close, r)
873 self.addCleanup(os.close, w)
874 code = r"""if 1:
875 import os
876 import threading
877 import time
878
879 def f():
880 # Sleep a bit so that the thread is still running when
881 # Py_EndInterpreter is called.
882 time.sleep(0.05)
883 os.write(%d, b"x")
884 threading.Thread(target=f).start()
885 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100886 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200887 self.assertEqual(ret, 0)
888 # The thread was joined properly.
889 self.assertEqual(os.read(r, 1), b"x")
890
Antoine Pitrou7b476992013-09-07 23:38:37 +0200891 def test_threads_join_2(self):
892 # Same as above, but a delay gets introduced after the thread's
893 # Python code returned but before the thread state is deleted.
894 # To achieve this, we register a thread-local object which sleeps
895 # a bit when deallocated.
896 r, w = os.pipe()
897 self.addCleanup(os.close, r)
898 self.addCleanup(os.close, w)
899 code = r"""if 1:
900 import os
901 import threading
902 import time
903
904 class Sleeper:
905 def __del__(self):
906 time.sleep(0.05)
907
908 tls = threading.local()
909
910 def f():
911 # Sleep a bit so that the thread is still running when
912 # Py_EndInterpreter is called.
913 time.sleep(0.05)
914 tls.x = Sleeper()
915 os.write(%d, b"x")
916 threading.Thread(target=f).start()
917 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100918 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200919 self.assertEqual(ret, 0)
920 # The thread was joined properly.
921 self.assertEqual(os.read(r, 1), b"x")
922
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200923 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200924 def test_daemon_threads_fatal_error(self):
925 subinterp_code = r"""if 1:
926 import os
927 import threading
928 import time
929
930 def f():
931 # Make sure the daemon thread is still running when
932 # Py_EndInterpreter is called.
933 time.sleep(10)
934 threading.Thread(target=f, daemon=True).start()
935 """
936 script = r"""if 1:
937 import _testcapi
938
939 _testcapi.run_in_subinterp(%r)
940 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200941 with test.support.SuppressCrashReport():
942 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200943 self.assertIn("Fatal Python error: Py_EndInterpreter: "
944 "not the last thread", err.decode())
945
946
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000947class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000948 # A RuntimeError should be raised if Thread.start() is called
949 # multiple times.
950 def test_start_thread_again(self):
951 thread = threading.Thread()
952 thread.start()
953 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700954 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000955
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000956 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000957 current_thread = threading.current_thread()
958 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000959
960 def test_joining_inactive_thread(self):
961 thread = threading.Thread()
962 self.assertRaises(RuntimeError, thread.join)
963
964 def test_daemonize_active_thread(self):
965 thread = threading.Thread()
966 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000967 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700968 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000969
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000970 def test_releasing_unacquired_lock(self):
971 lock = threading.Lock()
972 self.assertRaises(RuntimeError, lock.release)
973
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400974 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
975 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700976 def test_recursion_limit(self):
977 # Issue 9670
978 # test that excessive recursion within a non-main thread causes
979 # an exception rather than crashing the interpreter on platforms
980 # like Mac OS X or FreeBSD which have small default stack sizes
981 # for threads
982 script = """if True:
983 import threading
984
985 def recurse():
986 return recurse()
987
988 def outer():
989 try:
990 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400991 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700992 pass
993
994 w = threading.Thread(target=outer)
995 w.start()
996 w.join()
997 print('end of main thread')
998 """
999 expected_output = "end of main thread\n"
1000 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001001 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001002 stdout, stderr = p.communicate()
1003 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001004 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001005 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001006
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001007 def test_print_exception(self):
1008 script = r"""if True:
1009 import threading
1010 import time
1011
1012 running = False
1013 def run():
1014 global running
1015 running = True
1016 while running:
1017 time.sleep(0.01)
1018 1/0
1019 t = threading.Thread(target=run)
1020 t.start()
1021 while not running:
1022 time.sleep(0.01)
1023 running = False
1024 t.join()
1025 """
1026 rc, out, err = assert_python_ok("-c", script)
1027 self.assertEqual(out, b'')
1028 err = err.decode()
1029 self.assertIn("Exception in thread", err)
1030 self.assertIn("Traceback (most recent call last):", err)
1031 self.assertIn("ZeroDivisionError", err)
1032 self.assertNotIn("Unhandled exception", err)
1033
Serhiy Storchakaa7930372016-07-03 22:27:26 +03001034 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001035 def test_print_exception_stderr_is_none_1(self):
1036 script = r"""if True:
1037 import sys
1038 import threading
1039 import time
1040
1041 running = False
1042 def run():
1043 global running
1044 running = True
1045 while running:
1046 time.sleep(0.01)
1047 1/0
1048 t = threading.Thread(target=run)
1049 t.start()
1050 while not running:
1051 time.sleep(0.01)
1052 sys.stderr = None
1053 running = False
1054 t.join()
1055 """
1056 rc, out, err = assert_python_ok("-c", script)
1057 self.assertEqual(out, b'')
1058 err = err.decode()
1059 self.assertIn("Exception in thread", err)
1060 self.assertIn("Traceback (most recent call last):", err)
1061 self.assertIn("ZeroDivisionError", err)
1062 self.assertNotIn("Unhandled exception", err)
1063
1064 def test_print_exception_stderr_is_none_2(self):
1065 script = r"""if True:
1066 import sys
1067 import threading
1068 import time
1069
1070 running = False
1071 def run():
1072 global running
1073 running = True
1074 while running:
1075 time.sleep(0.01)
1076 1/0
1077 sys.stderr = None
1078 t = threading.Thread(target=run)
1079 t.start()
1080 while not running:
1081 time.sleep(0.01)
1082 running = False
1083 t.join()
1084 """
1085 rc, out, err = assert_python_ok("-c", script)
1086 self.assertEqual(out, b'')
1087 self.assertNotIn("Unhandled exception", err.decode())
1088
Victor Stinnereec93312016-08-18 18:13:10 +02001089 def test_bare_raise_in_brand_new_thread(self):
1090 def bare_raise():
1091 raise
1092
1093 class Issue27558(threading.Thread):
1094 exc = None
1095
1096 def run(self):
1097 try:
1098 bare_raise()
1099 except Exception as exc:
1100 self.exc = exc
1101
1102 thread = Issue27558()
1103 thread.start()
1104 thread.join()
1105 self.assertIsNotNone(thread.exc)
1106 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001107 # explicitly break the reference cycle to not leak a dangling thread
1108 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001109
R David Murray19aeb432013-03-30 17:19:38 -04001110class TimerTests(BaseTestCase):
1111
1112 def setUp(self):
1113 BaseTestCase.setUp(self)
1114 self.callback_args = []
1115 self.callback_event = threading.Event()
1116
1117 def test_init_immutable_default_args(self):
1118 # Issue 17435: constructor defaults were mutable objects, they could be
1119 # mutated via the object attributes and affect other Timer objects.
1120 timer1 = threading.Timer(0.01, self._callback_spy)
1121 timer1.start()
1122 self.callback_event.wait()
1123 timer1.args.append("blah")
1124 timer1.kwargs["foo"] = "bar"
1125 self.callback_event.clear()
1126 timer2 = threading.Timer(0.01, self._callback_spy)
1127 timer2.start()
1128 self.callback_event.wait()
1129 self.assertEqual(len(self.callback_args), 2)
1130 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001131 timer1.join()
1132 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001133
1134 def _callback_spy(self, *args, **kwargs):
1135 self.callback_args.append((args[:], kwargs.copy()))
1136 self.callback_event.set()
1137
Antoine Pitrou557934f2009-11-06 22:41:14 +00001138class LockTests(lock_tests.LockTests):
1139 locktype = staticmethod(threading.Lock)
1140
Antoine Pitrou434736a2009-11-10 18:46:01 +00001141class PyRLockTests(lock_tests.RLockTests):
1142 locktype = staticmethod(threading._PyRLock)
1143
Charles-François Natali6b671b22012-01-28 11:36:04 +01001144@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001145class CRLockTests(lock_tests.RLockTests):
1146 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001147
1148class EventTests(lock_tests.EventTests):
1149 eventtype = staticmethod(threading.Event)
1150
1151class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001152 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001153 locktype = staticmethod(threading.Condition)
1154
1155class ConditionTests(lock_tests.ConditionTests):
1156 condtype = staticmethod(threading.Condition)
1157
1158class SemaphoreTests(lock_tests.SemaphoreTests):
1159 semtype = staticmethod(threading.Semaphore)
1160
1161class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1162 semtype = staticmethod(threading.BoundedSemaphore)
1163
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001164class BarrierTests(lock_tests.BarrierTests):
1165 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001166
Martin Panter19e69c52015-11-14 12:46:42 +00001167class MiscTestCase(unittest.TestCase):
1168 def test__all__(self):
1169 extra = {"ThreadError"}
1170 blacklist = {'currentThread', 'activeCount'}
1171 support.check__all__(self, threading, ('threading', '_thread'),
1172 extra=extra, blacklist=blacklist)
1173
Tim Peters84d54892005-01-08 06:03:17 +00001174if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001175 unittest.main()