blob: b63050982ab694e4ad8f7dbf53fd21c907dc6c0c [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
Georg Brandl0c77a822008-06-10 16:37:50 +000011import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +000012import sys
Antoine Pitrouc4d78642011-05-05 20:17:32 +020013_thread = import_module('_thread')
14threading = import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000015import time
Tim Peters84d54892005-01-08 06:03:17 +000016import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000017import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000018import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000019import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000020
Antoine Pitrou557934f2009-11-06 22:41:14 +000021from test import lock_tests
22
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)
Tim Peters711906e2005-01-08 07:30:42 +0000173 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000174
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000175 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
176 # exposed at the Python level. This test relies on ctypes to get at it.
177 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200178 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000179
180 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
181
182 class AsyncExc(Exception):
183 pass
184
185 exception = ctypes.py_object(AsyncExc)
186
Antoine Pitroube4d8092009-10-18 18:27:17 +0000187 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200188 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000189
190 try:
191 result = set_async_exc(ctypes.c_long(tid), exception)
192 # The exception is async, so we might have to keep the VM busy until
193 # it notices.
194 while True:
195 pass
196 except AsyncExc:
197 pass
198 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000199 # This code is unreachable but it reflects the intent. If we wanted
200 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000201 self.fail("AsyncExc not raised")
202 try:
203 self.assertEqual(result, 1) # one thread state modified
204 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000205 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000206 pass
207
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000208 # `worker_started` is set by the thread when it's inside a try/except
209 # block waiting to catch the asynchronously set AsyncExc exception.
210 # `worker_saw_exception` is set by the thread upon catching that
211 # exception.
212 worker_started = threading.Event()
213 worker_saw_exception = threading.Event()
214
215 class Worker(threading.Thread):
216 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200217 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 self.finished = False
219
220 try:
221 while True:
222 worker_started.set()
223 time.sleep(0.1)
224 except AsyncExc:
225 self.finished = True
226 worker_saw_exception.set()
227
228 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000229 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000230 t.start()
231 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000232 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233
234 # Try a thread id that doesn't make sense.
235 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000236 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000237 result = set_async_exc(ctypes.c_long(-1), exception)
238 self.assertEqual(result, 0) # no thread states modified
239
240 # Now raise an exception in the worker thread.
241 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000242 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000243 ret = worker_started.wait()
244 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000246 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200247 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000248 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000250 result = set_async_exc(ctypes.c_long(t.id), exception)
251 self.assertEqual(result, 1) # one thread state modified
252 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000253 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000254 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000255 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000256 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000257 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000258 if t.finished:
259 t.join()
260 # else the thread is still running, and we have no way to kill it
261
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000262 def test_limbo_cleanup(self):
263 # Issue 7481: Failure to start thread should cleanup the limbo map.
264 def fail_new_thread(*args):
265 raise threading.ThreadError()
266 _start_new_thread = threading._start_new_thread
267 threading._start_new_thread = fail_new_thread
268 try:
269 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000270 self.assertRaises(threading.ThreadError, t.start)
271 self.assertFalse(
272 t in threading._limbo,
273 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000274 finally:
275 threading._start_new_thread = _start_new_thread
276
Christian Heimes7d2ff882007-11-30 14:35:04 +0000277 def test_finalize_runnning_thread(self):
278 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
279 # very late on python exit: on deallocation of a running thread for
280 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200281 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000282
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200283 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000284 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000285
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000286 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000287 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000288 ready.acquire()
289
Christian Heimes7d2ff882007-11-30 14:35:04 +0000290 # Module globals are cleared before __del__ is run
291 # So we save the functions in class dict
292 class C:
293 ensure = ctypes.pythonapi.PyGILState_Ensure
294 release = ctypes.pythonapi.PyGILState_Release
295 def __del__(self):
296 state = self.ensure()
297 self.release(state)
298
299 def waitingThread():
300 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000301 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000302 time.sleep(100)
303
Georg Brandl2067bfd2008-05-25 13:05:15 +0000304 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000305 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000306 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200307 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000308 self.assertEqual(rc, 42)
309
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000310 def test_finalize_with_trace(self):
311 # Issue1733757
312 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200313 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000314 import sys, threading
315
316 # A deadlock-killer, to prevent the
317 # testsuite to hang forever
318 def killer():
319 import os, time
320 time.sleep(2)
321 print('program blocked; aborting')
322 os._exit(2)
323 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000324 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000325 t.start()
326
327 # This is the trace function
328 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000329 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000330 return func
331
332 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200333 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000334
Antoine Pitrou011bd622009-10-20 21:52:47 +0000335 def test_join_nondaemon_on_shutdown(self):
336 # Issue 1722344
337 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200338 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000339 import threading
340 from time import sleep
341
342 def child():
343 sleep(1)
344 # As a non-daemon thread we SHOULD wake up and nothing
345 # should be torn down yet
346 print("Woke up, sleep function is:", sleep)
347
348 threading.Thread(target=child).start()
349 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200350 """)
351 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000352 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200353 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000354
Christian Heimes1af737c2008-01-23 08:24:23 +0000355 def test_enumerate_after_join(self):
356 # Try hard to trigger #1703448: a thread is still returned in
357 # threading.enumerate() after it has been join()ed.
358 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000359 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000360 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000361 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000362 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000363 t = threading.Thread(target=lambda: None)
364 t.start()
365 t.join()
366 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000367 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000368 "#1703448 triggered after %d trials: %s" % (i, l))
369 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000370 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000371
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000372 def test_no_refcycle_through_target(self):
373 class RunSelfFunction(object):
374 def __init__(self, should_raise):
375 # The links in this refcycle from Thread back to self
376 # should be cleaned up when the thread completes.
377 self.should_raise = should_raise
378 self.thread = threading.Thread(target=self._run,
379 args=(self,),
380 kwargs={'yet_another':self})
381 self.thread.start()
382
383 def _run(self, other_ref, yet_another):
384 if self.should_raise:
385 raise SystemExit
386
387 cyclic_object = RunSelfFunction(should_raise=False)
388 weak_cyclic_object = weakref.ref(cyclic_object)
389 cyclic_object.thread.join()
390 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000391 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000392 msg=('%d references still around' %
393 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000394
395 raising_cyclic_object = RunSelfFunction(should_raise=True)
396 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
397 raising_cyclic_object.thread.join()
398 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000399 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000400 msg=('%d references still around' %
401 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000402
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000403 def test_old_threading_api(self):
404 # Just a quick sanity check to make sure the old method names are
405 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000406 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000407 t.isDaemon()
408 t.setDaemon(True)
409 t.getName()
410 t.setName("name")
411 t.isAlive()
412 e = threading.Event()
413 e.isSet()
414 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000415
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000416 def test_repr_daemon(self):
417 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200418 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000419 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200420 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000421
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000422 def test_deamon_param(self):
423 t = threading.Thread()
424 self.assertFalse(t.daemon)
425 t = threading.Thread(daemon=False)
426 self.assertFalse(t.daemon)
427 t = threading.Thread(daemon=True)
428 self.assertTrue(t.daemon)
429
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200430 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
431 def test_dummy_thread_after_fork(self):
432 # Issue #14308: a dummy thread in the active list doesn't mess up
433 # the after-fork mechanism.
434 code = """if 1:
435 import _thread, threading, os, time
436
437 def background_thread(evt):
438 # Creates and registers the _DummyThread instance
439 threading.current_thread()
440 evt.set()
441 time.sleep(10)
442
443 evt = threading.Event()
444 _thread.start_new_thread(background_thread, (evt,))
445 evt.wait()
446 assert threading.active_count() == 2, threading.active_count()
447 if os.fork() == 0:
448 assert threading.active_count() == 1, threading.active_count()
449 os._exit(0)
450 else:
451 os.wait()
452 """
453 _, out, err = assert_python_ok("-c", code)
454 self.assertEqual(out, b'')
455 self.assertEqual(err, b'')
456
Charles-François Natali9939cc82013-08-30 23:32:53 +0200457 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
458 def test_is_alive_after_fork(self):
459 # Try hard to trigger #18418: is_alive() could sometimes be True on
460 # threads that vanished after a fork.
461 old_interval = sys.getswitchinterval()
462 self.addCleanup(sys.setswitchinterval, old_interval)
463
464 # Make the bug more likely to manifest.
465 sys.setswitchinterval(1e-6)
466
467 for i in range(20):
468 t = threading.Thread(target=lambda: None)
469 t.start()
470 self.addCleanup(t.join)
471 pid = os.fork()
472 if pid == 0:
473 os._exit(1 if t.is_alive() else 0)
474 else:
475 pid, status = os.waitpid(pid, 0)
476 self.assertEqual(0, status)
477
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300478 def test_main_thread(self):
479 main = threading.main_thread()
480 self.assertEqual(main.name, 'MainThread')
481 self.assertEqual(main.ident, threading.current_thread().ident)
482 self.assertEqual(main.ident, threading.get_ident())
483
484 def f():
485 self.assertNotEqual(threading.main_thread().ident,
486 threading.current_thread().ident)
487 th = threading.Thread(target=f)
488 th.start()
489 th.join()
490
491 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
492 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
493 def test_main_thread_after_fork(self):
494 code = """if 1:
495 import os, threading
496
497 pid = os.fork()
498 if pid == 0:
499 main = threading.main_thread()
500 print(main.name)
501 print(main.ident == threading.current_thread().ident)
502 print(main.ident == threading.get_ident())
503 else:
504 os.waitpid(pid, 0)
505 """
506 _, out, err = assert_python_ok("-c", code)
507 data = out.decode().replace('\r', '')
508 self.assertEqual(err, b"")
509 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
510
511 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
512 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
513 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
514 def test_main_thread_after_fork_from_nonmain_thread(self):
515 code = """if 1:
516 import os, threading, sys
517
518 def f():
519 pid = os.fork()
520 if pid == 0:
521 main = threading.main_thread()
522 print(main.name)
523 print(main.ident == threading.current_thread().ident)
524 print(main.ident == threading.get_ident())
525 # stdout is fully buffered because not a tty,
526 # we have to flush before exit.
527 sys.stdout.flush()
528 else:
529 os.waitpid(pid, 0)
530
531 th = threading.Thread(target=f)
532 th.start()
533 th.join()
534 """
535 _, out, err = assert_python_ok("-c", code)
536 data = out.decode().replace('\r', '')
537 self.assertEqual(err, b"")
538 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
539
Antoine Pitrou7b476992013-09-07 23:38:37 +0200540 def test_tstate_lock(self):
541 # Test an implementation detail of Thread objects.
542 started = _thread.allocate_lock()
543 finish = _thread.allocate_lock()
544 started.acquire()
545 finish.acquire()
546 def f():
547 started.release()
548 finish.acquire()
549 time.sleep(0.01)
550 # The tstate lock is None until the thread is started
551 t = threading.Thread(target=f)
552 self.assertIs(t._tstate_lock, None)
553 t.start()
554 started.acquire()
555 self.assertTrue(t.is_alive())
556 # The tstate lock can't be acquired when the thread is running
557 # (or suspended).
558 tstate_lock = t._tstate_lock
559 self.assertFalse(tstate_lock.acquire(timeout=0), False)
560 finish.release()
561 # When the thread ends, the state_lock can be successfully
562 # acquired.
563 self.assertTrue(tstate_lock.acquire(timeout=5), False)
564 # But is_alive() is still True: we hold _tstate_lock now, which
565 # prevents is_alive() from knowing the thread's end-of-life C code
566 # is done.
567 self.assertTrue(t.is_alive())
568 # Let is_alive() find out the C code is done.
569 tstate_lock.release()
570 self.assertFalse(t.is_alive())
571 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200572 self.assertIsNone(t._tstate_lock)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200573
Tim Peters72460fa2013-09-09 18:48:24 -0500574 def test_repr_stopped(self):
575 # Verify that "stopped" shows up in repr(Thread) appropriately.
576 started = _thread.allocate_lock()
577 finish = _thread.allocate_lock()
578 started.acquire()
579 finish.acquire()
580 def f():
581 started.release()
582 finish.acquire()
583 t = threading.Thread(target=f)
584 t.start()
585 started.acquire()
586 self.assertIn("started", repr(t))
587 finish.release()
588 # "stopped" should appear in the repr in a reasonable amount of time.
589 # Implementation detail: as of this writing, that's trivially true
590 # if .join() is called, and almost trivially true if .is_alive() is
591 # called. The detail we're testing here is that "stopped" shows up
592 # "all on its own".
593 LOOKING_FOR = "stopped"
594 for i in range(500):
595 if LOOKING_FOR in repr(t):
596 break
597 time.sleep(0.01)
598 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Christian Heimes1af737c2008-01-23 08:24:23 +0000599
Tim Peters7634e1c2013-10-08 20:55:51 -0500600 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500601 # BoundedSemaphore should raise ValueError if released too often.
602 for limit in range(1, 10):
603 bs = threading.BoundedSemaphore(limit)
604 threads = [threading.Thread(target=bs.acquire)
605 for _ in range(limit)]
606 for t in threads:
607 t.start()
608 for t in threads:
609 t.join()
610 threads = [threading.Thread(target=bs.release)
611 for _ in range(limit)]
612 for t in threads:
613 t.start()
614 for t in threads:
615 t.join()
616 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500617
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200618 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100619 def test_frame_tstate_tracing(self):
620 # Issue #14432: Crash when a generator is created in a C thread that is
621 # destroyed while the generator is still used. The issue was that a
622 # generator contains a frame, and the frame kept a reference to the
623 # Python state of the destroyed C thread. The crash occurs when a trace
624 # function is setup.
625
626 def noop_trace(frame, event, arg):
627 # no operation
628 return noop_trace
629
630 def generator():
631 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300632 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100633
634 def callback():
635 if callback.gen is None:
636 callback.gen = generator()
637 return next(callback.gen)
638 callback.gen = None
639
640 old_trace = sys.gettrace()
641 sys.settrace(noop_trace)
642 try:
643 # Install a trace function
644 threading.settrace(noop_trace)
645
646 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200647 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100648 _testcapi.call_in_temporary_c_thread(callback)
649
650 # Call the generator in a different Python thread, check that the
651 # generator didn't keep a reference to the destroyed thread state
652 for test in range(3):
653 # The trace function is still called here
654 callback()
655 finally:
656 sys.settrace(old_trace)
657
Victor Stinner45956b92013-11-12 16:37:55 +0100658
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000659class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000660
661 def _run_and_join(self, script):
662 script = """if 1:
663 import sys, os, time, threading
664
665 # a thread, which waits for the main program to terminate
666 def joiningfunc(mainthread):
667 mainthread.join()
668 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000669 # stdout is fully buffered because not a tty, we have to flush
670 # before exit.
671 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000672 \n""" + script
673
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200674 rc, out, err = assert_python_ok("-c", script)
675 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000676 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000677
678 def test_1_join_on_shutdown(self):
679 # The usual case: on exit, wait for a non-daemon thread
680 script = """if 1:
681 import os
682 t = threading.Thread(target=joiningfunc,
683 args=(threading.current_thread(),))
684 t.start()
685 time.sleep(0.1)
686 print('end of main')
687 """
688 self._run_and_join(script)
689
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000690 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200691 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000692 def test_2_join_in_forked_process(self):
693 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000694 script = """if 1:
695 childpid = os.fork()
696 if childpid != 0:
697 os.waitpid(childpid, 0)
698 sys.exit(0)
699
700 t = threading.Thread(target=joiningfunc,
701 args=(threading.current_thread(),))
702 t.start()
703 print('end of main')
704 """
705 self._run_and_join(script)
706
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000707 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200708 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000709 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000710 # Like the test above, but fork() was called from a worker thread
711 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000712
Jesse Nollera8513972008-07-17 16:49:17 +0000713 script = """if 1:
714 main_thread = threading.current_thread()
715 def worker():
716 childpid = os.fork()
717 if childpid != 0:
718 os.waitpid(childpid, 0)
719 sys.exit(0)
720
721 t = threading.Thread(target=joiningfunc,
722 args=(main_thread,))
723 print('end of main')
724 t.start()
725 t.join() # Should not block: main_thread is already stopped
726
727 w = threading.Thread(target=worker)
728 w.start()
729 """
730 self._run_and_join(script)
731
Victor Stinner26d31862011-07-01 14:26:24 +0200732 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500733 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200734 # Check that a daemon thread cannot crash the interpreter on shutdown
735 # by manipulating internal structures that are being disposed of in
736 # the main thread.
737 script = """if True:
738 import os
739 import random
740 import sys
741 import time
742 import threading
743
744 thread_has_run = set()
745
746 def random_io():
747 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200748 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200749 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200750 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200751 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200752 null_f.write(stuff)
753 time.sleep(random.random() / 1995)
754 null_f.close()
755 in_f.close()
756 thread_has_run.add(threading.current_thread())
757
758 def main():
759 count = 0
760 for _ in range(40):
761 new_thread = threading.Thread(target=random_io)
762 new_thread.daemon = True
763 new_thread.start()
764 count += 1
765 while len(thread_has_run) < count:
766 time.sleep(0.001)
767 # Trigger process shutdown
768 sys.exit(0)
769
770 main()
771 """
772 rc, out, err = assert_python_ok('-c', script)
773 self.assertFalse(err)
774
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100775 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100776 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100777 def test_reinit_tls_after_fork(self):
778 # Issue #13817: fork() would deadlock in a multithreaded program with
779 # the ad-hoc TLS implementation.
780
781 def do_fork_and_wait():
782 # just fork a child process and wait it
783 pid = os.fork()
784 if pid > 0:
785 os.waitpid(pid, 0)
786 else:
787 os._exit(0)
788
789 # start a bunch of threads that will fork() child processes
790 threads = []
791 for i in range(16):
792 t = threading.Thread(target=do_fork_and_wait)
793 threads.append(t)
794 t.start()
795
796 for t in threads:
797 t.join()
798
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200799 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
800 def test_clear_threads_states_after_fork(self):
801 # Issue #17094: check that threads states are cleared after fork()
802
803 # start a bunch of threads
804 threads = []
805 for i in range(16):
806 t = threading.Thread(target=lambda : time.sleep(0.3))
807 threads.append(t)
808 t.start()
809
810 pid = os.fork()
811 if pid == 0:
812 # check that threads states have been cleared
813 if len(sys._current_frames()) == 1:
814 os._exit(0)
815 else:
816 os._exit(1)
817 else:
818 _, status = os.waitpid(pid, 0)
819 self.assertEqual(0, status)
820
821 for t in threads:
822 t.join()
823
Jesse Nollera8513972008-07-17 16:49:17 +0000824
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200825class SubinterpThreadingTests(BaseTestCase):
826
827 def test_threads_join(self):
828 # Non-daemon threads should be joined at subinterpreter shutdown
829 # (issue #18808)
830 r, w = os.pipe()
831 self.addCleanup(os.close, r)
832 self.addCleanup(os.close, w)
833 code = r"""if 1:
834 import os
835 import threading
836 import time
837
838 def f():
839 # Sleep a bit so that the thread is still running when
840 # Py_EndInterpreter is called.
841 time.sleep(0.05)
842 os.write(%d, b"x")
843 threading.Thread(target=f).start()
844 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100845 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200846 self.assertEqual(ret, 0)
847 # The thread was joined properly.
848 self.assertEqual(os.read(r, 1), b"x")
849
Antoine Pitrou7b476992013-09-07 23:38:37 +0200850 def test_threads_join_2(self):
851 # Same as above, but a delay gets introduced after the thread's
852 # Python code returned but before the thread state is deleted.
853 # To achieve this, we register a thread-local object which sleeps
854 # a bit when deallocated.
855 r, w = os.pipe()
856 self.addCleanup(os.close, r)
857 self.addCleanup(os.close, w)
858 code = r"""if 1:
859 import os
860 import threading
861 import time
862
863 class Sleeper:
864 def __del__(self):
865 time.sleep(0.05)
866
867 tls = threading.local()
868
869 def f():
870 # Sleep a bit so that the thread is still running when
871 # Py_EndInterpreter is called.
872 time.sleep(0.05)
873 tls.x = Sleeper()
874 os.write(%d, b"x")
875 threading.Thread(target=f).start()
876 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100877 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200878 self.assertEqual(ret, 0)
879 # The thread was joined properly.
880 self.assertEqual(os.read(r, 1), b"x")
881
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200882 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200883 def test_daemon_threads_fatal_error(self):
884 subinterp_code = r"""if 1:
885 import os
886 import threading
887 import time
888
889 def f():
890 # Make sure the daemon thread is still running when
891 # Py_EndInterpreter is called.
892 time.sleep(10)
893 threading.Thread(target=f, daemon=True).start()
894 """
895 script = r"""if 1:
896 import _testcapi
897
898 _testcapi.run_in_subinterp(%r)
899 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200900 with test.support.SuppressCrashReport():
901 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200902 self.assertIn("Fatal Python error: Py_EndInterpreter: "
903 "not the last thread", err.decode())
904
905
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000906class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000907 # A RuntimeError should be raised if Thread.start() is called
908 # multiple times.
909 def test_start_thread_again(self):
910 thread = threading.Thread()
911 thread.start()
912 self.assertRaises(RuntimeError, thread.start)
913
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000914 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000915 current_thread = threading.current_thread()
916 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000917
918 def test_joining_inactive_thread(self):
919 thread = threading.Thread()
920 self.assertRaises(RuntimeError, thread.join)
921
922 def test_daemonize_active_thread(self):
923 thread = threading.Thread()
924 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000925 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000926
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000927 def test_releasing_unacquired_lock(self):
928 lock = threading.Lock()
929 self.assertRaises(RuntimeError, lock.release)
930
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400931 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
932 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700933 def test_recursion_limit(self):
934 # Issue 9670
935 # test that excessive recursion within a non-main thread causes
936 # an exception rather than crashing the interpreter on platforms
937 # like Mac OS X or FreeBSD which have small default stack sizes
938 # for threads
939 script = """if True:
940 import threading
941
942 def recurse():
943 return recurse()
944
945 def outer():
946 try:
947 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400948 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700949 pass
950
951 w = threading.Thread(target=outer)
952 w.start()
953 w.join()
954 print('end of main thread')
955 """
956 expected_output = "end of main thread\n"
957 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200958 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700959 stdout, stderr = p.communicate()
960 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200961 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700962 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000963
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300964 def test_print_exception(self):
965 script = r"""if True:
966 import threading
967 import time
968
969 running = False
970 def run():
971 global running
972 running = True
973 while running:
974 time.sleep(0.01)
975 1/0
976 t = threading.Thread(target=run)
977 t.start()
978 while not running:
979 time.sleep(0.01)
980 running = False
981 t.join()
982 """
983 rc, out, err = assert_python_ok("-c", script)
984 self.assertEqual(out, b'')
985 err = err.decode()
986 self.assertIn("Exception in thread", err)
987 self.assertIn("Traceback (most recent call last):", err)
988 self.assertIn("ZeroDivisionError", err)
989 self.assertNotIn("Unhandled exception", err)
990
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300991 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300992 def test_print_exception_stderr_is_none_1(self):
993 script = r"""if True:
994 import sys
995 import threading
996 import time
997
998 running = False
999 def run():
1000 global running
1001 running = True
1002 while running:
1003 time.sleep(0.01)
1004 1/0
1005 t = threading.Thread(target=run)
1006 t.start()
1007 while not running:
1008 time.sleep(0.01)
1009 sys.stderr = None
1010 running = False
1011 t.join()
1012 """
1013 rc, out, err = assert_python_ok("-c", script)
1014 self.assertEqual(out, b'')
1015 err = err.decode()
1016 self.assertIn("Exception in thread", err)
1017 self.assertIn("Traceback (most recent call last):", err)
1018 self.assertIn("ZeroDivisionError", err)
1019 self.assertNotIn("Unhandled exception", err)
1020
1021 def test_print_exception_stderr_is_none_2(self):
1022 script = r"""if True:
1023 import sys
1024 import threading
1025 import time
1026
1027 running = False
1028 def run():
1029 global running
1030 running = True
1031 while running:
1032 time.sleep(0.01)
1033 1/0
1034 sys.stderr = None
1035 t = threading.Thread(target=run)
1036 t.start()
1037 while not running:
1038 time.sleep(0.01)
1039 running = False
1040 t.join()
1041 """
1042 rc, out, err = assert_python_ok("-c", script)
1043 self.assertEqual(out, b'')
1044 self.assertNotIn("Unhandled exception", err.decode())
1045
Victor Stinnereec93312016-08-18 18:13:10 +02001046 def test_bare_raise_in_brand_new_thread(self):
1047 def bare_raise():
1048 raise
1049
1050 class Issue27558(threading.Thread):
1051 exc = None
1052
1053 def run(self):
1054 try:
1055 bare_raise()
1056 except Exception as exc:
1057 self.exc = exc
1058
1059 thread = Issue27558()
1060 thread.start()
1061 thread.join()
1062 self.assertIsNotNone(thread.exc)
1063 self.assertIsInstance(thread.exc, RuntimeError)
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001064
R David Murray19aeb432013-03-30 17:19:38 -04001065class TimerTests(BaseTestCase):
1066
1067 def setUp(self):
1068 BaseTestCase.setUp(self)
1069 self.callback_args = []
1070 self.callback_event = threading.Event()
1071
1072 def test_init_immutable_default_args(self):
1073 # Issue 17435: constructor defaults were mutable objects, they could be
1074 # mutated via the object attributes and affect other Timer objects.
1075 timer1 = threading.Timer(0.01, self._callback_spy)
1076 timer1.start()
1077 self.callback_event.wait()
1078 timer1.args.append("blah")
1079 timer1.kwargs["foo"] = "bar"
1080 self.callback_event.clear()
1081 timer2 = threading.Timer(0.01, self._callback_spy)
1082 timer2.start()
1083 self.callback_event.wait()
1084 self.assertEqual(len(self.callback_args), 2)
1085 self.assertEqual(self.callback_args, [((), {}), ((), {})])
1086
1087 def _callback_spy(self, *args, **kwargs):
1088 self.callback_args.append((args[:], kwargs.copy()))
1089 self.callback_event.set()
1090
Antoine Pitrou557934f2009-11-06 22:41:14 +00001091class LockTests(lock_tests.LockTests):
1092 locktype = staticmethod(threading.Lock)
1093
Antoine Pitrou434736a2009-11-10 18:46:01 +00001094class PyRLockTests(lock_tests.RLockTests):
1095 locktype = staticmethod(threading._PyRLock)
1096
Charles-François Natali6b671b22012-01-28 11:36:04 +01001097@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001098class CRLockTests(lock_tests.RLockTests):
1099 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001100
1101class EventTests(lock_tests.EventTests):
1102 eventtype = staticmethod(threading.Event)
1103
1104class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001105 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001106 locktype = staticmethod(threading.Condition)
1107
1108class ConditionTests(lock_tests.ConditionTests):
1109 condtype = staticmethod(threading.Condition)
1110
1111class SemaphoreTests(lock_tests.SemaphoreTests):
1112 semtype = staticmethod(threading.Semaphore)
1113
1114class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1115 semtype = staticmethod(threading.BoundedSemaphore)
1116
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001117class BarrierTests(lock_tests.BarrierTests):
1118 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001119
Tim Peters84d54892005-01-08 06:03:17 +00001120if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001121 unittest.main()