blob: f7c3680bda379b5ab17fe7d5a16f99ed64649857 [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.
28platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
29 'hp-ux11')
30
31
Tim Peters84d54892005-01-08 06:03:17 +000032# A trivial mutable counter.
33class Counter(object):
34 def __init__(self):
35 self.value = 0
36 def inc(self):
37 self.value += 1
38 def dec(self):
39 self.value -= 1
40 def get(self):
41 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000042
43class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000044 def __init__(self, name, testcase, sema, mutex, nrunning):
45 threading.Thread.__init__(self, name=name)
46 self.testcase = testcase
47 self.sema = sema
48 self.mutex = mutex
49 self.nrunning = nrunning
50
Skip Montanaro4533f602001-08-20 20:28:48 +000051 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000052 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000053 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000054 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000055 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000056
Christian Heimes4fbc72b2008-03-22 00:47:35 +000057 with self.sema:
58 with self.mutex:
59 self.nrunning.inc()
60 if verbose:
61 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020062 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000063
Christian Heimes4fbc72b2008-03-22 00:47:35 +000064 time.sleep(delay)
65 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000066 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000067
Christian Heimes4fbc72b2008-03-22 00:47:35 +000068 with self.mutex:
69 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020070 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 if verbose:
72 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000073 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000074
Skip Montanaro4533f602001-08-20 20:28:48 +000075
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000076class BaseTestCase(unittest.TestCase):
77 def setUp(self):
78 self._threads = test.support.threading_setup()
79
80 def tearDown(self):
81 test.support.threading_cleanup(*self._threads)
82 test.support.reap_children()
83
84
85class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000086
Tim Peters84d54892005-01-08 06:03:17 +000087 # Create a bunch of threads, let each do some work, wait until all are
88 # done.
89 def test_various_ops(self):
90 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
91 # times about 1 second per clump).
92 NUMTASKS = 10
93
94 # no more than 3 of the 10 can run at once
95 sema = threading.BoundedSemaphore(value=3)
96 mutex = threading.RLock()
97 numrunning = Counter()
98
99 threads = []
100
101 for i in range(NUMTASKS):
102 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
103 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200104 self.assertIsNone(t.ident)
105 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000106 t.start()
107
108 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000110 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200111 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200112 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200114 self.assertIsNotNone(t.ident)
115 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000116 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000117 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000118 self.assertEqual(numrunning.get(), 0)
119
Benjamin Petersond23f8222009-04-05 19:13:16 +0000120 def test_ident_of_no_threading_threads(self):
121 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200122 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000123 def f():
124 ident.append(threading.currentThread().ident)
125 done.set()
126 done = threading.Event()
127 ident = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700128 with support.wait_threads_exit():
129 tid = _thread.start_new_thread(f, ())
130 done.wait()
131 self.assertEqual(ident[0], tid)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000132 # Kill the "immortal" _DummyThread
133 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000134
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 # run with a small(ish) thread stack size (256kB)
136 def test_various_ops_small_stack(self):
137 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000138 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 try:
140 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000141 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000142 raise unittest.SkipTest(
143 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 self.test_various_ops()
145 threading.stack_size(0)
146
147 # run with a large thread stack size (1MB)
148 def test_various_ops_large_stack(self):
149 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000150 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151 try:
152 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000153 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000154 raise unittest.SkipTest(
155 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156 self.test_various_ops()
157 threading.stack_size(0)
158
Tim Peters711906e2005-01-08 07:30:42 +0000159 def test_foreign_thread(self):
160 # Check that a "foreign" thread can use the threading module.
161 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000162 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000163 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000164 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000165 mutex.release()
166
167 mutex = threading.Lock()
168 mutex.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700169 with support.wait_threads_exit():
170 tid = _thread.start_new_thread(f, (mutex,))
171 # Wait for the thread to finish.
172 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000173 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000174 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800175 #Issue 29376
176 self.assertTrue(threading._active[tid].is_alive())
177 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000178 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000179
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
181 # exposed at the Python level. This test relies on ctypes to get at it.
182 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200183 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000184
185 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200186 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000187
188 class AsyncExc(Exception):
189 pass
190
191 exception = ctypes.py_object(AsyncExc)
192
Antoine Pitroube4d8092009-10-18 18:27:17 +0000193 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200194 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200195 self.assertIsInstance(tid, int)
196 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000197
198 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200199 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000200 # The exception is async, so we might have to keep the VM busy until
201 # it notices.
202 while True:
203 pass
204 except AsyncExc:
205 pass
206 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000207 # This code is unreachable but it reflects the intent. If we wanted
208 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000209 self.fail("AsyncExc not raised")
210 try:
211 self.assertEqual(result, 1) # one thread state modified
212 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000213 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000214 pass
215
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000216 # `worker_started` is set by the thread when it's inside a try/except
217 # block waiting to catch the asynchronously set AsyncExc exception.
218 # `worker_saw_exception` is set by the thread upon catching that
219 # exception.
220 worker_started = threading.Event()
221 worker_saw_exception = threading.Event()
222
223 class Worker(threading.Thread):
224 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200225 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000226 self.finished = False
227
228 try:
229 while True:
230 worker_started.set()
231 time.sleep(0.1)
232 except AsyncExc:
233 self.finished = True
234 worker_saw_exception.set()
235
236 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000237 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000238 t.start()
239 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241
242 # Try a thread id that doesn't make sense.
243 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200245 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 self.assertEqual(result, 0) # no thread states modified
247
248 # Now raise an exception in the worker thread.
249 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000251 ret = worker_started.wait()
252 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000253 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000254 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200255 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000256 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000257 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200258 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000259 self.assertEqual(result, 1) # one thread state modified
260 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000261 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000262 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000263 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000264 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000265 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000266 if t.finished:
267 t.join()
268 # else the thread is still running, and we have no way to kill it
269
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000270 def test_limbo_cleanup(self):
271 # Issue 7481: Failure to start thread should cleanup the limbo map.
272 def fail_new_thread(*args):
273 raise threading.ThreadError()
274 _start_new_thread = threading._start_new_thread
275 threading._start_new_thread = fail_new_thread
276 try:
277 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000278 self.assertRaises(threading.ThreadError, t.start)
279 self.assertFalse(
280 t in threading._limbo,
281 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000282 finally:
283 threading._start_new_thread = _start_new_thread
284
Christian Heimes7d2ff882007-11-30 14:35:04 +0000285 def test_finalize_runnning_thread(self):
286 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
287 # very late on python exit: on deallocation of a running thread for
288 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200289 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000290
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200291 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000292 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000293
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000294 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000295 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000296 ready.acquire()
297
Christian Heimes7d2ff882007-11-30 14:35:04 +0000298 # Module globals are cleared before __del__ is run
299 # So we save the functions in class dict
300 class C:
301 ensure = ctypes.pythonapi.PyGILState_Ensure
302 release = ctypes.pythonapi.PyGILState_Release
303 def __del__(self):
304 state = self.ensure()
305 self.release(state)
306
307 def waitingThread():
308 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000309 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000310 time.sleep(100)
311
Georg Brandl2067bfd2008-05-25 13:05:15 +0000312 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000313 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000314 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200315 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000316 self.assertEqual(rc, 42)
317
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000318 def test_finalize_with_trace(self):
319 # Issue1733757
320 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200321 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000322 import sys, threading
323
324 # A deadlock-killer, to prevent the
325 # testsuite to hang forever
326 def killer():
327 import os, time
328 time.sleep(2)
329 print('program blocked; aborting')
330 os._exit(2)
331 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000332 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000333 t.start()
334
335 # This is the trace function
336 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000337 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000338 return func
339
340 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200341 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000342
Antoine Pitrou011bd622009-10-20 21:52:47 +0000343 def test_join_nondaemon_on_shutdown(self):
344 # Issue 1722344
345 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200346 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000347 import threading
348 from time import sleep
349
350 def child():
351 sleep(1)
352 # As a non-daemon thread we SHOULD wake up and nothing
353 # should be torn down yet
354 print("Woke up, sleep function is:", sleep)
355
356 threading.Thread(target=child).start()
357 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200358 """)
359 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000360 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200361 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000362
Christian Heimes1af737c2008-01-23 08:24:23 +0000363 def test_enumerate_after_join(self):
364 # Try hard to trigger #1703448: a thread is still returned in
365 # threading.enumerate() after it has been join()ed.
366 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000367 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000368 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000369 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000370 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000371 t = threading.Thread(target=lambda: None)
372 t.start()
373 t.join()
374 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000375 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000376 "#1703448 triggered after %d trials: %s" % (i, l))
377 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000378 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000379
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000380 def test_no_refcycle_through_target(self):
381 class RunSelfFunction(object):
382 def __init__(self, should_raise):
383 # The links in this refcycle from Thread back to self
384 # should be cleaned up when the thread completes.
385 self.should_raise = should_raise
386 self.thread = threading.Thread(target=self._run,
387 args=(self,),
388 kwargs={'yet_another':self})
389 self.thread.start()
390
391 def _run(self, other_ref, yet_another):
392 if self.should_raise:
393 raise SystemExit
394
395 cyclic_object = RunSelfFunction(should_raise=False)
396 weak_cyclic_object = weakref.ref(cyclic_object)
397 cyclic_object.thread.join()
398 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000399 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000400 msg=('%d references still around' %
401 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000402
403 raising_cyclic_object = RunSelfFunction(should_raise=True)
404 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
405 raising_cyclic_object.thread.join()
406 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000407 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000408 msg=('%d references still around' %
409 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000410
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000411 def test_old_threading_api(self):
412 # Just a quick sanity check to make sure the old method names are
413 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000414 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000415 t.isDaemon()
416 t.setDaemon(True)
417 t.getName()
418 t.setName("name")
419 t.isAlive()
420 e = threading.Event()
421 e.isSet()
422 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000423
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000424 def test_repr_daemon(self):
425 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200426 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000427 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200428 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000429
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000430 def test_deamon_param(self):
431 t = threading.Thread()
432 self.assertFalse(t.daemon)
433 t = threading.Thread(daemon=False)
434 self.assertFalse(t.daemon)
435 t = threading.Thread(daemon=True)
436 self.assertTrue(t.daemon)
437
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200438 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
439 def test_dummy_thread_after_fork(self):
440 # Issue #14308: a dummy thread in the active list doesn't mess up
441 # the after-fork mechanism.
442 code = """if 1:
443 import _thread, threading, os, time
444
445 def background_thread(evt):
446 # Creates and registers the _DummyThread instance
447 threading.current_thread()
448 evt.set()
449 time.sleep(10)
450
451 evt = threading.Event()
452 _thread.start_new_thread(background_thread, (evt,))
453 evt.wait()
454 assert threading.active_count() == 2, threading.active_count()
455 if os.fork() == 0:
456 assert threading.active_count() == 1, threading.active_count()
457 os._exit(0)
458 else:
459 os.wait()
460 """
461 _, out, err = assert_python_ok("-c", code)
462 self.assertEqual(out, b'')
463 self.assertEqual(err, b'')
464
Charles-François Natali9939cc82013-08-30 23:32:53 +0200465 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
466 def test_is_alive_after_fork(self):
467 # Try hard to trigger #18418: is_alive() could sometimes be True on
468 # threads that vanished after a fork.
469 old_interval = sys.getswitchinterval()
470 self.addCleanup(sys.setswitchinterval, old_interval)
471
472 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100473 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200474
475 for i in range(20):
476 t = threading.Thread(target=lambda: None)
477 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200478 pid = os.fork()
479 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700480 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200481 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700482 t.join()
483
Charles-François Natali9939cc82013-08-30 23:32:53 +0200484 pid, status = os.waitpid(pid, 0)
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700485 self.assertTrue(os.WIFEXITED(status))
486 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200487
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300488 def test_main_thread(self):
489 main = threading.main_thread()
490 self.assertEqual(main.name, 'MainThread')
491 self.assertEqual(main.ident, threading.current_thread().ident)
492 self.assertEqual(main.ident, threading.get_ident())
493
494 def f():
495 self.assertNotEqual(threading.main_thread().ident,
496 threading.current_thread().ident)
497 th = threading.Thread(target=f)
498 th.start()
499 th.join()
500
501 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
502 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
503 def test_main_thread_after_fork(self):
504 code = """if 1:
505 import os, threading
506
507 pid = os.fork()
508 if pid == 0:
509 main = threading.main_thread()
510 print(main.name)
511 print(main.ident == threading.current_thread().ident)
512 print(main.ident == threading.get_ident())
513 else:
514 os.waitpid(pid, 0)
515 """
516 _, out, err = assert_python_ok("-c", code)
517 data = out.decode().replace('\r', '')
518 self.assertEqual(err, b"")
519 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
520
521 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
522 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
523 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
524 def test_main_thread_after_fork_from_nonmain_thread(self):
525 code = """if 1:
526 import os, threading, sys
527
528 def f():
529 pid = os.fork()
530 if pid == 0:
531 main = threading.main_thread()
532 print(main.name)
533 print(main.ident == threading.current_thread().ident)
534 print(main.ident == threading.get_ident())
535 # stdout is fully buffered because not a tty,
536 # we have to flush before exit.
537 sys.stdout.flush()
538 else:
539 os.waitpid(pid, 0)
540
541 th = threading.Thread(target=f)
542 th.start()
543 th.join()
544 """
545 _, out, err = assert_python_ok("-c", code)
546 data = out.decode().replace('\r', '')
547 self.assertEqual(err, b"")
548 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
549
Antoine Pitrou7b476992013-09-07 23:38:37 +0200550 def test_tstate_lock(self):
551 # Test an implementation detail of Thread objects.
552 started = _thread.allocate_lock()
553 finish = _thread.allocate_lock()
554 started.acquire()
555 finish.acquire()
556 def f():
557 started.release()
558 finish.acquire()
559 time.sleep(0.01)
560 # The tstate lock is None until the thread is started
561 t = threading.Thread(target=f)
562 self.assertIs(t._tstate_lock, None)
563 t.start()
564 started.acquire()
565 self.assertTrue(t.is_alive())
566 # The tstate lock can't be acquired when the thread is running
567 # (or suspended).
568 tstate_lock = t._tstate_lock
569 self.assertFalse(tstate_lock.acquire(timeout=0), False)
570 finish.release()
571 # When the thread ends, the state_lock can be successfully
572 # acquired.
573 self.assertTrue(tstate_lock.acquire(timeout=5), False)
574 # But is_alive() is still True: we hold _tstate_lock now, which
575 # prevents is_alive() from knowing the thread's end-of-life C code
576 # is done.
577 self.assertTrue(t.is_alive())
578 # Let is_alive() find out the C code is done.
579 tstate_lock.release()
580 self.assertFalse(t.is_alive())
581 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200582 self.assertIsNone(t._tstate_lock)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700583 t.join()
Antoine Pitrou7b476992013-09-07 23:38:37 +0200584
Tim Peters72460fa2013-09-09 18:48:24 -0500585 def test_repr_stopped(self):
586 # Verify that "stopped" shows up in repr(Thread) appropriately.
587 started = _thread.allocate_lock()
588 finish = _thread.allocate_lock()
589 started.acquire()
590 finish.acquire()
591 def f():
592 started.release()
593 finish.acquire()
594 t = threading.Thread(target=f)
595 t.start()
596 started.acquire()
597 self.assertIn("started", repr(t))
598 finish.release()
599 # "stopped" should appear in the repr in a reasonable amount of time.
600 # Implementation detail: as of this writing, that's trivially true
601 # if .join() is called, and almost trivially true if .is_alive() is
602 # called. The detail we're testing here is that "stopped" shows up
603 # "all on its own".
604 LOOKING_FOR = "stopped"
605 for i in range(500):
606 if LOOKING_FOR in repr(t):
607 break
608 time.sleep(0.01)
609 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700610 t.join()
Christian Heimes1af737c2008-01-23 08:24:23 +0000611
Tim Peters7634e1c2013-10-08 20:55:51 -0500612 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500613 # BoundedSemaphore should raise ValueError if released too often.
614 for limit in range(1, 10):
615 bs = threading.BoundedSemaphore(limit)
616 threads = [threading.Thread(target=bs.acquire)
617 for _ in range(limit)]
618 for t in threads:
619 t.start()
620 for t in threads:
621 t.join()
622 threads = [threading.Thread(target=bs.release)
623 for _ in range(limit)]
624 for t in threads:
625 t.start()
626 for t in threads:
627 t.join()
628 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500629
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200630 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100631 def test_frame_tstate_tracing(self):
632 # Issue #14432: Crash when a generator is created in a C thread that is
633 # destroyed while the generator is still used. The issue was that a
634 # generator contains a frame, and the frame kept a reference to the
635 # Python state of the destroyed C thread. The crash occurs when a trace
636 # function is setup.
637
638 def noop_trace(frame, event, arg):
639 # no operation
640 return noop_trace
641
642 def generator():
643 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300644 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100645
646 def callback():
647 if callback.gen is None:
648 callback.gen = generator()
649 return next(callback.gen)
650 callback.gen = None
651
652 old_trace = sys.gettrace()
653 sys.settrace(noop_trace)
654 try:
655 # Install a trace function
656 threading.settrace(noop_trace)
657
658 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200659 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100660 _testcapi.call_in_temporary_c_thread(callback)
661
662 # Call the generator in a different Python thread, check that the
663 # generator didn't keep a reference to the destroyed thread state
664 for test in range(3):
665 # The trace function is still called here
666 callback()
667 finally:
668 sys.settrace(old_trace)
669
Victor Stinner45956b92013-11-12 16:37:55 +0100670
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000671class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000672
673 def _run_and_join(self, script):
674 script = """if 1:
675 import sys, os, time, threading
676
677 # a thread, which waits for the main program to terminate
678 def joiningfunc(mainthread):
679 mainthread.join()
680 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000681 # stdout is fully buffered because not a tty, we have to flush
682 # before exit.
683 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000684 \n""" + script
685
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200686 rc, out, err = assert_python_ok("-c", script)
687 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000688 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000689
690 def test_1_join_on_shutdown(self):
691 # The usual case: on exit, wait for a non-daemon thread
692 script = """if 1:
693 import os
694 t = threading.Thread(target=joiningfunc,
695 args=(threading.current_thread(),))
696 t.start()
697 time.sleep(0.1)
698 print('end of main')
699 """
700 self._run_and_join(script)
701
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000702 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200703 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000704 def test_2_join_in_forked_process(self):
705 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000706 script = """if 1:
707 childpid = os.fork()
708 if childpid != 0:
709 os.waitpid(childpid, 0)
710 sys.exit(0)
711
712 t = threading.Thread(target=joiningfunc,
713 args=(threading.current_thread(),))
714 t.start()
715 print('end of main')
716 """
717 self._run_and_join(script)
718
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000719 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200720 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000721 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000722 # Like the test above, but fork() was called from a worker thread
723 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000724
Jesse Nollera8513972008-07-17 16:49:17 +0000725 script = """if 1:
726 main_thread = threading.current_thread()
727 def worker():
728 childpid = os.fork()
729 if childpid != 0:
730 os.waitpid(childpid, 0)
731 sys.exit(0)
732
733 t = threading.Thread(target=joiningfunc,
734 args=(main_thread,))
735 print('end of main')
736 t.start()
737 t.join() # Should not block: main_thread is already stopped
738
739 w = threading.Thread(target=worker)
740 w.start()
741 """
742 self._run_and_join(script)
743
Victor Stinner26d31862011-07-01 14:26:24 +0200744 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500745 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200746 # Check that a daemon thread cannot crash the interpreter on shutdown
747 # by manipulating internal structures that are being disposed of in
748 # the main thread.
749 script = """if True:
750 import os
751 import random
752 import sys
753 import time
754 import threading
755
756 thread_has_run = set()
757
758 def random_io():
759 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200760 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200761 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200762 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200763 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200764 null_f.write(stuff)
765 time.sleep(random.random() / 1995)
766 null_f.close()
767 in_f.close()
768 thread_has_run.add(threading.current_thread())
769
770 def main():
771 count = 0
772 for _ in range(40):
773 new_thread = threading.Thread(target=random_io)
774 new_thread.daemon = True
775 new_thread.start()
776 count += 1
777 while len(thread_has_run) < count:
778 time.sleep(0.001)
779 # Trigger process shutdown
780 sys.exit(0)
781
782 main()
783 """
784 rc, out, err = assert_python_ok('-c', script)
785 self.assertFalse(err)
786
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100787 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100788 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100789 def test_reinit_tls_after_fork(self):
790 # Issue #13817: fork() would deadlock in a multithreaded program with
791 # the ad-hoc TLS implementation.
792
793 def do_fork_and_wait():
794 # just fork a child process and wait it
795 pid = os.fork()
796 if pid > 0:
797 os.waitpid(pid, 0)
798 else:
799 os._exit(0)
800
801 # start a bunch of threads that will fork() child processes
802 threads = []
803 for i in range(16):
804 t = threading.Thread(target=do_fork_and_wait)
805 threads.append(t)
806 t.start()
807
808 for t in threads:
809 t.join()
810
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200811 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
812 def test_clear_threads_states_after_fork(self):
813 # Issue #17094: check that threads states are cleared after fork()
814
815 # start a bunch of threads
816 threads = []
817 for i in range(16):
818 t = threading.Thread(target=lambda : time.sleep(0.3))
819 threads.append(t)
820 t.start()
821
822 pid = os.fork()
823 if pid == 0:
824 # check that threads states have been cleared
825 if len(sys._current_frames()) == 1:
826 os._exit(0)
827 else:
828 os._exit(1)
829 else:
830 _, status = os.waitpid(pid, 0)
831 self.assertEqual(0, status)
832
833 for t in threads:
834 t.join()
835
Jesse Nollera8513972008-07-17 16:49:17 +0000836
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200837class SubinterpThreadingTests(BaseTestCase):
838
839 def test_threads_join(self):
840 # Non-daemon threads should be joined at subinterpreter shutdown
841 # (issue #18808)
842 r, w = os.pipe()
843 self.addCleanup(os.close, r)
844 self.addCleanup(os.close, w)
845 code = r"""if 1:
846 import os
847 import threading
848 import time
849
850 def f():
851 # Sleep a bit so that the thread is still running when
852 # Py_EndInterpreter is called.
853 time.sleep(0.05)
854 os.write(%d, b"x")
855 threading.Thread(target=f).start()
856 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100857 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200858 self.assertEqual(ret, 0)
859 # The thread was joined properly.
860 self.assertEqual(os.read(r, 1), b"x")
861
Antoine Pitrou7b476992013-09-07 23:38:37 +0200862 def test_threads_join_2(self):
863 # Same as above, but a delay gets introduced after the thread's
864 # Python code returned but before the thread state is deleted.
865 # To achieve this, we register a thread-local object which sleeps
866 # a bit when deallocated.
867 r, w = os.pipe()
868 self.addCleanup(os.close, r)
869 self.addCleanup(os.close, w)
870 code = r"""if 1:
871 import os
872 import threading
873 import time
874
875 class Sleeper:
876 def __del__(self):
877 time.sleep(0.05)
878
879 tls = threading.local()
880
881 def f():
882 # Sleep a bit so that the thread is still running when
883 # Py_EndInterpreter is called.
884 time.sleep(0.05)
885 tls.x = Sleeper()
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 Pitrou7b476992013-09-07 23:38:37 +0200890 self.assertEqual(ret, 0)
891 # The thread was joined properly.
892 self.assertEqual(os.read(r, 1), b"x")
893
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200894 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200895 def test_daemon_threads_fatal_error(self):
896 subinterp_code = r"""if 1:
897 import os
898 import threading
899 import time
900
901 def f():
902 # Make sure the daemon thread is still running when
903 # Py_EndInterpreter is called.
904 time.sleep(10)
905 threading.Thread(target=f, daemon=True).start()
906 """
907 script = r"""if 1:
908 import _testcapi
909
910 _testcapi.run_in_subinterp(%r)
911 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200912 with test.support.SuppressCrashReport():
913 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200914 self.assertIn("Fatal Python error: Py_EndInterpreter: "
915 "not the last thread", err.decode())
916
917
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000918class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000919 # A RuntimeError should be raised if Thread.start() is called
920 # multiple times.
921 def test_start_thread_again(self):
922 thread = threading.Thread()
923 thread.start()
924 self.assertRaises(RuntimeError, thread.start)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700925 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000926
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000927 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000928 current_thread = threading.current_thread()
929 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000930
931 def test_joining_inactive_thread(self):
932 thread = threading.Thread()
933 self.assertRaises(RuntimeError, thread.join)
934
935 def test_daemonize_active_thread(self):
936 thread = threading.Thread()
937 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000938 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Victor Stinnerb8c7be22017-09-14 13:05:21 -0700939 thread.join()
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000940
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000941 def test_releasing_unacquired_lock(self):
942 lock = threading.Lock()
943 self.assertRaises(RuntimeError, lock.release)
944
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400945 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
946 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700947 def test_recursion_limit(self):
948 # Issue 9670
949 # test that excessive recursion within a non-main thread causes
950 # an exception rather than crashing the interpreter on platforms
951 # like Mac OS X or FreeBSD which have small default stack sizes
952 # for threads
953 script = """if True:
954 import threading
955
956 def recurse():
957 return recurse()
958
959 def outer():
960 try:
961 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400962 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700963 pass
964
965 w = threading.Thread(target=outer)
966 w.start()
967 w.join()
968 print('end of main thread')
969 """
970 expected_output = "end of main thread\n"
971 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200972 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700973 stdout, stderr = p.communicate()
974 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200975 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700976 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000977
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300978 def test_print_exception(self):
979 script = r"""if True:
980 import threading
981 import time
982
983 running = False
984 def run():
985 global running
986 running = True
987 while running:
988 time.sleep(0.01)
989 1/0
990 t = threading.Thread(target=run)
991 t.start()
992 while not running:
993 time.sleep(0.01)
994 running = False
995 t.join()
996 """
997 rc, out, err = assert_python_ok("-c", script)
998 self.assertEqual(out, b'')
999 err = err.decode()
1000 self.assertIn("Exception in thread", err)
1001 self.assertIn("Traceback (most recent call last):", err)
1002 self.assertIn("ZeroDivisionError", err)
1003 self.assertNotIn("Unhandled exception", err)
1004
Serhiy Storchakaa7930372016-07-03 22:27:26 +03001005 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001006 def test_print_exception_stderr_is_none_1(self):
1007 script = r"""if True:
1008 import sys
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 sys.stderr = None
1024 running = False
1025 t.join()
1026 """
1027 rc, out, err = assert_python_ok("-c", script)
1028 self.assertEqual(out, b'')
1029 err = err.decode()
1030 self.assertIn("Exception in thread", err)
1031 self.assertIn("Traceback (most recent call last):", err)
1032 self.assertIn("ZeroDivisionError", err)
1033 self.assertNotIn("Unhandled exception", err)
1034
1035 def test_print_exception_stderr_is_none_2(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 sys.stderr = None
1049 t = threading.Thread(target=run)
1050 t.start()
1051 while not running:
1052 time.sleep(0.01)
1053 running = False
1054 t.join()
1055 """
1056 rc, out, err = assert_python_ok("-c", script)
1057 self.assertEqual(out, b'')
1058 self.assertNotIn("Unhandled exception", err.decode())
1059
Victor Stinnereec93312016-08-18 18:13:10 +02001060 def test_bare_raise_in_brand_new_thread(self):
1061 def bare_raise():
1062 raise
1063
1064 class Issue27558(threading.Thread):
1065 exc = None
1066
1067 def run(self):
1068 try:
1069 bare_raise()
1070 except Exception as exc:
1071 self.exc = exc
1072
1073 thread = Issue27558()
1074 thread.start()
1075 thread.join()
1076 self.assertIsNotNone(thread.exc)
1077 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001078 # explicitly break the reference cycle to not leak a dangling thread
1079 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001080
R David Murray19aeb432013-03-30 17:19:38 -04001081class TimerTests(BaseTestCase):
1082
1083 def setUp(self):
1084 BaseTestCase.setUp(self)
1085 self.callback_args = []
1086 self.callback_event = threading.Event()
1087
1088 def test_init_immutable_default_args(self):
1089 # Issue 17435: constructor defaults were mutable objects, they could be
1090 # mutated via the object attributes and affect other Timer objects.
1091 timer1 = threading.Timer(0.01, self._callback_spy)
1092 timer1.start()
1093 self.callback_event.wait()
1094 timer1.args.append("blah")
1095 timer1.kwargs["foo"] = "bar"
1096 self.callback_event.clear()
1097 timer2 = threading.Timer(0.01, self._callback_spy)
1098 timer2.start()
1099 self.callback_event.wait()
1100 self.assertEqual(len(self.callback_args), 2)
1101 self.assertEqual(self.callback_args, [((), {}), ((), {})])
Victor Stinnerda3e5cf2017-09-15 05:37:42 -07001102 timer1.join()
1103 timer2.join()
R David Murray19aeb432013-03-30 17:19:38 -04001104
1105 def _callback_spy(self, *args, **kwargs):
1106 self.callback_args.append((args[:], kwargs.copy()))
1107 self.callback_event.set()
1108
Antoine Pitrou557934f2009-11-06 22:41:14 +00001109class LockTests(lock_tests.LockTests):
1110 locktype = staticmethod(threading.Lock)
1111
Antoine Pitrou434736a2009-11-10 18:46:01 +00001112class PyRLockTests(lock_tests.RLockTests):
1113 locktype = staticmethod(threading._PyRLock)
1114
Charles-François Natali6b671b22012-01-28 11:36:04 +01001115@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001116class CRLockTests(lock_tests.RLockTests):
1117 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001118
1119class EventTests(lock_tests.EventTests):
1120 eventtype = staticmethod(threading.Event)
1121
1122class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001123 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001124 locktype = staticmethod(threading.Condition)
1125
1126class ConditionTests(lock_tests.ConditionTests):
1127 condtype = staticmethod(threading.Condition)
1128
1129class SemaphoreTests(lock_tests.SemaphoreTests):
1130 semtype = staticmethod(threading.Semaphore)
1131
1132class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1133 semtype = staticmethod(threading.BoundedSemaphore)
1134
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001135class BarrierTests(lock_tests.BarrierTests):
1136 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001137
Martin Panter19e69c52015-11-14 12:46:42 +00001138class MiscTestCase(unittest.TestCase):
1139 def test__all__(self):
1140 extra = {"ThreadError"}
1141 blacklist = {'currentThread', 'activeCount'}
1142 support.check__all__(self, threading, ('threading', '_thread'),
1143 extra=extra, blacklist=blacklist)
1144
Tim Peters84d54892005-01-08 06:03:17 +00001145if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001146 unittest.main()