blob: 800d26f71b289a207b563ea6dc16f1f52d2143bf [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 Pitrouc4d78642011-05-05 20:17:32 +020012_thread = import_module('_thread')
13threading = import_module('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 = []
128 _thread.start_new_thread(f, ())
129 done.wait()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200130 self.assertIsNotNone(ident[0])
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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000134 # run with a small(ish) thread stack size (256kB)
135 def test_various_ops_small_stack(self):
136 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000137 print('with 256kB 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
146 # run with a large thread stack size (1MB)
147 def test_various_ops_large_stack(self):
148 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print('with 1MB 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()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000168 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000169 # Wait for the thread to finish.
170 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000172 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhangf3a9fab2017-02-27 11:01:30 +0800173 #Issue 29376
174 self.assertTrue(threading._active[tid].is_alive())
175 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000176 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000177
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
179 # exposed at the Python level. This test relies on ctypes to get at it.
180 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200181 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182
183 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200184 set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000185
186 class AsyncExc(Exception):
187 pass
188
189 exception = ctypes.py_object(AsyncExc)
190
Antoine Pitroube4d8092009-10-18 18:27:17 +0000191 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200192 tid = threading.get_ident()
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 self.assertIsInstance(tid, int)
194 self.assertGreater(tid, 0)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000195
196 try:
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200197 result = set_async_exc(tid, exception)
Antoine Pitroube4d8092009-10-18 18:27:17 +0000198 # The exception is async, so we might have to keep the VM busy until
199 # it notices.
200 while True:
201 pass
202 except AsyncExc:
203 pass
204 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000205 # This code is unreachable but it reflects the intent. If we wanted
206 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000207 self.fail("AsyncExc not raised")
208 try:
209 self.assertEqual(result, 1) # one thread state modified
210 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000211 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000212 pass
213
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000214 # `worker_started` is set by the thread when it's inside a try/except
215 # block waiting to catch the asynchronously set AsyncExc exception.
216 # `worker_saw_exception` is set by the thread upon catching that
217 # exception.
218 worker_started = threading.Event()
219 worker_saw_exception = threading.Event()
220
221 class Worker(threading.Thread):
222 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200223 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000224 self.finished = False
225
226 try:
227 while True:
228 worker_started.set()
229 time.sleep(0.1)
230 except AsyncExc:
231 self.finished = True
232 worker_saw_exception.set()
233
234 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000235 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236 t.start()
237 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000238 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000239
240 # Try a thread id that doesn't make sense.
241 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000242 print(" trying nonsensical thread id")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200243 result = set_async_exc(-1, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 self.assertEqual(result, 0) # no thread states modified
245
246 # Now raise an exception in the worker thread.
247 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000248 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000249 ret = worker_started.wait()
250 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000251 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000252 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200253 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000254 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000255 print(" attempting to raise asynch exception in worker")
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200256 result = set_async_exc(t.id, exception)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000257 self.assertEqual(result, 1) # one thread state modified
258 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000259 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000260 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000261 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000262 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000263 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000264 if t.finished:
265 t.join()
266 # else the thread is still running, and we have no way to kill it
267
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000268 def test_limbo_cleanup(self):
269 # Issue 7481: Failure to start thread should cleanup the limbo map.
270 def fail_new_thread(*args):
271 raise threading.ThreadError()
272 _start_new_thread = threading._start_new_thread
273 threading._start_new_thread = fail_new_thread
274 try:
275 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000276 self.assertRaises(threading.ThreadError, t.start)
277 self.assertFalse(
278 t in threading._limbo,
279 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000280 finally:
281 threading._start_new_thread = _start_new_thread
282
Christian Heimes7d2ff882007-11-30 14:35:04 +0000283 def test_finalize_runnning_thread(self):
284 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
285 # very late on python exit: on deallocation of a running thread for
286 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200287 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000288
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200289 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000290 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000291
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000292 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000293 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000294 ready.acquire()
295
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296 # Module globals are cleared before __del__ is run
297 # So we save the functions in class dict
298 class C:
299 ensure = ctypes.pythonapi.PyGILState_Ensure
300 release = ctypes.pythonapi.PyGILState_Release
301 def __del__(self):
302 state = self.ensure()
303 self.release(state)
304
305 def waitingThread():
306 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000307 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000308 time.sleep(100)
309
Georg Brandl2067bfd2008-05-25 13:05:15 +0000310 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000311 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000312 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200313 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000314 self.assertEqual(rc, 42)
315
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000316 def test_finalize_with_trace(self):
317 # Issue1733757
318 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200319 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000320 import sys, threading
321
322 # A deadlock-killer, to prevent the
323 # testsuite to hang forever
324 def killer():
325 import os, time
326 time.sleep(2)
327 print('program blocked; aborting')
328 os._exit(2)
329 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000330 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000331 t.start()
332
333 # This is the trace function
334 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000335 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000336 return func
337
338 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200339 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000340
Antoine Pitrou011bd622009-10-20 21:52:47 +0000341 def test_join_nondaemon_on_shutdown(self):
342 # Issue 1722344
343 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200344 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000345 import threading
346 from time import sleep
347
348 def child():
349 sleep(1)
350 # As a non-daemon thread we SHOULD wake up and nothing
351 # should be torn down yet
352 print("Woke up, sleep function is:", sleep)
353
354 threading.Thread(target=child).start()
355 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200356 """)
357 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000358 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200359 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000360
Christian Heimes1af737c2008-01-23 08:24:23 +0000361 def test_enumerate_after_join(self):
362 # Try hard to trigger #1703448: a thread is still returned in
363 # threading.enumerate() after it has been join()ed.
364 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000365 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000366 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000367 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000368 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000369 t = threading.Thread(target=lambda: None)
370 t.start()
371 t.join()
372 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000373 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000374 "#1703448 triggered after %d trials: %s" % (i, l))
375 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000376 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000377
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000378 def test_no_refcycle_through_target(self):
379 class RunSelfFunction(object):
380 def __init__(self, should_raise):
381 # The links in this refcycle from Thread back to self
382 # should be cleaned up when the thread completes.
383 self.should_raise = should_raise
384 self.thread = threading.Thread(target=self._run,
385 args=(self,),
386 kwargs={'yet_another':self})
387 self.thread.start()
388
389 def _run(self, other_ref, yet_another):
390 if self.should_raise:
391 raise SystemExit
392
393 cyclic_object = RunSelfFunction(should_raise=False)
394 weak_cyclic_object = weakref.ref(cyclic_object)
395 cyclic_object.thread.join()
396 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000397 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000398 msg=('%d references still around' %
399 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000400
401 raising_cyclic_object = RunSelfFunction(should_raise=True)
402 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
403 raising_cyclic_object.thread.join()
404 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000405 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000406 msg=('%d references still around' %
407 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000408
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000409 def test_old_threading_api(self):
410 # Just a quick sanity check to make sure the old method names are
411 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000412 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000413 t.isDaemon()
414 t.setDaemon(True)
415 t.getName()
416 t.setName("name")
417 t.isAlive()
418 e = threading.Event()
419 e.isSet()
420 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000421
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000422 def test_repr_daemon(self):
423 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200424 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000425 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200426 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000427
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000428 def test_deamon_param(self):
429 t = threading.Thread()
430 self.assertFalse(t.daemon)
431 t = threading.Thread(daemon=False)
432 self.assertFalse(t.daemon)
433 t = threading.Thread(daemon=True)
434 self.assertTrue(t.daemon)
435
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200436 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
437 def test_dummy_thread_after_fork(self):
438 # Issue #14308: a dummy thread in the active list doesn't mess up
439 # the after-fork mechanism.
440 code = """if 1:
441 import _thread, threading, os, time
442
443 def background_thread(evt):
444 # Creates and registers the _DummyThread instance
445 threading.current_thread()
446 evt.set()
447 time.sleep(10)
448
449 evt = threading.Event()
450 _thread.start_new_thread(background_thread, (evt,))
451 evt.wait()
452 assert threading.active_count() == 2, threading.active_count()
453 if os.fork() == 0:
454 assert threading.active_count() == 1, threading.active_count()
455 os._exit(0)
456 else:
457 os.wait()
458 """
459 _, out, err = assert_python_ok("-c", code)
460 self.assertEqual(out, b'')
461 self.assertEqual(err, b'')
462
Charles-François Natali9939cc82013-08-30 23:32:53 +0200463 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
464 def test_is_alive_after_fork(self):
465 # Try hard to trigger #18418: is_alive() could sometimes be True on
466 # threads that vanished after a fork.
467 old_interval = sys.getswitchinterval()
468 self.addCleanup(sys.setswitchinterval, old_interval)
469
470 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100471 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200472
473 for i in range(20):
474 t = threading.Thread(target=lambda: None)
475 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200476 pid = os.fork()
477 if pid == 0:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700478 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200479 else:
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700480 t.join()
481
Charles-François Natali9939cc82013-08-30 23:32:53 +0200482 pid, status = os.waitpid(pid, 0)
Victor Stinnerf8d05b32017-05-17 11:58:50 -0700483 self.assertTrue(os.WIFEXITED(status))
484 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200485
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300486 def test_main_thread(self):
487 main = threading.main_thread()
488 self.assertEqual(main.name, 'MainThread')
489 self.assertEqual(main.ident, threading.current_thread().ident)
490 self.assertEqual(main.ident, threading.get_ident())
491
492 def f():
493 self.assertNotEqual(threading.main_thread().ident,
494 threading.current_thread().ident)
495 th = threading.Thread(target=f)
496 th.start()
497 th.join()
498
499 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
500 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
501 def test_main_thread_after_fork(self):
502 code = """if 1:
503 import os, threading
504
505 pid = os.fork()
506 if pid == 0:
507 main = threading.main_thread()
508 print(main.name)
509 print(main.ident == threading.current_thread().ident)
510 print(main.ident == threading.get_ident())
511 else:
512 os.waitpid(pid, 0)
513 """
514 _, out, err = assert_python_ok("-c", code)
515 data = out.decode().replace('\r', '')
516 self.assertEqual(err, b"")
517 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
518
519 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
520 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
521 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
522 def test_main_thread_after_fork_from_nonmain_thread(self):
523 code = """if 1:
524 import os, threading, sys
525
526 def f():
527 pid = os.fork()
528 if pid == 0:
529 main = threading.main_thread()
530 print(main.name)
531 print(main.ident == threading.current_thread().ident)
532 print(main.ident == threading.get_ident())
533 # stdout is fully buffered because not a tty,
534 # we have to flush before exit.
535 sys.stdout.flush()
536 else:
537 os.waitpid(pid, 0)
538
539 th = threading.Thread(target=f)
540 th.start()
541 th.join()
542 """
543 _, out, err = assert_python_ok("-c", code)
544 data = out.decode().replace('\r', '')
545 self.assertEqual(err, b"")
546 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
547
Antoine Pitrou7b476992013-09-07 23:38:37 +0200548 def test_tstate_lock(self):
549 # Test an implementation detail of Thread objects.
550 started = _thread.allocate_lock()
551 finish = _thread.allocate_lock()
552 started.acquire()
553 finish.acquire()
554 def f():
555 started.release()
556 finish.acquire()
557 time.sleep(0.01)
558 # The tstate lock is None until the thread is started
559 t = threading.Thread(target=f)
560 self.assertIs(t._tstate_lock, None)
561 t.start()
562 started.acquire()
563 self.assertTrue(t.is_alive())
564 # The tstate lock can't be acquired when the thread is running
565 # (or suspended).
566 tstate_lock = t._tstate_lock
567 self.assertFalse(tstate_lock.acquire(timeout=0), False)
568 finish.release()
569 # When the thread ends, the state_lock can be successfully
570 # acquired.
571 self.assertTrue(tstate_lock.acquire(timeout=5), False)
572 # But is_alive() is still True: we hold _tstate_lock now, which
573 # prevents is_alive() from knowing the thread's end-of-life C code
574 # is done.
575 self.assertTrue(t.is_alive())
576 # Let is_alive() find out the C code is done.
577 tstate_lock.release()
578 self.assertFalse(t.is_alive())
579 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200580 self.assertIsNone(t._tstate_lock)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200581
Tim Peters72460fa2013-09-09 18:48:24 -0500582 def test_repr_stopped(self):
583 # Verify that "stopped" shows up in repr(Thread) appropriately.
584 started = _thread.allocate_lock()
585 finish = _thread.allocate_lock()
586 started.acquire()
587 finish.acquire()
588 def f():
589 started.release()
590 finish.acquire()
591 t = threading.Thread(target=f)
592 t.start()
593 started.acquire()
594 self.assertIn("started", repr(t))
595 finish.release()
596 # "stopped" should appear in the repr in a reasonable amount of time.
597 # Implementation detail: as of this writing, that's trivially true
598 # if .join() is called, and almost trivially true if .is_alive() is
599 # called. The detail we're testing here is that "stopped" shows up
600 # "all on its own".
601 LOOKING_FOR = "stopped"
602 for i in range(500):
603 if LOOKING_FOR in repr(t):
604 break
605 time.sleep(0.01)
606 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Christian Heimes1af737c2008-01-23 08:24:23 +0000607
Tim Peters7634e1c2013-10-08 20:55:51 -0500608 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500609 # BoundedSemaphore should raise ValueError if released too often.
610 for limit in range(1, 10):
611 bs = threading.BoundedSemaphore(limit)
612 threads = [threading.Thread(target=bs.acquire)
613 for _ in range(limit)]
614 for t in threads:
615 t.start()
616 for t in threads:
617 t.join()
618 threads = [threading.Thread(target=bs.release)
619 for _ in range(limit)]
620 for t in threads:
621 t.start()
622 for t in threads:
623 t.join()
624 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500625
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200626 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100627 def test_frame_tstate_tracing(self):
628 # Issue #14432: Crash when a generator is created in a C thread that is
629 # destroyed while the generator is still used. The issue was that a
630 # generator contains a frame, and the frame kept a reference to the
631 # Python state of the destroyed C thread. The crash occurs when a trace
632 # function is setup.
633
634 def noop_trace(frame, event, arg):
635 # no operation
636 return noop_trace
637
638 def generator():
639 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300640 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100641
642 def callback():
643 if callback.gen is None:
644 callback.gen = generator()
645 return next(callback.gen)
646 callback.gen = None
647
648 old_trace = sys.gettrace()
649 sys.settrace(noop_trace)
650 try:
651 # Install a trace function
652 threading.settrace(noop_trace)
653
654 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200655 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100656 _testcapi.call_in_temporary_c_thread(callback)
657
658 # Call the generator in a different Python thread, check that the
659 # generator didn't keep a reference to the destroyed thread state
660 for test in range(3):
661 # The trace function is still called here
662 callback()
663 finally:
664 sys.settrace(old_trace)
665
Victor Stinner45956b92013-11-12 16:37:55 +0100666
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000667class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000668
669 def _run_and_join(self, script):
670 script = """if 1:
671 import sys, os, time, threading
672
673 # a thread, which waits for the main program to terminate
674 def joiningfunc(mainthread):
675 mainthread.join()
676 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000677 # stdout is fully buffered because not a tty, we have to flush
678 # before exit.
679 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000680 \n""" + script
681
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200682 rc, out, err = assert_python_ok("-c", script)
683 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000684 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000685
686 def test_1_join_on_shutdown(self):
687 # The usual case: on exit, wait for a non-daemon thread
688 script = """if 1:
689 import os
690 t = threading.Thread(target=joiningfunc,
691 args=(threading.current_thread(),))
692 t.start()
693 time.sleep(0.1)
694 print('end of main')
695 """
696 self._run_and_join(script)
697
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000698 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200699 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000700 def test_2_join_in_forked_process(self):
701 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000702 script = """if 1:
703 childpid = os.fork()
704 if childpid != 0:
705 os.waitpid(childpid, 0)
706 sys.exit(0)
707
708 t = threading.Thread(target=joiningfunc,
709 args=(threading.current_thread(),))
710 t.start()
711 print('end of main')
712 """
713 self._run_and_join(script)
714
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000715 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200716 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000717 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000718 # Like the test above, but fork() was called from a worker thread
719 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000720
Jesse Nollera8513972008-07-17 16:49:17 +0000721 script = """if 1:
722 main_thread = threading.current_thread()
723 def worker():
724 childpid = os.fork()
725 if childpid != 0:
726 os.waitpid(childpid, 0)
727 sys.exit(0)
728
729 t = threading.Thread(target=joiningfunc,
730 args=(main_thread,))
731 print('end of main')
732 t.start()
733 t.join() # Should not block: main_thread is already stopped
734
735 w = threading.Thread(target=worker)
736 w.start()
737 """
738 self._run_and_join(script)
739
Victor Stinner26d31862011-07-01 14:26:24 +0200740 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500741 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200742 # Check that a daemon thread cannot crash the interpreter on shutdown
743 # by manipulating internal structures that are being disposed of in
744 # the main thread.
745 script = """if True:
746 import os
747 import random
748 import sys
749 import time
750 import threading
751
752 thread_has_run = set()
753
754 def random_io():
755 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200756 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200757 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200758 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200759 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200760 null_f.write(stuff)
761 time.sleep(random.random() / 1995)
762 null_f.close()
763 in_f.close()
764 thread_has_run.add(threading.current_thread())
765
766 def main():
767 count = 0
768 for _ in range(40):
769 new_thread = threading.Thread(target=random_io)
770 new_thread.daemon = True
771 new_thread.start()
772 count += 1
773 while len(thread_has_run) < count:
774 time.sleep(0.001)
775 # Trigger process shutdown
776 sys.exit(0)
777
778 main()
779 """
780 rc, out, err = assert_python_ok('-c', script)
781 self.assertFalse(err)
782
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100783 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100784 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100785 def test_reinit_tls_after_fork(self):
786 # Issue #13817: fork() would deadlock in a multithreaded program with
787 # the ad-hoc TLS implementation.
788
789 def do_fork_and_wait():
790 # just fork a child process and wait it
791 pid = os.fork()
792 if pid > 0:
793 os.waitpid(pid, 0)
794 else:
795 os._exit(0)
796
797 # start a bunch of threads that will fork() child processes
798 threads = []
799 for i in range(16):
800 t = threading.Thread(target=do_fork_and_wait)
801 threads.append(t)
802 t.start()
803
804 for t in threads:
805 t.join()
806
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200807 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
808 def test_clear_threads_states_after_fork(self):
809 # Issue #17094: check that threads states are cleared after fork()
810
811 # start a bunch of threads
812 threads = []
813 for i in range(16):
814 t = threading.Thread(target=lambda : time.sleep(0.3))
815 threads.append(t)
816 t.start()
817
818 pid = os.fork()
819 if pid == 0:
820 # check that threads states have been cleared
821 if len(sys._current_frames()) == 1:
822 os._exit(0)
823 else:
824 os._exit(1)
825 else:
826 _, status = os.waitpid(pid, 0)
827 self.assertEqual(0, status)
828
829 for t in threads:
830 t.join()
831
Jesse Nollera8513972008-07-17 16:49:17 +0000832
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200833class SubinterpThreadingTests(BaseTestCase):
834
835 def test_threads_join(self):
836 # Non-daemon threads should be joined at subinterpreter shutdown
837 # (issue #18808)
838 r, w = os.pipe()
839 self.addCleanup(os.close, r)
840 self.addCleanup(os.close, w)
841 code = r"""if 1:
842 import os
843 import threading
844 import time
845
846 def f():
847 # Sleep a bit so that the thread is still running when
848 # Py_EndInterpreter is called.
849 time.sleep(0.05)
850 os.write(%d, b"x")
851 threading.Thread(target=f).start()
852 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100853 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200854 self.assertEqual(ret, 0)
855 # The thread was joined properly.
856 self.assertEqual(os.read(r, 1), b"x")
857
Antoine Pitrou7b476992013-09-07 23:38:37 +0200858 def test_threads_join_2(self):
859 # Same as above, but a delay gets introduced after the thread's
860 # Python code returned but before the thread state is deleted.
861 # To achieve this, we register a thread-local object which sleeps
862 # a bit when deallocated.
863 r, w = os.pipe()
864 self.addCleanup(os.close, r)
865 self.addCleanup(os.close, w)
866 code = r"""if 1:
867 import os
868 import threading
869 import time
870
871 class Sleeper:
872 def __del__(self):
873 time.sleep(0.05)
874
875 tls = threading.local()
876
877 def f():
878 # Sleep a bit so that the thread is still running when
879 # Py_EndInterpreter is called.
880 time.sleep(0.05)
881 tls.x = Sleeper()
882 os.write(%d, b"x")
883 threading.Thread(target=f).start()
884 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100885 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200886 self.assertEqual(ret, 0)
887 # The thread was joined properly.
888 self.assertEqual(os.read(r, 1), b"x")
889
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200890 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200891 def test_daemon_threads_fatal_error(self):
892 subinterp_code = r"""if 1:
893 import os
894 import threading
895 import time
896
897 def f():
898 # Make sure the daemon thread is still running when
899 # Py_EndInterpreter is called.
900 time.sleep(10)
901 threading.Thread(target=f, daemon=True).start()
902 """
903 script = r"""if 1:
904 import _testcapi
905
906 _testcapi.run_in_subinterp(%r)
907 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200908 with test.support.SuppressCrashReport():
909 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200910 self.assertIn("Fatal Python error: Py_EndInterpreter: "
911 "not the last thread", err.decode())
912
913
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000914class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000915 # A RuntimeError should be raised if Thread.start() is called
916 # multiple times.
917 def test_start_thread_again(self):
918 thread = threading.Thread()
919 thread.start()
920 self.assertRaises(RuntimeError, thread.start)
921
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000922 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000923 current_thread = threading.current_thread()
924 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000925
926 def test_joining_inactive_thread(self):
927 thread = threading.Thread()
928 self.assertRaises(RuntimeError, thread.join)
929
930 def test_daemonize_active_thread(self):
931 thread = threading.Thread()
932 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000933 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000934
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000935 def test_releasing_unacquired_lock(self):
936 lock = threading.Lock()
937 self.assertRaises(RuntimeError, lock.release)
938
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400939 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
940 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700941 def test_recursion_limit(self):
942 # Issue 9670
943 # test that excessive recursion within a non-main thread causes
944 # an exception rather than crashing the interpreter on platforms
945 # like Mac OS X or FreeBSD which have small default stack sizes
946 # for threads
947 script = """if True:
948 import threading
949
950 def recurse():
951 return recurse()
952
953 def outer():
954 try:
955 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400956 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700957 pass
958
959 w = threading.Thread(target=outer)
960 w.start()
961 w.join()
962 print('end of main thread')
963 """
964 expected_output = "end of main thread\n"
965 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200966 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700967 stdout, stderr = p.communicate()
968 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200969 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700970 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000971
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300972 def test_print_exception(self):
973 script = r"""if True:
974 import threading
975 import time
976
977 running = False
978 def run():
979 global running
980 running = True
981 while running:
982 time.sleep(0.01)
983 1/0
984 t = threading.Thread(target=run)
985 t.start()
986 while not running:
987 time.sleep(0.01)
988 running = False
989 t.join()
990 """
991 rc, out, err = assert_python_ok("-c", script)
992 self.assertEqual(out, b'')
993 err = err.decode()
994 self.assertIn("Exception in thread", err)
995 self.assertIn("Traceback (most recent call last):", err)
996 self.assertIn("ZeroDivisionError", err)
997 self.assertNotIn("Unhandled exception", err)
998
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300999 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001000 def test_print_exception_stderr_is_none_1(self):
1001 script = r"""if True:
1002 import sys
1003 import threading
1004 import time
1005
1006 running = False
1007 def run():
1008 global running
1009 running = True
1010 while running:
1011 time.sleep(0.01)
1012 1/0
1013 t = threading.Thread(target=run)
1014 t.start()
1015 while not running:
1016 time.sleep(0.01)
1017 sys.stderr = None
1018 running = False
1019 t.join()
1020 """
1021 rc, out, err = assert_python_ok("-c", script)
1022 self.assertEqual(out, b'')
1023 err = err.decode()
1024 self.assertIn("Exception in thread", err)
1025 self.assertIn("Traceback (most recent call last):", err)
1026 self.assertIn("ZeroDivisionError", err)
1027 self.assertNotIn("Unhandled exception", err)
1028
1029 def test_print_exception_stderr_is_none_2(self):
1030 script = r"""if True:
1031 import sys
1032 import threading
1033 import time
1034
1035 running = False
1036 def run():
1037 global running
1038 running = True
1039 while running:
1040 time.sleep(0.01)
1041 1/0
1042 sys.stderr = None
1043 t = threading.Thread(target=run)
1044 t.start()
1045 while not running:
1046 time.sleep(0.01)
1047 running = False
1048 t.join()
1049 """
1050 rc, out, err = assert_python_ok("-c", script)
1051 self.assertEqual(out, b'')
1052 self.assertNotIn("Unhandled exception", err.decode())
1053
Victor Stinnereec93312016-08-18 18:13:10 +02001054 def test_bare_raise_in_brand_new_thread(self):
1055 def bare_raise():
1056 raise
1057
1058 class Issue27558(threading.Thread):
1059 exc = None
1060
1061 def run(self):
1062 try:
1063 bare_raise()
1064 except Exception as exc:
1065 self.exc = exc
1066
1067 thread = Issue27558()
1068 thread.start()
1069 thread.join()
1070 self.assertIsNotNone(thread.exc)
1071 self.assertIsInstance(thread.exc, RuntimeError)
Victor Stinner3d284c02017-08-19 01:54:42 +02001072 # explicitly break the reference cycle to not leak a dangling thread
1073 thread.exc = None
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001074
R David Murray19aeb432013-03-30 17:19:38 -04001075class TimerTests(BaseTestCase):
1076
1077 def setUp(self):
1078 BaseTestCase.setUp(self)
1079 self.callback_args = []
1080 self.callback_event = threading.Event()
1081
1082 def test_init_immutable_default_args(self):
1083 # Issue 17435: constructor defaults were mutable objects, they could be
1084 # mutated via the object attributes and affect other Timer objects.
1085 timer1 = threading.Timer(0.01, self._callback_spy)
1086 timer1.start()
1087 self.callback_event.wait()
1088 timer1.args.append("blah")
1089 timer1.kwargs["foo"] = "bar"
1090 self.callback_event.clear()
1091 timer2 = threading.Timer(0.01, self._callback_spy)
1092 timer2.start()
1093 self.callback_event.wait()
1094 self.assertEqual(len(self.callback_args), 2)
1095 self.assertEqual(self.callback_args, [((), {}), ((), {})])
1096
1097 def _callback_spy(self, *args, **kwargs):
1098 self.callback_args.append((args[:], kwargs.copy()))
1099 self.callback_event.set()
1100
Antoine Pitrou557934f2009-11-06 22:41:14 +00001101class LockTests(lock_tests.LockTests):
1102 locktype = staticmethod(threading.Lock)
1103
Antoine Pitrou434736a2009-11-10 18:46:01 +00001104class PyRLockTests(lock_tests.RLockTests):
1105 locktype = staticmethod(threading._PyRLock)
1106
Charles-François Natali6b671b22012-01-28 11:36:04 +01001107@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001108class CRLockTests(lock_tests.RLockTests):
1109 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001110
1111class EventTests(lock_tests.EventTests):
1112 eventtype = staticmethod(threading.Event)
1113
1114class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001115 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001116 locktype = staticmethod(threading.Condition)
1117
1118class ConditionTests(lock_tests.ConditionTests):
1119 condtype = staticmethod(threading.Condition)
1120
1121class SemaphoreTests(lock_tests.SemaphoreTests):
1122 semtype = staticmethod(threading.Semaphore)
1123
1124class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1125 semtype = staticmethod(threading.BoundedSemaphore)
1126
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001127class BarrierTests(lock_tests.BarrierTests):
1128 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001129
Martin Panter19e69c52015-11-14 12:46:42 +00001130class MiscTestCase(unittest.TestCase):
1131 def test__all__(self):
1132 extra = {"ThreadError"}
1133 blacklist = {'currentThread', 'activeCount'}
1134 support.check__all__(self, threading, ('threading', '_thread'),
1135 extra=extra, blacklist=blacklist)
1136
Tim Peters84d54892005-01-08 06:03:17 +00001137if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001138 unittest.main()