blob: d6317c71bf16ee7374b10f79fc602617e661bebe [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 Storchakae437a102016-04-24 21:41:02 +03006from test.support import verbose, import_module, cpython_only
Berker Peksagce643912015-05-06 06:33:17 +03007from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02008
Skip Montanaro4533f602001-08-20 20:28:48 +00009import random
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010import sys
Antoine Pitrouc4d78642011-05-05 20:17:32 +020011_thread = import_module('_thread')
12threading = import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000013import time
Tim Peters84d54892005-01-08 06:03:17 +000014import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000015import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000016import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000017import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000018
Antoine Pitrou557934f2009-11-06 22:41:14 +000019from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000020from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000021
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030022
23# Between fork() and exec(), only async-safe functions are allowed (issues
24# #12316 and #11870), and fork() from a worker thread is known to trigger
25# problems with some operating systems (issue #3863): skip problematic tests
26# on platforms known to behave badly.
27platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
28 'hp-ux11')
29
30
Tim Peters84d54892005-01-08 06:03:17 +000031# A trivial mutable counter.
32class Counter(object):
33 def __init__(self):
34 self.value = 0
35 def inc(self):
36 self.value += 1
37 def dec(self):
38 self.value -= 1
39 def get(self):
40 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000041
42class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000043 def __init__(self, name, testcase, sema, mutex, nrunning):
44 threading.Thread.__init__(self, name=name)
45 self.testcase = testcase
46 self.sema = sema
47 self.mutex = mutex
48 self.nrunning = nrunning
49
Skip Montanaro4533f602001-08-20 20:28:48 +000050 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000051 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000052 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000053 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000054 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000055
Christian Heimes4fbc72b2008-03-22 00:47:35 +000056 with self.sema:
57 with self.mutex:
58 self.nrunning.inc()
59 if verbose:
60 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020061 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000062
Christian Heimes4fbc72b2008-03-22 00:47:35 +000063 time.sleep(delay)
64 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000065 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000066
Christian Heimes4fbc72b2008-03-22 00:47:35 +000067 with self.mutex:
68 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020069 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000070 if verbose:
71 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000072 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000073
Skip Montanaro4533f602001-08-20 20:28:48 +000074
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000075class BaseTestCase(unittest.TestCase):
76 def setUp(self):
77 self._threads = test.support.threading_setup()
78
79 def tearDown(self):
80 test.support.threading_cleanup(*self._threads)
81 test.support.reap_children()
82
83
84class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000085
Tim Peters84d54892005-01-08 06:03:17 +000086 # Create a bunch of threads, let each do some work, wait until all are
87 # done.
88 def test_various_ops(self):
89 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
90 # times about 1 second per clump).
91 NUMTASKS = 10
92
93 # no more than 3 of the 10 can run at once
94 sema = threading.BoundedSemaphore(value=3)
95 mutex = threading.RLock()
96 numrunning = Counter()
97
98 threads = []
99
100 for i in range(NUMTASKS):
101 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
102 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200103 self.assertIsNone(t.ident)
104 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000105 t.start()
106
107 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000109 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200110 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200111 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000112 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200113 self.assertIsNotNone(t.ident)
114 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000115 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000116 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000117 self.assertEqual(numrunning.get(), 0)
118
Benjamin Petersond23f8222009-04-05 19:13:16 +0000119 def test_ident_of_no_threading_threads(self):
120 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200121 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000122 def f():
123 ident.append(threading.currentThread().ident)
124 done.set()
125 done = threading.Event()
126 ident = []
127 _thread.start_new_thread(f, ())
128 done.wait()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200129 self.assertIsNotNone(ident[0])
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000130 # Kill the "immortal" _DummyThread
131 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000132
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000133 # run with a small(ish) thread stack size (256kB)
134 def test_various_ops_small_stack(self):
135 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000136 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 try:
138 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000139 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000140 raise unittest.SkipTest(
141 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 self.test_various_ops()
143 threading.stack_size(0)
144
145 # run with a large thread stack size (1MB)
146 def test_various_ops_large_stack(self):
147 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000148 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000149 try:
150 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000151 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000152 raise unittest.SkipTest(
153 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154 self.test_various_ops()
155 threading.stack_size(0)
156
Tim Peters711906e2005-01-08 07:30:42 +0000157 def test_foreign_thread(self):
158 # Check that a "foreign" thread can use the threading module.
159 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000160 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000161 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000162 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000163 mutex.release()
164
165 mutex = threading.Lock()
166 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000167 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000168 # Wait for the thread to finish.
169 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000170 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000171 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000172 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000173
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000174 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
175 # exposed at the Python level. This test relies on ctypes to get at it.
176 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200177 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178
179 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
180
181 class AsyncExc(Exception):
182 pass
183
184 exception = ctypes.py_object(AsyncExc)
185
Antoine Pitroube4d8092009-10-18 18:27:17 +0000186 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200187 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000188
189 try:
190 result = set_async_exc(ctypes.c_long(tid), exception)
191 # The exception is async, so we might have to keep the VM busy until
192 # it notices.
193 while True:
194 pass
195 except AsyncExc:
196 pass
197 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000198 # This code is unreachable but it reflects the intent. If we wanted
199 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000200 self.fail("AsyncExc not raised")
201 try:
202 self.assertEqual(result, 1) # one thread state modified
203 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000204 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000205 pass
206
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 # `worker_started` is set by the thread when it's inside a try/except
208 # block waiting to catch the asynchronously set AsyncExc exception.
209 # `worker_saw_exception` is set by the thread upon catching that
210 # exception.
211 worker_started = threading.Event()
212 worker_saw_exception = threading.Event()
213
214 class Worker(threading.Thread):
215 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200216 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000217 self.finished = False
218
219 try:
220 while True:
221 worker_started.set()
222 time.sleep(0.1)
223 except AsyncExc:
224 self.finished = True
225 worker_saw_exception.set()
226
227 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000228 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000229 t.start()
230 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000231 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232
233 # Try a thread id that doesn't make sense.
234 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000235 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236 result = set_async_exc(ctypes.c_long(-1), exception)
237 self.assertEqual(result, 0) # no thread states modified
238
239 # Now raise an exception in the worker thread.
240 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000241 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000242 ret = worker_started.wait()
243 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200246 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000248 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000249 result = set_async_exc(ctypes.c_long(t.id), exception)
250 self.assertEqual(result, 1) # one thread state modified
251 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000252 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000253 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000254 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000255 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000256 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000257 if t.finished:
258 t.join()
259 # else the thread is still running, and we have no way to kill it
260
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000261 def test_limbo_cleanup(self):
262 # Issue 7481: Failure to start thread should cleanup the limbo map.
263 def fail_new_thread(*args):
264 raise threading.ThreadError()
265 _start_new_thread = threading._start_new_thread
266 threading._start_new_thread = fail_new_thread
267 try:
268 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000269 self.assertRaises(threading.ThreadError, t.start)
270 self.assertFalse(
271 t in threading._limbo,
272 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000273 finally:
274 threading._start_new_thread = _start_new_thread
275
Christian Heimes7d2ff882007-11-30 14:35:04 +0000276 def test_finalize_runnning_thread(self):
277 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
278 # very late on python exit: on deallocation of a running thread for
279 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200280 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000281
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200282 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000283 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000284
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000285 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000286 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000287 ready.acquire()
288
Christian Heimes7d2ff882007-11-30 14:35:04 +0000289 # Module globals are cleared before __del__ is run
290 # So we save the functions in class dict
291 class C:
292 ensure = ctypes.pythonapi.PyGILState_Ensure
293 release = ctypes.pythonapi.PyGILState_Release
294 def __del__(self):
295 state = self.ensure()
296 self.release(state)
297
298 def waitingThread():
299 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000300 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000301 time.sleep(100)
302
Georg Brandl2067bfd2008-05-25 13:05:15 +0000303 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000304 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000305 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200306 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000307 self.assertEqual(rc, 42)
308
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000309 def test_finalize_with_trace(self):
310 # Issue1733757
311 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200312 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000313 import sys, threading
314
315 # A deadlock-killer, to prevent the
316 # testsuite to hang forever
317 def killer():
318 import os, time
319 time.sleep(2)
320 print('program blocked; aborting')
321 os._exit(2)
322 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000323 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324 t.start()
325
326 # This is the trace function
327 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000328 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000329 return func
330
331 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200332 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000333
Antoine Pitrou011bd622009-10-20 21:52:47 +0000334 def test_join_nondaemon_on_shutdown(self):
335 # Issue 1722344
336 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200337 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000338 import threading
339 from time import sleep
340
341 def child():
342 sleep(1)
343 # As a non-daemon thread we SHOULD wake up and nothing
344 # should be torn down yet
345 print("Woke up, sleep function is:", sleep)
346
347 threading.Thread(target=child).start()
348 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200349 """)
350 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000351 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200352 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000353
Christian Heimes1af737c2008-01-23 08:24:23 +0000354 def test_enumerate_after_join(self):
355 # Try hard to trigger #1703448: a thread is still returned in
356 # threading.enumerate() after it has been join()ed.
357 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000358 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000359 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000360 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000361 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000362 t = threading.Thread(target=lambda: None)
363 t.start()
364 t.join()
365 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000366 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000367 "#1703448 triggered after %d trials: %s" % (i, l))
368 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000369 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000370
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000371 def test_no_refcycle_through_target(self):
372 class RunSelfFunction(object):
373 def __init__(self, should_raise):
374 # The links in this refcycle from Thread back to self
375 # should be cleaned up when the thread completes.
376 self.should_raise = should_raise
377 self.thread = threading.Thread(target=self._run,
378 args=(self,),
379 kwargs={'yet_another':self})
380 self.thread.start()
381
382 def _run(self, other_ref, yet_another):
383 if self.should_raise:
384 raise SystemExit
385
386 cyclic_object = RunSelfFunction(should_raise=False)
387 weak_cyclic_object = weakref.ref(cyclic_object)
388 cyclic_object.thread.join()
389 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000390 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000391 msg=('%d references still around' %
392 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000393
394 raising_cyclic_object = RunSelfFunction(should_raise=True)
395 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
396 raising_cyclic_object.thread.join()
397 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000398 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000399 msg=('%d references still around' %
400 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000401
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000402 def test_old_threading_api(self):
403 # Just a quick sanity check to make sure the old method names are
404 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000405 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000406 t.isDaemon()
407 t.setDaemon(True)
408 t.getName()
409 t.setName("name")
410 t.isAlive()
411 e = threading.Event()
412 e.isSet()
413 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000414
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000415 def test_repr_daemon(self):
416 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200417 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000418 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200419 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000420
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000421 def test_deamon_param(self):
422 t = threading.Thread()
423 self.assertFalse(t.daemon)
424 t = threading.Thread(daemon=False)
425 self.assertFalse(t.daemon)
426 t = threading.Thread(daemon=True)
427 self.assertTrue(t.daemon)
428
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200429 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
430 def test_dummy_thread_after_fork(self):
431 # Issue #14308: a dummy thread in the active list doesn't mess up
432 # the after-fork mechanism.
433 code = """if 1:
434 import _thread, threading, os, time
435
436 def background_thread(evt):
437 # Creates and registers the _DummyThread instance
438 threading.current_thread()
439 evt.set()
440 time.sleep(10)
441
442 evt = threading.Event()
443 _thread.start_new_thread(background_thread, (evt,))
444 evt.wait()
445 assert threading.active_count() == 2, threading.active_count()
446 if os.fork() == 0:
447 assert threading.active_count() == 1, threading.active_count()
448 os._exit(0)
449 else:
450 os.wait()
451 """
452 _, out, err = assert_python_ok("-c", code)
453 self.assertEqual(out, b'')
454 self.assertEqual(err, b'')
455
Charles-François Natali9939cc82013-08-30 23:32:53 +0200456 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
457 def test_is_alive_after_fork(self):
458 # Try hard to trigger #18418: is_alive() could sometimes be True on
459 # threads that vanished after a fork.
460 old_interval = sys.getswitchinterval()
461 self.addCleanup(sys.setswitchinterval, old_interval)
462
463 # Make the bug more likely to manifest.
464 sys.setswitchinterval(1e-6)
465
466 for i in range(20):
467 t = threading.Thread(target=lambda: None)
468 t.start()
469 self.addCleanup(t.join)
470 pid = os.fork()
471 if pid == 0:
472 os._exit(1 if t.is_alive() else 0)
473 else:
474 pid, status = os.waitpid(pid, 0)
475 self.assertEqual(0, status)
476
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300477 def test_main_thread(self):
478 main = threading.main_thread()
479 self.assertEqual(main.name, 'MainThread')
480 self.assertEqual(main.ident, threading.current_thread().ident)
481 self.assertEqual(main.ident, threading.get_ident())
482
483 def f():
484 self.assertNotEqual(threading.main_thread().ident,
485 threading.current_thread().ident)
486 th = threading.Thread(target=f)
487 th.start()
488 th.join()
489
490 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
491 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
492 def test_main_thread_after_fork(self):
493 code = """if 1:
494 import os, threading
495
496 pid = os.fork()
497 if pid == 0:
498 main = threading.main_thread()
499 print(main.name)
500 print(main.ident == threading.current_thread().ident)
501 print(main.ident == threading.get_ident())
502 else:
503 os.waitpid(pid, 0)
504 """
505 _, out, err = assert_python_ok("-c", code)
506 data = out.decode().replace('\r', '')
507 self.assertEqual(err, b"")
508 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
509
510 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
511 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
512 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
513 def test_main_thread_after_fork_from_nonmain_thread(self):
514 code = """if 1:
515 import os, threading, sys
516
517 def f():
518 pid = os.fork()
519 if pid == 0:
520 main = threading.main_thread()
521 print(main.name)
522 print(main.ident == threading.current_thread().ident)
523 print(main.ident == threading.get_ident())
524 # stdout is fully buffered because not a tty,
525 # we have to flush before exit.
526 sys.stdout.flush()
527 else:
528 os.waitpid(pid, 0)
529
530 th = threading.Thread(target=f)
531 th.start()
532 th.join()
533 """
534 _, out, err = assert_python_ok("-c", code)
535 data = out.decode().replace('\r', '')
536 self.assertEqual(err, b"")
537 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
538
Antoine Pitrou7b476992013-09-07 23:38:37 +0200539 def test_tstate_lock(self):
540 # Test an implementation detail of Thread objects.
541 started = _thread.allocate_lock()
542 finish = _thread.allocate_lock()
543 started.acquire()
544 finish.acquire()
545 def f():
546 started.release()
547 finish.acquire()
548 time.sleep(0.01)
549 # The tstate lock is None until the thread is started
550 t = threading.Thread(target=f)
551 self.assertIs(t._tstate_lock, None)
552 t.start()
553 started.acquire()
554 self.assertTrue(t.is_alive())
555 # The tstate lock can't be acquired when the thread is running
556 # (or suspended).
557 tstate_lock = t._tstate_lock
558 self.assertFalse(tstate_lock.acquire(timeout=0), False)
559 finish.release()
560 # When the thread ends, the state_lock can be successfully
561 # acquired.
562 self.assertTrue(tstate_lock.acquire(timeout=5), False)
563 # But is_alive() is still True: we hold _tstate_lock now, which
564 # prevents is_alive() from knowing the thread's end-of-life C code
565 # is done.
566 self.assertTrue(t.is_alive())
567 # Let is_alive() find out the C code is done.
568 tstate_lock.release()
569 self.assertFalse(t.is_alive())
570 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200571 self.assertIsNone(t._tstate_lock)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200572
Tim Peters72460fa2013-09-09 18:48:24 -0500573 def test_repr_stopped(self):
574 # Verify that "stopped" shows up in repr(Thread) appropriately.
575 started = _thread.allocate_lock()
576 finish = _thread.allocate_lock()
577 started.acquire()
578 finish.acquire()
579 def f():
580 started.release()
581 finish.acquire()
582 t = threading.Thread(target=f)
583 t.start()
584 started.acquire()
585 self.assertIn("started", repr(t))
586 finish.release()
587 # "stopped" should appear in the repr in a reasonable amount of time.
588 # Implementation detail: as of this writing, that's trivially true
589 # if .join() is called, and almost trivially true if .is_alive() is
590 # called. The detail we're testing here is that "stopped" shows up
591 # "all on its own".
592 LOOKING_FOR = "stopped"
593 for i in range(500):
594 if LOOKING_FOR in repr(t):
595 break
596 time.sleep(0.01)
597 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Christian Heimes1af737c2008-01-23 08:24:23 +0000598
Tim Peters7634e1c2013-10-08 20:55:51 -0500599 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500600 # BoundedSemaphore should raise ValueError if released too often.
601 for limit in range(1, 10):
602 bs = threading.BoundedSemaphore(limit)
603 threads = [threading.Thread(target=bs.acquire)
604 for _ in range(limit)]
605 for t in threads:
606 t.start()
607 for t in threads:
608 t.join()
609 threads = [threading.Thread(target=bs.release)
610 for _ in range(limit)]
611 for t in threads:
612 t.start()
613 for t in threads:
614 t.join()
615 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500616
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200617 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100618 def test_frame_tstate_tracing(self):
619 # Issue #14432: Crash when a generator is created in a C thread that is
620 # destroyed while the generator is still used. The issue was that a
621 # generator contains a frame, and the frame kept a reference to the
622 # Python state of the destroyed C thread. The crash occurs when a trace
623 # function is setup.
624
625 def noop_trace(frame, event, arg):
626 # no operation
627 return noop_trace
628
629 def generator():
630 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300631 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100632
633 def callback():
634 if callback.gen is None:
635 callback.gen = generator()
636 return next(callback.gen)
637 callback.gen = None
638
639 old_trace = sys.gettrace()
640 sys.settrace(noop_trace)
641 try:
642 # Install a trace function
643 threading.settrace(noop_trace)
644
645 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200646 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100647 _testcapi.call_in_temporary_c_thread(callback)
648
649 # Call the generator in a different Python thread, check that the
650 # generator didn't keep a reference to the destroyed thread state
651 for test in range(3):
652 # The trace function is still called here
653 callback()
654 finally:
655 sys.settrace(old_trace)
656
Victor Stinner45956b92013-11-12 16:37:55 +0100657
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000658class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000659
660 def _run_and_join(self, script):
661 script = """if 1:
662 import sys, os, time, threading
663
664 # a thread, which waits for the main program to terminate
665 def joiningfunc(mainthread):
666 mainthread.join()
667 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000668 # stdout is fully buffered because not a tty, we have to flush
669 # before exit.
670 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000671 \n""" + script
672
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200673 rc, out, err = assert_python_ok("-c", script)
674 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000675 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000676
677 def test_1_join_on_shutdown(self):
678 # The usual case: on exit, wait for a non-daemon thread
679 script = """if 1:
680 import os
681 t = threading.Thread(target=joiningfunc,
682 args=(threading.current_thread(),))
683 t.start()
684 time.sleep(0.1)
685 print('end of main')
686 """
687 self._run_and_join(script)
688
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000689 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200690 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000691 def test_2_join_in_forked_process(self):
692 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000693 script = """if 1:
694 childpid = os.fork()
695 if childpid != 0:
696 os.waitpid(childpid, 0)
697 sys.exit(0)
698
699 t = threading.Thread(target=joiningfunc,
700 args=(threading.current_thread(),))
701 t.start()
702 print('end of main')
703 """
704 self._run_and_join(script)
705
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000706 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200707 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000708 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000709 # Like the test above, but fork() was called from a worker thread
710 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000711
Jesse Nollera8513972008-07-17 16:49:17 +0000712 script = """if 1:
713 main_thread = threading.current_thread()
714 def worker():
715 childpid = os.fork()
716 if childpid != 0:
717 os.waitpid(childpid, 0)
718 sys.exit(0)
719
720 t = threading.Thread(target=joiningfunc,
721 args=(main_thread,))
722 print('end of main')
723 t.start()
724 t.join() # Should not block: main_thread is already stopped
725
726 w = threading.Thread(target=worker)
727 w.start()
728 """
729 self._run_and_join(script)
730
Victor Stinner26d31862011-07-01 14:26:24 +0200731 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500732 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200733 # Check that a daemon thread cannot crash the interpreter on shutdown
734 # by manipulating internal structures that are being disposed of in
735 # the main thread.
736 script = """if True:
737 import os
738 import random
739 import sys
740 import time
741 import threading
742
743 thread_has_run = set()
744
745 def random_io():
746 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200747 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200748 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200749 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200750 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200751 null_f.write(stuff)
752 time.sleep(random.random() / 1995)
753 null_f.close()
754 in_f.close()
755 thread_has_run.add(threading.current_thread())
756
757 def main():
758 count = 0
759 for _ in range(40):
760 new_thread = threading.Thread(target=random_io)
761 new_thread.daemon = True
762 new_thread.start()
763 count += 1
764 while len(thread_has_run) < count:
765 time.sleep(0.001)
766 # Trigger process shutdown
767 sys.exit(0)
768
769 main()
770 """
771 rc, out, err = assert_python_ok('-c', script)
772 self.assertFalse(err)
773
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100774 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100775 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100776 def test_reinit_tls_after_fork(self):
777 # Issue #13817: fork() would deadlock in a multithreaded program with
778 # the ad-hoc TLS implementation.
779
780 def do_fork_and_wait():
781 # just fork a child process and wait it
782 pid = os.fork()
783 if pid > 0:
784 os.waitpid(pid, 0)
785 else:
786 os._exit(0)
787
788 # start a bunch of threads that will fork() child processes
789 threads = []
790 for i in range(16):
791 t = threading.Thread(target=do_fork_and_wait)
792 threads.append(t)
793 t.start()
794
795 for t in threads:
796 t.join()
797
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200798 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
799 def test_clear_threads_states_after_fork(self):
800 # Issue #17094: check that threads states are cleared after fork()
801
802 # start a bunch of threads
803 threads = []
804 for i in range(16):
805 t = threading.Thread(target=lambda : time.sleep(0.3))
806 threads.append(t)
807 t.start()
808
809 pid = os.fork()
810 if pid == 0:
811 # check that threads states have been cleared
812 if len(sys._current_frames()) == 1:
813 os._exit(0)
814 else:
815 os._exit(1)
816 else:
817 _, status = os.waitpid(pid, 0)
818 self.assertEqual(0, status)
819
820 for t in threads:
821 t.join()
822
Jesse Nollera8513972008-07-17 16:49:17 +0000823
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200824class SubinterpThreadingTests(BaseTestCase):
825
826 def test_threads_join(self):
827 # Non-daemon threads should be joined at subinterpreter shutdown
828 # (issue #18808)
829 r, w = os.pipe()
830 self.addCleanup(os.close, r)
831 self.addCleanup(os.close, w)
832 code = r"""if 1:
833 import os
834 import threading
835 import time
836
837 def f():
838 # Sleep a bit so that the thread is still running when
839 # Py_EndInterpreter is called.
840 time.sleep(0.05)
841 os.write(%d, b"x")
842 threading.Thread(target=f).start()
843 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100844 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200845 self.assertEqual(ret, 0)
846 # The thread was joined properly.
847 self.assertEqual(os.read(r, 1), b"x")
848
Antoine Pitrou7b476992013-09-07 23:38:37 +0200849 def test_threads_join_2(self):
850 # Same as above, but a delay gets introduced after the thread's
851 # Python code returned but before the thread state is deleted.
852 # To achieve this, we register a thread-local object which sleeps
853 # a bit when deallocated.
854 r, w = os.pipe()
855 self.addCleanup(os.close, r)
856 self.addCleanup(os.close, w)
857 code = r"""if 1:
858 import os
859 import threading
860 import time
861
862 class Sleeper:
863 def __del__(self):
864 time.sleep(0.05)
865
866 tls = threading.local()
867
868 def f():
869 # Sleep a bit so that the thread is still running when
870 # Py_EndInterpreter is called.
871 time.sleep(0.05)
872 tls.x = Sleeper()
873 os.write(%d, b"x")
874 threading.Thread(target=f).start()
875 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100876 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200877 self.assertEqual(ret, 0)
878 # The thread was joined properly.
879 self.assertEqual(os.read(r, 1), b"x")
880
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200881 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200882 def test_daemon_threads_fatal_error(self):
883 subinterp_code = r"""if 1:
884 import os
885 import threading
886 import time
887
888 def f():
889 # Make sure the daemon thread is still running when
890 # Py_EndInterpreter is called.
891 time.sleep(10)
892 threading.Thread(target=f, daemon=True).start()
893 """
894 script = r"""if 1:
895 import _testcapi
896
897 _testcapi.run_in_subinterp(%r)
898 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200899 with test.support.SuppressCrashReport():
900 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200901 self.assertIn("Fatal Python error: Py_EndInterpreter: "
902 "not the last thread", err.decode())
903
904
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000905class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000906 # A RuntimeError should be raised if Thread.start() is called
907 # multiple times.
908 def test_start_thread_again(self):
909 thread = threading.Thread()
910 thread.start()
911 self.assertRaises(RuntimeError, thread.start)
912
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000913 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000914 current_thread = threading.current_thread()
915 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000916
917 def test_joining_inactive_thread(self):
918 thread = threading.Thread()
919 self.assertRaises(RuntimeError, thread.join)
920
921 def test_daemonize_active_thread(self):
922 thread = threading.Thread()
923 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000924 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000925
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000926 def test_releasing_unacquired_lock(self):
927 lock = threading.Lock()
928 self.assertRaises(RuntimeError, lock.release)
929
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400930 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
931 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700932 def test_recursion_limit(self):
933 # Issue 9670
934 # test that excessive recursion within a non-main thread causes
935 # an exception rather than crashing the interpreter on platforms
936 # like Mac OS X or FreeBSD which have small default stack sizes
937 # for threads
938 script = """if True:
939 import threading
940
941 def recurse():
942 return recurse()
943
944 def outer():
945 try:
946 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400947 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700948 pass
949
950 w = threading.Thread(target=outer)
951 w.start()
952 w.join()
953 print('end of main thread')
954 """
955 expected_output = "end of main thread\n"
956 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200957 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700958 stdout, stderr = p.communicate()
959 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200960 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700961 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000962
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300963 def test_print_exception(self):
964 script = r"""if True:
965 import threading
966 import time
967
968 running = False
969 def run():
970 global running
971 running = True
972 while running:
973 time.sleep(0.01)
974 1/0
975 t = threading.Thread(target=run)
976 t.start()
977 while not running:
978 time.sleep(0.01)
979 running = False
980 t.join()
981 """
982 rc, out, err = assert_python_ok("-c", script)
983 self.assertEqual(out, b'')
984 err = err.decode()
985 self.assertIn("Exception in thread", err)
986 self.assertIn("Traceback (most recent call last):", err)
987 self.assertIn("ZeroDivisionError", err)
988 self.assertNotIn("Unhandled exception", err)
989
990 def test_print_exception_stderr_is_none_1(self):
991 script = r"""if True:
992 import sys
993 import threading
994 import time
995
996 running = False
997 def run():
998 global running
999 running = True
1000 while running:
1001 time.sleep(0.01)
1002 1/0
1003 t = threading.Thread(target=run)
1004 t.start()
1005 while not running:
1006 time.sleep(0.01)
1007 sys.stderr = None
1008 running = False
1009 t.join()
1010 """
1011 rc, out, err = assert_python_ok("-c", script)
1012 self.assertEqual(out, b'')
1013 err = err.decode()
1014 self.assertIn("Exception in thread", err)
1015 self.assertIn("Traceback (most recent call last):", err)
1016 self.assertIn("ZeroDivisionError", err)
1017 self.assertNotIn("Unhandled exception", err)
1018
1019 def test_print_exception_stderr_is_none_2(self):
1020 script = r"""if True:
1021 import sys
1022 import threading
1023 import time
1024
1025 running = False
1026 def run():
1027 global running
1028 running = True
1029 while running:
1030 time.sleep(0.01)
1031 1/0
1032 sys.stderr = None
1033 t = threading.Thread(target=run)
1034 t.start()
1035 while not running:
1036 time.sleep(0.01)
1037 running = False
1038 t.join()
1039 """
1040 rc, out, err = assert_python_ok("-c", script)
1041 self.assertEqual(out, b'')
1042 self.assertNotIn("Unhandled exception", err.decode())
1043
1044
R David Murray19aeb432013-03-30 17:19:38 -04001045class TimerTests(BaseTestCase):
1046
1047 def setUp(self):
1048 BaseTestCase.setUp(self)
1049 self.callback_args = []
1050 self.callback_event = threading.Event()
1051
1052 def test_init_immutable_default_args(self):
1053 # Issue 17435: constructor defaults were mutable objects, they could be
1054 # mutated via the object attributes and affect other Timer objects.
1055 timer1 = threading.Timer(0.01, self._callback_spy)
1056 timer1.start()
1057 self.callback_event.wait()
1058 timer1.args.append("blah")
1059 timer1.kwargs["foo"] = "bar"
1060 self.callback_event.clear()
1061 timer2 = threading.Timer(0.01, self._callback_spy)
1062 timer2.start()
1063 self.callback_event.wait()
1064 self.assertEqual(len(self.callback_args), 2)
1065 self.assertEqual(self.callback_args, [((), {}), ((), {})])
1066
1067 def _callback_spy(self, *args, **kwargs):
1068 self.callback_args.append((args[:], kwargs.copy()))
1069 self.callback_event.set()
1070
Antoine Pitrou557934f2009-11-06 22:41:14 +00001071class LockTests(lock_tests.LockTests):
1072 locktype = staticmethod(threading.Lock)
1073
Antoine Pitrou434736a2009-11-10 18:46:01 +00001074class PyRLockTests(lock_tests.RLockTests):
1075 locktype = staticmethod(threading._PyRLock)
1076
Charles-François Natali6b671b22012-01-28 11:36:04 +01001077@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001078class CRLockTests(lock_tests.RLockTests):
1079 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001080
1081class EventTests(lock_tests.EventTests):
1082 eventtype = staticmethod(threading.Event)
1083
1084class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001085 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001086 locktype = staticmethod(threading.Condition)
1087
1088class ConditionTests(lock_tests.ConditionTests):
1089 condtype = staticmethod(threading.Condition)
1090
1091class SemaphoreTests(lock_tests.SemaphoreTests):
1092 semtype = staticmethod(threading.Semaphore)
1093
1094class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1095 semtype = staticmethod(threading.BoundedSemaphore)
1096
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001097class BarrierTests(lock_tests.BarrierTests):
1098 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001099
Martin Panter19e69c52015-11-14 12:46:42 +00001100class MiscTestCase(unittest.TestCase):
1101 def test__all__(self):
1102 extra = {"ThreadError"}
1103 blacklist = {'currentThread', 'activeCount'}
1104 support.check__all__(self, threading, ('threading', '_thread'),
1105 extra=extra, blacklist=blacklist)
1106
Tim Peters84d54892005-01-08 06:03:17 +00001107if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001108 unittest.main()