blob: fee48a391024afce8526c1f22b1cda4874408304 [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
Antoine Pitrouc4d78642011-05-05 20:17:32 +02006from test.support import verbose, strip_python_stderr, import_module
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02007from test.script_helper import assert_python_ok
8
Skip Montanaro4533f602001-08-20 20:28:48 +00009import random
Georg Brandl0c77a822008-06-10 16:37:50 +000010import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011import sys
Antoine Pitrouc4d78642011-05-05 20:17:32 +020012_thread = import_module('_thread')
13threading = import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000014import time
Tim Peters84d54892005-01-08 06:03:17 +000015import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000016import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000017import os
Antoine Pitrouc4d78642011-05-05 20:17:32 +020018from test.script_helper import assert_python_ok, assert_python_failure
Gregory P. Smith4b129d22011-01-04 00:51:50 +000019import subprocess
Victor Stinner13105102013-12-13 02:17:29 +010020try:
21 import _testcapi
22except ImportError:
23 _testcapi = None
Skip Montanaro4533f602001-08-20 20:28:48 +000024
Antoine Pitrou557934f2009-11-06 22:41:14 +000025from test import lock_tests
26
Tim Peters84d54892005-01-08 06:03:17 +000027# A trivial mutable counter.
28class Counter(object):
29 def __init__(self):
30 self.value = 0
31 def inc(self):
32 self.value += 1
33 def dec(self):
34 self.value -= 1
35 def get(self):
36 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000037
38class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000039 def __init__(self, name, testcase, sema, mutex, nrunning):
40 threading.Thread.__init__(self, name=name)
41 self.testcase = testcase
42 self.sema = sema
43 self.mutex = mutex
44 self.nrunning = nrunning
45
Skip Montanaro4533f602001-08-20 20:28:48 +000046 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000047 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000048 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000049 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000050 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000051
Christian Heimes4fbc72b2008-03-22 00:47:35 +000052 with self.sema:
53 with self.mutex:
54 self.nrunning.inc()
55 if verbose:
56 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000057 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000058
Christian Heimes4fbc72b2008-03-22 00:47:35 +000059 time.sleep(delay)
60 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000061 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000062
Christian Heimes4fbc72b2008-03-22 00:47:35 +000063 with self.mutex:
64 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000065 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000066 if verbose:
67 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000068 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000069
Skip Montanaro4533f602001-08-20 20:28:48 +000070
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000071class BaseTestCase(unittest.TestCase):
72 def setUp(self):
73 self._threads = test.support.threading_setup()
74
75 def tearDown(self):
76 test.support.threading_cleanup(*self._threads)
77 test.support.reap_children()
78
79
80class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000081
Tim Peters84d54892005-01-08 06:03:17 +000082 # Create a bunch of threads, let each do some work, wait until all are
83 # done.
84 def test_various_ops(self):
85 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
86 # times about 1 second per clump).
87 NUMTASKS = 10
88
89 # no more than 3 of the 10 can run at once
90 sema = threading.BoundedSemaphore(value=3)
91 mutex = threading.RLock()
92 numrunning = Counter()
93
94 threads = []
95
96 for i in range(NUMTASKS):
97 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
98 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertEqual(t.ident, None)
100 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000101 t.start()
102
103 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000105 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +0000106 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000107 self.assertTrue(not t.is_alive())
108 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000109 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000110 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
111 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000112 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000113 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000114 self.assertEqual(numrunning.get(), 0)
115
Benjamin Petersond23f8222009-04-05 19:13:16 +0000116 def test_ident_of_no_threading_threads(self):
117 # The ident still must work for the main thread and dummy threads.
118 self.assertFalse(threading.currentThread().ident is None)
119 def f():
120 ident.append(threading.currentThread().ident)
121 done.set()
122 done = threading.Event()
123 ident = []
124 _thread.start_new_thread(f, ())
125 done.wait()
126 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000127 # Kill the "immortal" _DummyThread
128 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000129
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 # run with a small(ish) thread stack size (256kB)
131 def test_various_ops_small_stack(self):
132 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000133 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000134 try:
135 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000136 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000137 raise unittest.SkipTest(
138 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 self.test_various_ops()
140 threading.stack_size(0)
141
142 # run with a large thread stack size (1MB)
143 def test_various_ops_large_stack(self):
144 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000145 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 try:
147 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000148 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000149 raise unittest.SkipTest(
150 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151 self.test_various_ops()
152 threading.stack_size(0)
153
Tim Peters711906e2005-01-08 07:30:42 +0000154 def test_foreign_thread(self):
155 # Check that a "foreign" thread can use the threading module.
156 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000157 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000158 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000159 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000160 mutex.release()
161
162 mutex = threading.Lock()
163 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000164 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000165 # Wait for the thread to finish.
166 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000167 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000168 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000169 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000170
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000171 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
172 # exposed at the Python level. This test relies on ctypes to get at it.
173 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200174 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000175
176 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
177
178 class AsyncExc(Exception):
179 pass
180
181 exception = ctypes.py_object(AsyncExc)
182
Antoine Pitroube4d8092009-10-18 18:27:17 +0000183 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200184 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000185
186 try:
187 result = set_async_exc(ctypes.c_long(tid), exception)
188 # The exception is async, so we might have to keep the VM busy until
189 # it notices.
190 while True:
191 pass
192 except AsyncExc:
193 pass
194 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000195 # This code is unreachable but it reflects the intent. If we wanted
196 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000197 self.fail("AsyncExc not raised")
198 try:
199 self.assertEqual(result, 1) # one thread state modified
200 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000201 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000202 pass
203
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000204 # `worker_started` is set by the thread when it's inside a try/except
205 # block waiting to catch the asynchronously set AsyncExc exception.
206 # `worker_saw_exception` is set by the thread upon catching that
207 # exception.
208 worker_started = threading.Event()
209 worker_saw_exception = threading.Event()
210
211 class Worker(threading.Thread):
212 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200213 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000214 self.finished = False
215
216 try:
217 while True:
218 worker_started.set()
219 time.sleep(0.1)
220 except AsyncExc:
221 self.finished = True
222 worker_saw_exception.set()
223
224 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000225 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000226 t.start()
227 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000228 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000229
230 # Try a thread id that doesn't make sense.
231 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000232 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 result = set_async_exc(ctypes.c_long(-1), exception)
234 self.assertEqual(result, 0) # no thread states modified
235
236 # Now raise an exception in the worker thread.
237 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000238 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000239 ret = worker_started.wait()
240 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000242 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000243 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 result = set_async_exc(ctypes.c_long(t.id), exception)
247 self.assertEqual(result, 1) # one thread state modified
248 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000250 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000251 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000252 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000253 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000254 if t.finished:
255 t.join()
256 # else the thread is still running, and we have no way to kill it
257
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000258 def test_limbo_cleanup(self):
259 # Issue 7481: Failure to start thread should cleanup the limbo map.
260 def fail_new_thread(*args):
261 raise threading.ThreadError()
262 _start_new_thread = threading._start_new_thread
263 threading._start_new_thread = fail_new_thread
264 try:
265 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000266 self.assertRaises(threading.ThreadError, t.start)
267 self.assertFalse(
268 t in threading._limbo,
269 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000270 finally:
271 threading._start_new_thread = _start_new_thread
272
Christian Heimes7d2ff882007-11-30 14:35:04 +0000273 def test_finalize_runnning_thread(self):
274 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
275 # very late on python exit: on deallocation of a running thread for
276 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200277 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200279 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000280 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000281
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000282 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000283 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000284 ready.acquire()
285
Christian Heimes7d2ff882007-11-30 14:35:04 +0000286 # Module globals are cleared before __del__ is run
287 # So we save the functions in class dict
288 class C:
289 ensure = ctypes.pythonapi.PyGILState_Ensure
290 release = ctypes.pythonapi.PyGILState_Release
291 def __del__(self):
292 state = self.ensure()
293 self.release(state)
294
295 def waitingThread():
296 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000297 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000298 time.sleep(100)
299
Georg Brandl2067bfd2008-05-25 13:05:15 +0000300 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000301 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000302 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200303 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000304 self.assertEqual(rc, 42)
305
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000306 def test_finalize_with_trace(self):
307 # Issue1733757
308 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200309 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000310 import sys, threading
311
312 # A deadlock-killer, to prevent the
313 # testsuite to hang forever
314 def killer():
315 import os, time
316 time.sleep(2)
317 print('program blocked; aborting')
318 os._exit(2)
319 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000320 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000321 t.start()
322
323 # This is the trace function
324 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000325 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000326 return func
327
328 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200329 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000330
Antoine Pitrou011bd622009-10-20 21:52:47 +0000331 def test_join_nondaemon_on_shutdown(self):
332 # Issue 1722344
333 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200334 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000335 import threading
336 from time import sleep
337
338 def child():
339 sleep(1)
340 # As a non-daemon thread we SHOULD wake up and nothing
341 # should be torn down yet
342 print("Woke up, sleep function is:", sleep)
343
344 threading.Thread(target=child).start()
345 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200346 """)
347 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000348 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200349 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000350
Christian Heimes1af737c2008-01-23 08:24:23 +0000351 def test_enumerate_after_join(self):
352 # Try hard to trigger #1703448: a thread is still returned in
353 # threading.enumerate() after it has been join()ed.
354 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000355 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000356 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000357 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000358 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000359 t = threading.Thread(target=lambda: None)
360 t.start()
361 t.join()
362 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000363 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000364 "#1703448 triggered after %d trials: %s" % (i, l))
365 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000366 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000367
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000368 def test_no_refcycle_through_target(self):
369 class RunSelfFunction(object):
370 def __init__(self, should_raise):
371 # The links in this refcycle from Thread back to self
372 # should be cleaned up when the thread completes.
373 self.should_raise = should_raise
374 self.thread = threading.Thread(target=self._run,
375 args=(self,),
376 kwargs={'yet_another':self})
377 self.thread.start()
378
379 def _run(self, other_ref, yet_another):
380 if self.should_raise:
381 raise SystemExit
382
383 cyclic_object = RunSelfFunction(should_raise=False)
384 weak_cyclic_object = weakref.ref(cyclic_object)
385 cyclic_object.thread.join()
386 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000387 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000388 msg=('%d references still around' %
389 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000390
391 raising_cyclic_object = RunSelfFunction(should_raise=True)
392 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
393 raising_cyclic_object.thread.join()
394 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000395 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000396 msg=('%d references still around' %
397 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000398
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000399 def test_old_threading_api(self):
400 # Just a quick sanity check to make sure the old method names are
401 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000402 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000403 t.isDaemon()
404 t.setDaemon(True)
405 t.getName()
406 t.setName("name")
407 t.isAlive()
408 e = threading.Event()
409 e.isSet()
410 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000411
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000412 def test_repr_daemon(self):
413 t = threading.Thread()
414 self.assertFalse('daemon' in repr(t))
415 t.daemon = True
416 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000417
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000418 def test_deamon_param(self):
419 t = threading.Thread()
420 self.assertFalse(t.daemon)
421 t = threading.Thread(daemon=False)
422 self.assertFalse(t.daemon)
423 t = threading.Thread(daemon=True)
424 self.assertTrue(t.daemon)
425
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200426 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
427 def test_dummy_thread_after_fork(self):
428 # Issue #14308: a dummy thread in the active list doesn't mess up
429 # the after-fork mechanism.
430 code = """if 1:
431 import _thread, threading, os, time
432
433 def background_thread(evt):
434 # Creates and registers the _DummyThread instance
435 threading.current_thread()
436 evt.set()
437 time.sleep(10)
438
439 evt = threading.Event()
440 _thread.start_new_thread(background_thread, (evt,))
441 evt.wait()
442 assert threading.active_count() == 2, threading.active_count()
443 if os.fork() == 0:
444 assert threading.active_count() == 1, threading.active_count()
445 os._exit(0)
446 else:
447 os.wait()
448 """
449 _, out, err = assert_python_ok("-c", code)
450 self.assertEqual(out, b'')
451 self.assertEqual(err, b'')
452
Charles-François Natali9939cc82013-08-30 23:32:53 +0200453 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
454 def test_is_alive_after_fork(self):
455 # Try hard to trigger #18418: is_alive() could sometimes be True on
456 # threads that vanished after a fork.
457 old_interval = sys.getswitchinterval()
458 self.addCleanup(sys.setswitchinterval, old_interval)
459
460 # Make the bug more likely to manifest.
461 sys.setswitchinterval(1e-6)
462
463 for i in range(20):
464 t = threading.Thread(target=lambda: None)
465 t.start()
466 self.addCleanup(t.join)
467 pid = os.fork()
468 if pid == 0:
469 os._exit(1 if t.is_alive() else 0)
470 else:
471 pid, status = os.waitpid(pid, 0)
472 self.assertEqual(0, status)
473
Christian Heimes1af737c2008-01-23 08:24:23 +0000474
Tim Peters7634e1c2013-10-08 20:55:51 -0500475 def test_BoundedSemaphore_limit(self):
476 # BoundedSemaphore should raise ValueError if released too often.
477 for limit in range(1, 10):
478 bs = threading.BoundedSemaphore(limit)
479 threads = [threading.Thread(target=bs.acquire)
480 for _ in range(limit)]
481 for t in threads:
482 t.start()
483 for t in threads:
484 t.join()
485 threads = [threading.Thread(target=bs.release)
486 for _ in range(limit)]
487 for t in threads:
488 t.start()
489 for t in threads:
490 t.join()
491 self.assertRaises(ValueError, bs.release)
492
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000493class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000494
Victor Stinner26d31862011-07-01 14:26:24 +0200495 # Between fork() and exec(), only async-safe functions are allowed (issues
496 # #12316 and #11870), and fork() from a worker thread is known to trigger
497 # problems with some operating systems (issue #3863): skip problematic tests
498 # on platforms known to behave badly.
499 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
Stefan Krahfc4aa762013-01-17 23:29:54 +0100500 'os2emx', 'hp-ux11')
Victor Stinner26d31862011-07-01 14:26:24 +0200501
Jesse Nollera8513972008-07-17 16:49:17 +0000502 def _run_and_join(self, script):
503 script = """if 1:
504 import sys, os, time, threading
505
506 # a thread, which waits for the main program to terminate
507 def joiningfunc(mainthread):
508 mainthread.join()
509 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000510 # stdout is fully buffered because not a tty, we have to flush
511 # before exit.
512 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000513 \n""" + script
514
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200515 rc, out, err = assert_python_ok("-c", script)
516 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000517 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000518
519 def test_1_join_on_shutdown(self):
520 # The usual case: on exit, wait for a non-daemon thread
521 script = """if 1:
522 import os
523 t = threading.Thread(target=joiningfunc,
524 args=(threading.current_thread(),))
525 t.start()
526 time.sleep(0.1)
527 print('end of main')
528 """
529 self._run_and_join(script)
530
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000531 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200532 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000533 def test_2_join_in_forked_process(self):
534 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000535 script = """if 1:
536 childpid = os.fork()
537 if childpid != 0:
538 os.waitpid(childpid, 0)
539 sys.exit(0)
540
541 t = threading.Thread(target=joiningfunc,
542 args=(threading.current_thread(),))
543 t.start()
544 print('end of main')
545 """
546 self._run_and_join(script)
547
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000548 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200549 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000550 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000551 # Like the test above, but fork() was called from a worker thread
552 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000553
Jesse Nollera8513972008-07-17 16:49:17 +0000554 script = """if 1:
555 main_thread = threading.current_thread()
556 def worker():
557 childpid = os.fork()
558 if childpid != 0:
559 os.waitpid(childpid, 0)
560 sys.exit(0)
561
562 t = threading.Thread(target=joiningfunc,
563 args=(main_thread,))
564 print('end of main')
565 t.start()
566 t.join() # Should not block: main_thread is already stopped
567
568 w = threading.Thread(target=worker)
569 w.start()
570 """
571 self._run_and_join(script)
572
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000573 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200574 rc, out, err = assert_python_ok("-c", script)
575 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000576 self.assertEqual(data, expected_output)
577
578 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200579 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000580 def test_4_joining_across_fork_in_worker_thread(self):
581 # There used to be a possible deadlock when forking from a child
582 # thread. See http://bugs.python.org/issue6643.
583
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000584 # The script takes the following steps:
585 # - The main thread in the parent process starts a new thread and then
586 # tries to join it.
587 # - The join operation acquires the Lock inside the thread's _block
588 # Condition. (See threading.py:Thread.join().)
589 # - We stub out the acquire method on the condition to force it to wait
590 # until the child thread forks. (See LOCK ACQUIRED HERE)
591 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
592 # HERE)
593 # - The main thread of the parent process enters Condition.wait(),
594 # which releases the lock on the child thread.
595 # - The child process returns. Without the necessary fix, when the
596 # main thread of the child process (which used to be the child thread
597 # in the parent process) attempts to exit, it will try to acquire the
598 # lock in the Thread._block Condition object and hang, because the
599 # lock was held across the fork.
600
601 script = """if 1:
602 import os, time, threading
603
604 finish_join = False
605 start_fork = False
606
607 def worker():
608 # Wait until this thread's lock is acquired before forking to
609 # create the deadlock.
610 global finish_join
611 while not start_fork:
612 time.sleep(0.01)
613 # LOCK HELD: Main thread holds lock across this call.
614 childpid = os.fork()
615 finish_join = True
616 if childpid != 0:
617 # Parent process just waits for child.
618 os.waitpid(childpid, 0)
619 # Child process should just return.
620
621 w = threading.Thread(target=worker)
622
623 # Stub out the private condition variable's lock acquire method.
624 # This acquires the lock and then waits until the child has forked
625 # before returning, which will release the lock soon after. If
626 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200627 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000628 # deadlock when it shouldn't.
629 condition = w._block
630 orig_acquire = condition.acquire
631 call_count_lock = threading.Lock()
632 call_count = 0
633 def my_acquire():
634 global call_count
635 global start_fork
636 orig_acquire() # LOCK ACQUIRED HERE
637 start_fork = True
638 if call_count == 0:
639 while not finish_join:
640 time.sleep(0.01) # WORKER THREAD FORKS HERE
641 with call_count_lock:
642 call_count += 1
643 condition.acquire = my_acquire
644
645 w.start()
646 w.join()
647 print('end of main')
648 """
649 self.assertScriptHasOutput(script, "end of main\n")
650
651 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200652 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000653 def test_5_clear_waiter_locks_to_avoid_crash(self):
654 # Check that a spawned thread that forks doesn't segfault on certain
655 # platforms, namely OS X. This used to happen if there was a waiter
656 # lock in the thread's condition variable's waiters list. Even though
657 # we know the lock will be held across the fork, it is not safe to
658 # release locks held across forks on all platforms, so releasing the
659 # waiter lock caused a segfault on OS X. Furthermore, since locks on
660 # OS X are (as of this writing) implemented with a mutex + condition
661 # variable instead of a semaphore, while we know that the Python-level
662 # lock will be acquired, we can't know if the internal mutex will be
663 # acquired at the time of the fork.
664
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000665 script = """if True:
666 import os, time, threading
667
668 start_fork = False
669
670 def worker():
671 # Wait until the main thread has attempted to join this thread
672 # before continuing.
673 while not start_fork:
674 time.sleep(0.01)
675 childpid = os.fork()
676 if childpid != 0:
677 # Parent process just waits for child.
678 (cpid, rc) = os.waitpid(childpid, 0)
679 assert cpid == childpid
680 assert rc == 0
681 print('end of worker thread')
682 else:
683 # Child process should just return.
684 pass
685
686 w = threading.Thread(target=worker)
687
688 # Stub out the private condition variable's _release_save method.
689 # This releases the condition's lock and flips the global that
690 # causes the worker to fork. At this point, the problematic waiter
691 # lock has been acquired once by the waiter and has been put onto
692 # the waiters list.
693 condition = w._block
694 orig_release_save = condition._release_save
695 def my_release_save():
696 global start_fork
697 orig_release_save()
698 # Waiter lock held here, condition lock released.
699 start_fork = True
700 condition._release_save = my_release_save
701
702 w.start()
703 w.join()
704 print('end of main thread')
705 """
706 output = "end of worker thread\nend of main thread\n"
707 self.assertScriptHasOutput(script, output)
708
Charles-François Natali8e6fe642012-03-24 20:36:09 +0100709 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200710 def test_6_daemon_threads(self):
711 # Check that a daemon thread cannot crash the interpreter on shutdown
712 # by manipulating internal structures that are being disposed of in
713 # the main thread.
714 script = """if True:
715 import os
716 import random
717 import sys
718 import time
719 import threading
720
721 thread_has_run = set()
722
723 def random_io():
724 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200725 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200726 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200727 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200728 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200729 null_f.write(stuff)
730 time.sleep(random.random() / 1995)
731 null_f.close()
732 in_f.close()
733 thread_has_run.add(threading.current_thread())
734
735 def main():
736 count = 0
737 for _ in range(40):
738 new_thread = threading.Thread(target=random_io)
739 new_thread.daemon = True
740 new_thread.start()
741 count += 1
742 while len(thread_has_run) < count:
743 time.sleep(0.001)
744 # Trigger process shutdown
745 sys.exit(0)
746
747 main()
748 """
749 rc, out, err = assert_python_ok('-c', script)
750 self.assertFalse(err)
751
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100752 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100753 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100754 def test_reinit_tls_after_fork(self):
755 # Issue #13817: fork() would deadlock in a multithreaded program with
756 # the ad-hoc TLS implementation.
757
758 def do_fork_and_wait():
759 # just fork a child process and wait it
760 pid = os.fork()
761 if pid > 0:
762 os.waitpid(pid, 0)
763 else:
764 os._exit(0)
765
766 # start a bunch of threads that will fork() child processes
767 threads = []
768 for i in range(16):
769 t = threading.Thread(target=do_fork_and_wait)
770 threads.append(t)
771 t.start()
772
773 for t in threads:
774 t.join()
775
Victor Stinner13105102013-12-13 02:17:29 +0100776 @unittest.skipIf(_testcapi is None, "need _testcapi module")
777 def test_frame_tstate_tracing(self):
778 # Issue #14432: Crash when a generator is created in a C thread that is
779 # destroyed while the generator is still used. The issue was that a
780 # generator contains a frame, and the frame kept a reference to the
781 # Python state of the destroyed C thread. The crash occurs when a trace
782 # function is setup.
783
784 def noop_trace(frame, event, arg):
785 # no operation
786 return noop_trace
787
788 def generator():
789 while 1:
790 yield "genereator"
791
792 def callback():
793 if callback.gen is None:
794 callback.gen = generator()
795 return next(callback.gen)
796 callback.gen = None
797
798 old_trace = sys.gettrace()
799 sys.settrace(noop_trace)
800 try:
801 # Install a trace function
802 threading.settrace(noop_trace)
803
804 # Create a generator in a C thread which exits after the call
805 _testcapi.call_in_temporary_c_thread(callback)
806
807 # Call the generator in a different Python thread, check that the
808 # generator didn't keep a reference to the destroyed thread state
809 for test in range(3):
810 # The trace function is still called here
811 callback()
812 finally:
813 sys.settrace(old_trace)
814
Jesse Nollera8513972008-07-17 16:49:17 +0000815
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000816class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000817 # A RuntimeError should be raised if Thread.start() is called
818 # multiple times.
819 def test_start_thread_again(self):
820 thread = threading.Thread()
821 thread.start()
822 self.assertRaises(RuntimeError, thread.start)
823
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000824 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000825 current_thread = threading.current_thread()
826 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000827
828 def test_joining_inactive_thread(self):
829 thread = threading.Thread()
830 self.assertRaises(RuntimeError, thread.join)
831
832 def test_daemonize_active_thread(self):
833 thread = threading.Thread()
834 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000835 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000836
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000837 def test_releasing_unacquired_lock(self):
838 lock = threading.Lock()
839 self.assertRaises(RuntimeError, lock.release)
840
Łukasz Langa20ea96f2013-04-24 01:29:26 +0200841 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
842 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700843 def test_recursion_limit(self):
844 # Issue 9670
845 # test that excessive recursion within a non-main thread causes
846 # an exception rather than crashing the interpreter on platforms
847 # like Mac OS X or FreeBSD which have small default stack sizes
848 # for threads
849 script = """if True:
850 import threading
851
852 def recurse():
853 return recurse()
854
855 def outer():
856 try:
857 recurse()
858 except RuntimeError:
859 pass
860
861 w = threading.Thread(target=outer)
862 w.start()
863 w.join()
864 print('end of main thread')
865 """
866 expected_output = "end of main thread\n"
867 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200868 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700869 stdout, stderr = p.communicate()
870 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200871 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700872 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000873
R David Murray19aeb432013-03-30 17:19:38 -0400874class TimerTests(BaseTestCase):
875
876 def setUp(self):
877 BaseTestCase.setUp(self)
878 self.callback_args = []
879 self.callback_event = threading.Event()
880
881 def test_init_immutable_default_args(self):
882 # Issue 17435: constructor defaults were mutable objects, they could be
883 # mutated via the object attributes and affect other Timer objects.
884 timer1 = threading.Timer(0.01, self._callback_spy)
885 timer1.start()
886 self.callback_event.wait()
887 timer1.args.append("blah")
888 timer1.kwargs["foo"] = "bar"
889 self.callback_event.clear()
890 timer2 = threading.Timer(0.01, self._callback_spy)
891 timer2.start()
892 self.callback_event.wait()
893 self.assertEqual(len(self.callback_args), 2)
894 self.assertEqual(self.callback_args, [((), {}), ((), {})])
895
896 def _callback_spy(self, *args, **kwargs):
897 self.callback_args.append((args[:], kwargs.copy()))
898 self.callback_event.set()
899
Antoine Pitrou557934f2009-11-06 22:41:14 +0000900class LockTests(lock_tests.LockTests):
901 locktype = staticmethod(threading.Lock)
902
Antoine Pitrou434736a2009-11-10 18:46:01 +0000903class PyRLockTests(lock_tests.RLockTests):
904 locktype = staticmethod(threading._PyRLock)
905
Charles-François Natali6b671b22012-01-28 11:36:04 +0100906@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +0000907class CRLockTests(lock_tests.RLockTests):
908 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000909
910class EventTests(lock_tests.EventTests):
911 eventtype = staticmethod(threading.Event)
912
913class ConditionAsRLockTests(lock_tests.RLockTests):
914 # An Condition uses an RLock by default and exports its API.
915 locktype = staticmethod(threading.Condition)
916
917class ConditionTests(lock_tests.ConditionTests):
918 condtype = staticmethod(threading.Condition)
919
920class SemaphoreTests(lock_tests.SemaphoreTests):
921 semtype = staticmethod(threading.Semaphore)
922
923class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
924 semtype = staticmethod(threading.BoundedSemaphore)
925
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000926class BarrierTests(lock_tests.BarrierTests):
927 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000928
Tim Peters84d54892005-01-08 06:03:17 +0000929if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -0400930 unittest.main()