blob: 29ce0394135ec248652545e12f1612201a63baab [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')
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +020014import _testcapi
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
Antoine Pitrouc4d78642011-05-05 20:17:32 +020019from test.script_helper import assert_python_ok, assert_python_failure
Gregory P. Smith4b129d22011-01-04 00:51:50 +000020import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000021
Antoine Pitrou557934f2009-11-06 22:41:14 +000022from test import lock_tests
23
Tim Peters84d54892005-01-08 06:03:17 +000024# A trivial mutable counter.
25class Counter(object):
26 def __init__(self):
27 self.value = 0
28 def inc(self):
29 self.value += 1
30 def dec(self):
31 self.value -= 1
32 def get(self):
33 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000034
35class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000036 def __init__(self, name, testcase, sema, mutex, nrunning):
37 threading.Thread.__init__(self, name=name)
38 self.testcase = testcase
39 self.sema = sema
40 self.mutex = mutex
41 self.nrunning = nrunning
42
Skip Montanaro4533f602001-08-20 20:28:48 +000043 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000044 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000045 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000046 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000047 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000048
Christian Heimes4fbc72b2008-03-22 00:47:35 +000049 with self.sema:
50 with self.mutex:
51 self.nrunning.inc()
52 if verbose:
53 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000054 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000055
Christian Heimes4fbc72b2008-03-22 00:47:35 +000056 time.sleep(delay)
57 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000058 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000059
Christian Heimes4fbc72b2008-03-22 00:47:35 +000060 with self.mutex:
61 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000062 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000063 if verbose:
64 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000065 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000066
Skip Montanaro4533f602001-08-20 20:28:48 +000067
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000068class BaseTestCase(unittest.TestCase):
69 def setUp(self):
70 self._threads = test.support.threading_setup()
71
72 def tearDown(self):
73 test.support.threading_cleanup(*self._threads)
74 test.support.reap_children()
75
76
77class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000078
Tim Peters84d54892005-01-08 06:03:17 +000079 # Create a bunch of threads, let each do some work, wait until all are
80 # done.
81 def test_various_ops(self):
82 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
83 # times about 1 second per clump).
84 NUMTASKS = 10
85
86 # no more than 3 of the 10 can run at once
87 sema = threading.BoundedSemaphore(value=3)
88 mutex = threading.RLock()
89 numrunning = Counter()
90
91 threads = []
92
93 for i in range(NUMTASKS):
94 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
95 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000096 self.assertEqual(t.ident, None)
97 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000098 t.start()
99
100 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000101 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000102 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +0000103 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000104 self.assertTrue(not t.is_alive())
105 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000106 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000107 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
108 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000109 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000111 self.assertEqual(numrunning.get(), 0)
112
Benjamin Petersond23f8222009-04-05 19:13:16 +0000113 def test_ident_of_no_threading_threads(self):
114 # The ident still must work for the main thread and dummy threads.
115 self.assertFalse(threading.currentThread().ident is None)
116 def f():
117 ident.append(threading.currentThread().ident)
118 done.set()
119 done = threading.Event()
120 ident = []
121 _thread.start_new_thread(f, ())
122 done.wait()
123 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000124 # Kill the "immortal" _DummyThread
125 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000126
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 # run with a small(ish) thread stack size (256kB)
128 def test_various_ops_small_stack(self):
129 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000130 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000131 try:
132 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000133 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000134 raise unittest.SkipTest(
135 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 self.test_various_ops()
137 threading.stack_size(0)
138
139 # run with a large thread stack size (1MB)
140 def test_various_ops_large_stack(self):
141 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000142 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 try:
144 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000145 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000146 raise unittest.SkipTest(
147 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148 self.test_various_ops()
149 threading.stack_size(0)
150
Tim Peters711906e2005-01-08 07:30:42 +0000151 def test_foreign_thread(self):
152 # Check that a "foreign" thread can use the threading module.
153 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000154 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000155 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000156 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000157 mutex.release()
158
159 mutex = threading.Lock()
160 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000161 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000162 # Wait for the thread to finish.
163 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000164 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000165 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000166 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000167
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000168 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
169 # exposed at the Python level. This test relies on ctypes to get at it.
170 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200171 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000172
173 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
174
175 class AsyncExc(Exception):
176 pass
177
178 exception = ctypes.py_object(AsyncExc)
179
Antoine Pitroube4d8092009-10-18 18:27:17 +0000180 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200181 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000182
183 try:
184 result = set_async_exc(ctypes.c_long(tid), exception)
185 # The exception is async, so we might have to keep the VM busy until
186 # it notices.
187 while True:
188 pass
189 except AsyncExc:
190 pass
191 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000192 # This code is unreachable but it reflects the intent. If we wanted
193 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000194 self.fail("AsyncExc not raised")
195 try:
196 self.assertEqual(result, 1) # one thread state modified
197 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000198 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000199 pass
200
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000201 # `worker_started` is set by the thread when it's inside a try/except
202 # block waiting to catch the asynchronously set AsyncExc exception.
203 # `worker_saw_exception` is set by the thread upon catching that
204 # exception.
205 worker_started = threading.Event()
206 worker_saw_exception = threading.Event()
207
208 class Worker(threading.Thread):
209 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200210 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000211 self.finished = False
212
213 try:
214 while True:
215 worker_started.set()
216 time.sleep(0.1)
217 except AsyncExc:
218 self.finished = True
219 worker_saw_exception.set()
220
221 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000222 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000223 t.start()
224 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000225 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000226
227 # Try a thread id that doesn't make sense.
228 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000230 result = set_async_exc(ctypes.c_long(-1), exception)
231 self.assertEqual(result, 0) # no thread states modified
232
233 # Now raise an exception in the worker thread.
234 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000235 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000236 ret = worker_started.wait()
237 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000238 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000240 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000242 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000243 result = set_async_exc(ctypes.c_long(t.id), exception)
244 self.assertEqual(result, 1) # one thread state modified
245 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000246 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000249 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000251 if t.finished:
252 t.join()
253 # else the thread is still running, and we have no way to kill it
254
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000255 def test_limbo_cleanup(self):
256 # Issue 7481: Failure to start thread should cleanup the limbo map.
257 def fail_new_thread(*args):
258 raise threading.ThreadError()
259 _start_new_thread = threading._start_new_thread
260 threading._start_new_thread = fail_new_thread
261 try:
262 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000263 self.assertRaises(threading.ThreadError, t.start)
264 self.assertFalse(
265 t in threading._limbo,
266 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000267 finally:
268 threading._start_new_thread = _start_new_thread
269
Christian Heimes7d2ff882007-11-30 14:35:04 +0000270 def test_finalize_runnning_thread(self):
271 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
272 # very late on python exit: on deallocation of a running thread for
273 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200274 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000275
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200276 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000277 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000279 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000280 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000281 ready.acquire()
282
Christian Heimes7d2ff882007-11-30 14:35:04 +0000283 # Module globals are cleared before __del__ is run
284 # So we save the functions in class dict
285 class C:
286 ensure = ctypes.pythonapi.PyGILState_Ensure
287 release = ctypes.pythonapi.PyGILState_Release
288 def __del__(self):
289 state = self.ensure()
290 self.release(state)
291
292 def waitingThread():
293 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000294 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000295 time.sleep(100)
296
Georg Brandl2067bfd2008-05-25 13:05:15 +0000297 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000298 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000299 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200300 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000301 self.assertEqual(rc, 42)
302
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000303 def test_finalize_with_trace(self):
304 # Issue1733757
305 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200306 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000307 import sys, threading
308
309 # A deadlock-killer, to prevent the
310 # testsuite to hang forever
311 def killer():
312 import os, time
313 time.sleep(2)
314 print('program blocked; aborting')
315 os._exit(2)
316 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000317 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000318 t.start()
319
320 # This is the trace function
321 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000322 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000323 return func
324
325 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200326 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000327
Antoine Pitrou011bd622009-10-20 21:52:47 +0000328 def test_join_nondaemon_on_shutdown(self):
329 # Issue 1722344
330 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200331 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000332 import threading
333 from time import sleep
334
335 def child():
336 sleep(1)
337 # As a non-daemon thread we SHOULD wake up and nothing
338 # should be torn down yet
339 print("Woke up, sleep function is:", sleep)
340
341 threading.Thread(target=child).start()
342 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200343 """)
344 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000345 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200346 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000347
Christian Heimes1af737c2008-01-23 08:24:23 +0000348 def test_enumerate_after_join(self):
349 # Try hard to trigger #1703448: a thread is still returned in
350 # threading.enumerate() after it has been join()ed.
351 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000352 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000353 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000354 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000355 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000356 t = threading.Thread(target=lambda: None)
357 t.start()
358 t.join()
359 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000360 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000361 "#1703448 triggered after %d trials: %s" % (i, l))
362 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000363 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000364
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000365 def test_no_refcycle_through_target(self):
366 class RunSelfFunction(object):
367 def __init__(self, should_raise):
368 # The links in this refcycle from Thread back to self
369 # should be cleaned up when the thread completes.
370 self.should_raise = should_raise
371 self.thread = threading.Thread(target=self._run,
372 args=(self,),
373 kwargs={'yet_another':self})
374 self.thread.start()
375
376 def _run(self, other_ref, yet_another):
377 if self.should_raise:
378 raise SystemExit
379
380 cyclic_object = RunSelfFunction(should_raise=False)
381 weak_cyclic_object = weakref.ref(cyclic_object)
382 cyclic_object.thread.join()
383 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000384 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000385 msg=('%d references still around' %
386 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000387
388 raising_cyclic_object = RunSelfFunction(should_raise=True)
389 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
390 raising_cyclic_object.thread.join()
391 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000392 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000393 msg=('%d references still around' %
394 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000395
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000396 def test_old_threading_api(self):
397 # Just a quick sanity check to make sure the old method names are
398 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000399 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000400 t.isDaemon()
401 t.setDaemon(True)
402 t.getName()
403 t.setName("name")
404 t.isAlive()
405 e = threading.Event()
406 e.isSet()
407 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000408
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000409 def test_repr_daemon(self):
410 t = threading.Thread()
411 self.assertFalse('daemon' in repr(t))
412 t.daemon = True
413 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000414
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000415 def test_deamon_param(self):
416 t = threading.Thread()
417 self.assertFalse(t.daemon)
418 t = threading.Thread(daemon=False)
419 self.assertFalse(t.daemon)
420 t = threading.Thread(daemon=True)
421 self.assertTrue(t.daemon)
422
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200423 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
424 def test_dummy_thread_after_fork(self):
425 # Issue #14308: a dummy thread in the active list doesn't mess up
426 # the after-fork mechanism.
427 code = """if 1:
428 import _thread, threading, os, time
429
430 def background_thread(evt):
431 # Creates and registers the _DummyThread instance
432 threading.current_thread()
433 evt.set()
434 time.sleep(10)
435
436 evt = threading.Event()
437 _thread.start_new_thread(background_thread, (evt,))
438 evt.wait()
439 assert threading.active_count() == 2, threading.active_count()
440 if os.fork() == 0:
441 assert threading.active_count() == 1, threading.active_count()
442 os._exit(0)
443 else:
444 os.wait()
445 """
446 _, out, err = assert_python_ok("-c", code)
447 self.assertEqual(out, b'')
448 self.assertEqual(err, b'')
449
Charles-François Natali9939cc82013-08-30 23:32:53 +0200450 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
451 def test_is_alive_after_fork(self):
452 # Try hard to trigger #18418: is_alive() could sometimes be True on
453 # threads that vanished after a fork.
454 old_interval = sys.getswitchinterval()
455 self.addCleanup(sys.setswitchinterval, old_interval)
456
457 # Make the bug more likely to manifest.
458 sys.setswitchinterval(1e-6)
459
460 for i in range(20):
461 t = threading.Thread(target=lambda: None)
462 t.start()
463 self.addCleanup(t.join)
464 pid = os.fork()
465 if pid == 0:
466 os._exit(1 if t.is_alive() else 0)
467 else:
468 pid, status = os.waitpid(pid, 0)
469 self.assertEqual(0, status)
470
Christian Heimes1af737c2008-01-23 08:24:23 +0000471
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000472class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000473
Victor Stinner26d31862011-07-01 14:26:24 +0200474 # Between fork() and exec(), only async-safe functions are allowed (issues
475 # #12316 and #11870), and fork() from a worker thread is known to trigger
476 # problems with some operating systems (issue #3863): skip problematic tests
477 # on platforms known to behave badly.
478 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
Stefan Krahbfc02452013-01-17 23:36:08 +0100479 'hp-ux11')
Victor Stinner26d31862011-07-01 14:26:24 +0200480
Jesse Nollera8513972008-07-17 16:49:17 +0000481 def _run_and_join(self, script):
482 script = """if 1:
483 import sys, os, time, threading
484
485 # a thread, which waits for the main program to terminate
486 def joiningfunc(mainthread):
487 mainthread.join()
488 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000489 # stdout is fully buffered because not a tty, we have to flush
490 # before exit.
491 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000492 \n""" + script
493
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200494 rc, out, err = assert_python_ok("-c", script)
495 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000496 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000497
498 def test_1_join_on_shutdown(self):
499 # The usual case: on exit, wait for a non-daemon thread
500 script = """if 1:
501 import os
502 t = threading.Thread(target=joiningfunc,
503 args=(threading.current_thread(),))
504 t.start()
505 time.sleep(0.1)
506 print('end of main')
507 """
508 self._run_and_join(script)
509
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000510 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200511 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000512 def test_2_join_in_forked_process(self):
513 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000514 script = """if 1:
515 childpid = os.fork()
516 if childpid != 0:
517 os.waitpid(childpid, 0)
518 sys.exit(0)
519
520 t = threading.Thread(target=joiningfunc,
521 args=(threading.current_thread(),))
522 t.start()
523 print('end of main')
524 """
525 self._run_and_join(script)
526
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000527 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200528 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000529 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000530 # Like the test above, but fork() was called from a worker thread
531 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000532
Jesse Nollera8513972008-07-17 16:49:17 +0000533 script = """if 1:
534 main_thread = threading.current_thread()
535 def worker():
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=(main_thread,))
543 print('end of main')
544 t.start()
545 t.join() # Should not block: main_thread is already stopped
546
547 w = threading.Thread(target=worker)
548 w.start()
549 """
550 self._run_and_join(script)
551
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000552 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200553 rc, out, err = assert_python_ok("-c", script)
554 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000555 self.assertEqual(data, expected_output)
556
557 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200558 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000559 def test_4_joining_across_fork_in_worker_thread(self):
560 # There used to be a possible deadlock when forking from a child
561 # thread. See http://bugs.python.org/issue6643.
562
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000563 # The script takes the following steps:
564 # - The main thread in the parent process starts a new thread and then
565 # tries to join it.
566 # - The join operation acquires the Lock inside the thread's _block
567 # Condition. (See threading.py:Thread.join().)
568 # - We stub out the acquire method on the condition to force it to wait
569 # until the child thread forks. (See LOCK ACQUIRED HERE)
570 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
571 # HERE)
572 # - The main thread of the parent process enters Condition.wait(),
573 # which releases the lock on the child thread.
574 # - The child process returns. Without the necessary fix, when the
575 # main thread of the child process (which used to be the child thread
576 # in the parent process) attempts to exit, it will try to acquire the
577 # lock in the Thread._block Condition object and hang, because the
578 # lock was held across the fork.
579
580 script = """if 1:
581 import os, time, threading
582
583 finish_join = False
584 start_fork = False
585
586 def worker():
587 # Wait until this thread's lock is acquired before forking to
588 # create the deadlock.
589 global finish_join
590 while not start_fork:
591 time.sleep(0.01)
592 # LOCK HELD: Main thread holds lock across this call.
593 childpid = os.fork()
594 finish_join = True
595 if childpid != 0:
596 # Parent process just waits for child.
597 os.waitpid(childpid, 0)
598 # Child process should just return.
599
600 w = threading.Thread(target=worker)
601
602 # Stub out the private condition variable's lock acquire method.
603 # This acquires the lock and then waits until the child has forked
604 # before returning, which will release the lock soon after. If
605 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200606 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000607 # deadlock when it shouldn't.
608 condition = w._block
609 orig_acquire = condition.acquire
610 call_count_lock = threading.Lock()
611 call_count = 0
612 def my_acquire():
613 global call_count
614 global start_fork
615 orig_acquire() # LOCK ACQUIRED HERE
616 start_fork = True
617 if call_count == 0:
618 while not finish_join:
619 time.sleep(0.01) # WORKER THREAD FORKS HERE
620 with call_count_lock:
621 call_count += 1
622 condition.acquire = my_acquire
623
624 w.start()
625 w.join()
626 print('end of main')
627 """
628 self.assertScriptHasOutput(script, "end of main\n")
629
630 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200631 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000632 def test_5_clear_waiter_locks_to_avoid_crash(self):
633 # Check that a spawned thread that forks doesn't segfault on certain
634 # platforms, namely OS X. This used to happen if there was a waiter
635 # lock in the thread's condition variable's waiters list. Even though
636 # we know the lock will be held across the fork, it is not safe to
637 # release locks held across forks on all platforms, so releasing the
638 # waiter lock caused a segfault on OS X. Furthermore, since locks on
639 # OS X are (as of this writing) implemented with a mutex + condition
640 # variable instead of a semaphore, while we know that the Python-level
641 # lock will be acquired, we can't know if the internal mutex will be
642 # acquired at the time of the fork.
643
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000644 script = """if True:
645 import os, time, threading
646
647 start_fork = False
648
649 def worker():
650 # Wait until the main thread has attempted to join this thread
651 # before continuing.
652 while not start_fork:
653 time.sleep(0.01)
654 childpid = os.fork()
655 if childpid != 0:
656 # Parent process just waits for child.
657 (cpid, rc) = os.waitpid(childpid, 0)
658 assert cpid == childpid
659 assert rc == 0
660 print('end of worker thread')
661 else:
662 # Child process should just return.
663 pass
664
665 w = threading.Thread(target=worker)
666
667 # Stub out the private condition variable's _release_save method.
668 # This releases the condition's lock and flips the global that
669 # causes the worker to fork. At this point, the problematic waiter
670 # lock has been acquired once by the waiter and has been put onto
671 # the waiters list.
672 condition = w._block
673 orig_release_save = condition._release_save
674 def my_release_save():
675 global start_fork
676 orig_release_save()
677 # Waiter lock held here, condition lock released.
678 start_fork = True
679 condition._release_save = my_release_save
680
681 w.start()
682 w.join()
683 print('end of main thread')
684 """
685 output = "end of worker thread\nend of main thread\n"
686 self.assertScriptHasOutput(script, output)
687
Charles-François Natali8e6fe642012-03-24 20:36:09 +0100688 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200689 def test_6_daemon_threads(self):
690 # Check that a daemon thread cannot crash the interpreter on shutdown
691 # by manipulating internal structures that are being disposed of in
692 # the main thread.
693 script = """if True:
694 import os
695 import random
696 import sys
697 import time
698 import threading
699
700 thread_has_run = set()
701
702 def random_io():
703 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200704 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200705 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200706 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200707 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200708 null_f.write(stuff)
709 time.sleep(random.random() / 1995)
710 null_f.close()
711 in_f.close()
712 thread_has_run.add(threading.current_thread())
713
714 def main():
715 count = 0
716 for _ in range(40):
717 new_thread = threading.Thread(target=random_io)
718 new_thread.daemon = True
719 new_thread.start()
720 count += 1
721 while len(thread_has_run) < count:
722 time.sleep(0.001)
723 # Trigger process shutdown
724 sys.exit(0)
725
726 main()
727 """
728 rc, out, err = assert_python_ok('-c', script)
729 self.assertFalse(err)
730
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100731 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100732 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100733 def test_reinit_tls_after_fork(self):
734 # Issue #13817: fork() would deadlock in a multithreaded program with
735 # the ad-hoc TLS implementation.
736
737 def do_fork_and_wait():
738 # just fork a child process and wait it
739 pid = os.fork()
740 if pid > 0:
741 os.waitpid(pid, 0)
742 else:
743 os._exit(0)
744
745 # start a bunch of threads that will fork() child processes
746 threads = []
747 for i in range(16):
748 t = threading.Thread(target=do_fork_and_wait)
749 threads.append(t)
750 t.start()
751
752 for t in threads:
753 t.join()
754
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200755 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
756 def test_clear_threads_states_after_fork(self):
757 # Issue #17094: check that threads states are cleared after fork()
758
759 # start a bunch of threads
760 threads = []
761 for i in range(16):
762 t = threading.Thread(target=lambda : time.sleep(0.3))
763 threads.append(t)
764 t.start()
765
766 pid = os.fork()
767 if pid == 0:
768 # check that threads states have been cleared
769 if len(sys._current_frames()) == 1:
770 os._exit(0)
771 else:
772 os._exit(1)
773 else:
774 _, status = os.waitpid(pid, 0)
775 self.assertEqual(0, status)
776
777 for t in threads:
778 t.join()
779
Jesse Nollera8513972008-07-17 16:49:17 +0000780
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200781class SubinterpThreadingTests(BaseTestCase):
782
783 def test_threads_join(self):
784 # Non-daemon threads should be joined at subinterpreter shutdown
785 # (issue #18808)
786 r, w = os.pipe()
787 self.addCleanup(os.close, r)
788 self.addCleanup(os.close, w)
789 code = r"""if 1:
790 import os
791 import threading
792 import time
793
794 def f():
795 # Sleep a bit so that the thread is still running when
796 # Py_EndInterpreter is called.
797 time.sleep(0.05)
798 os.write(%d, b"x")
799 threading.Thread(target=f).start()
800 """ % (w,)
801 ret = _testcapi.run_in_subinterp(code)
802 self.assertEqual(ret, 0)
803 # The thread was joined properly.
804 self.assertEqual(os.read(r, 1), b"x")
805
806 def test_daemon_threads_fatal_error(self):
807 subinterp_code = r"""if 1:
808 import os
809 import threading
810 import time
811
812 def f():
813 # Make sure the daemon thread is still running when
814 # Py_EndInterpreter is called.
815 time.sleep(10)
816 threading.Thread(target=f, daemon=True).start()
817 """
818 script = r"""if 1:
819 import _testcapi
820
821 _testcapi.run_in_subinterp(%r)
822 """ % (subinterp_code,)
823 rc, out, err = assert_python_failure("-c", script)
824 self.assertIn("Fatal Python error: Py_EndInterpreter: "
825 "not the last thread", err.decode())
826
827
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000828class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000829 # A RuntimeError should be raised if Thread.start() is called
830 # multiple times.
831 def test_start_thread_again(self):
832 thread = threading.Thread()
833 thread.start()
834 self.assertRaises(RuntimeError, thread.start)
835
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000836 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000837 current_thread = threading.current_thread()
838 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000839
840 def test_joining_inactive_thread(self):
841 thread = threading.Thread()
842 self.assertRaises(RuntimeError, thread.join)
843
844 def test_daemonize_active_thread(self):
845 thread = threading.Thread()
846 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000847 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000848
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000849 def test_releasing_unacquired_lock(self):
850 lock = threading.Lock()
851 self.assertRaises(RuntimeError, lock.release)
852
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400853 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
854 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700855 def test_recursion_limit(self):
856 # Issue 9670
857 # test that excessive recursion within a non-main thread causes
858 # an exception rather than crashing the interpreter on platforms
859 # like Mac OS X or FreeBSD which have small default stack sizes
860 # for threads
861 script = """if True:
862 import threading
863
864 def recurse():
865 return recurse()
866
867 def outer():
868 try:
869 recurse()
870 except RuntimeError:
871 pass
872
873 w = threading.Thread(target=outer)
874 w.start()
875 w.join()
876 print('end of main thread')
877 """
878 expected_output = "end of main thread\n"
879 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200880 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700881 stdout, stderr = p.communicate()
882 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200883 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700884 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000885
R David Murray19aeb432013-03-30 17:19:38 -0400886class TimerTests(BaseTestCase):
887
888 def setUp(self):
889 BaseTestCase.setUp(self)
890 self.callback_args = []
891 self.callback_event = threading.Event()
892
893 def test_init_immutable_default_args(self):
894 # Issue 17435: constructor defaults were mutable objects, they could be
895 # mutated via the object attributes and affect other Timer objects.
896 timer1 = threading.Timer(0.01, self._callback_spy)
897 timer1.start()
898 self.callback_event.wait()
899 timer1.args.append("blah")
900 timer1.kwargs["foo"] = "bar"
901 self.callback_event.clear()
902 timer2 = threading.Timer(0.01, self._callback_spy)
903 timer2.start()
904 self.callback_event.wait()
905 self.assertEqual(len(self.callback_args), 2)
906 self.assertEqual(self.callback_args, [((), {}), ((), {})])
907
908 def _callback_spy(self, *args, **kwargs):
909 self.callback_args.append((args[:], kwargs.copy()))
910 self.callback_event.set()
911
Antoine Pitrou557934f2009-11-06 22:41:14 +0000912class LockTests(lock_tests.LockTests):
913 locktype = staticmethod(threading.Lock)
914
Antoine Pitrou434736a2009-11-10 18:46:01 +0000915class PyRLockTests(lock_tests.RLockTests):
916 locktype = staticmethod(threading._PyRLock)
917
Charles-François Natali6b671b22012-01-28 11:36:04 +0100918@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +0000919class CRLockTests(lock_tests.RLockTests):
920 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000921
922class EventTests(lock_tests.EventTests):
923 eventtype = staticmethod(threading.Event)
924
925class ConditionAsRLockTests(lock_tests.RLockTests):
926 # An Condition uses an RLock by default and exports its API.
927 locktype = staticmethod(threading.Condition)
928
929class ConditionTests(lock_tests.ConditionTests):
930 condtype = staticmethod(threading.Condition)
931
932class SemaphoreTests(lock_tests.SemaphoreTests):
933 semtype = staticmethod(threading.Semaphore)
934
935class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
936 semtype = staticmethod(threading.BoundedSemaphore)
937
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000938class BarrierTests(lock_tests.BarrierTests):
939 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000940
Tim Peters84d54892005-01-08 06:03:17 +0000941if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -0400942 unittest.main()