blob: 0ebeb39cbdc660516ddf4235187c2f0980d9513d [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
Skip Montanaro4533f602001-08-20 20:28:48 +000020
Antoine Pitrou557934f2009-11-06 22:41:14 +000021from test import lock_tests
22
Tim Peters84d54892005-01-08 06:03:17 +000023# A trivial mutable counter.
24class Counter(object):
25 def __init__(self):
26 self.value = 0
27 def inc(self):
28 self.value += 1
29 def dec(self):
30 self.value -= 1
31 def get(self):
32 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000033
34class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000035 def __init__(self, name, testcase, sema, mutex, nrunning):
36 threading.Thread.__init__(self, name=name)
37 self.testcase = testcase
38 self.sema = sema
39 self.mutex = mutex
40 self.nrunning = nrunning
41
Skip Montanaro4533f602001-08-20 20:28:48 +000042 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000043 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000044 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000045 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000046 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000047
Christian Heimes4fbc72b2008-03-22 00:47:35 +000048 with self.sema:
49 with self.mutex:
50 self.nrunning.inc()
51 if verbose:
52 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000053 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000054
Christian Heimes4fbc72b2008-03-22 00:47:35 +000055 time.sleep(delay)
56 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000057 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000058
Christian Heimes4fbc72b2008-03-22 00:47:35 +000059 with self.mutex:
60 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000061 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000062 if verbose:
63 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000064 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000065
Skip Montanaro4533f602001-08-20 20:28:48 +000066
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000067class BaseTestCase(unittest.TestCase):
68 def setUp(self):
69 self._threads = test.support.threading_setup()
70
71 def tearDown(self):
72 test.support.threading_cleanup(*self._threads)
73 test.support.reap_children()
74
75
76class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000077
Tim Peters84d54892005-01-08 06:03:17 +000078 # Create a bunch of threads, let each do some work, wait until all are
79 # done.
80 def test_various_ops(self):
81 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
82 # times about 1 second per clump).
83 NUMTASKS = 10
84
85 # no more than 3 of the 10 can run at once
86 sema = threading.BoundedSemaphore(value=3)
87 mutex = threading.RLock()
88 numrunning = Counter()
89
90 threads = []
91
92 for i in range(NUMTASKS):
93 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
94 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000095 self.assertEqual(t.ident, None)
96 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000097 t.start()
98
99 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000100 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000101 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +0000102 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000103 self.assertTrue(not t.is_alive())
104 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000105 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000106 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
107 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000108 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000110 self.assertEqual(numrunning.get(), 0)
111
Benjamin Petersond23f8222009-04-05 19:13:16 +0000112 def test_ident_of_no_threading_threads(self):
113 # The ident still must work for the main thread and dummy threads.
114 self.assertFalse(threading.currentThread().ident is None)
115 def f():
116 ident.append(threading.currentThread().ident)
117 done.set()
118 done = threading.Event()
119 ident = []
120 _thread.start_new_thread(f, ())
121 done.wait()
122 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000123 # Kill the "immortal" _DummyThread
124 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000125
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 # run with a small(ish) thread stack size (256kB)
127 def test_various_ops_small_stack(self):
128 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000129 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 try:
131 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000132 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000133 raise unittest.SkipTest(
134 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 self.test_various_ops()
136 threading.stack_size(0)
137
138 # run with a large thread stack size (1MB)
139 def test_various_ops_large_stack(self):
140 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000141 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 try:
143 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000144 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000145 raise unittest.SkipTest(
146 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000147 self.test_various_ops()
148 threading.stack_size(0)
149
Tim Peters711906e2005-01-08 07:30:42 +0000150 def test_foreign_thread(self):
151 # Check that a "foreign" thread can use the threading module.
152 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000153 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000154 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000155 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000156 mutex.release()
157
158 mutex = threading.Lock()
159 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000160 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000161 # Wait for the thread to finish.
162 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000163 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000164 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000165 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000166
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000167 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
168 # exposed at the Python level. This test relies on ctypes to get at it.
169 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200170 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000171
172 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
173
174 class AsyncExc(Exception):
175 pass
176
177 exception = ctypes.py_object(AsyncExc)
178
Antoine Pitroube4d8092009-10-18 18:27:17 +0000179 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200180 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000181
182 try:
183 result = set_async_exc(ctypes.c_long(tid), exception)
184 # The exception is async, so we might have to keep the VM busy until
185 # it notices.
186 while True:
187 pass
188 except AsyncExc:
189 pass
190 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000191 # This code is unreachable but it reflects the intent. If we wanted
192 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000193 self.fail("AsyncExc not raised")
194 try:
195 self.assertEqual(result, 1) # one thread state modified
196 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000197 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000198 pass
199
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000200 # `worker_started` is set by the thread when it's inside a try/except
201 # block waiting to catch the asynchronously set AsyncExc exception.
202 # `worker_saw_exception` is set by the thread upon catching that
203 # exception.
204 worker_started = threading.Event()
205 worker_saw_exception = threading.Event()
206
207 class Worker(threading.Thread):
208 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200209 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000210 self.finished = False
211
212 try:
213 while True:
214 worker_started.set()
215 time.sleep(0.1)
216 except AsyncExc:
217 self.finished = True
218 worker_saw_exception.set()
219
220 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000221 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000222 t.start()
223 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000224 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000225
226 # Try a thread id that doesn't make sense.
227 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000228 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000229 result = set_async_exc(ctypes.c_long(-1), exception)
230 self.assertEqual(result, 0) # no thread states modified
231
232 # Now raise an exception in the worker thread.
233 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000234 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000235 ret = worker_started.wait()
236 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000237 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000238 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000239 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000240 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000241 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000242 result = set_async_exc(ctypes.c_long(t.id), exception)
243 self.assertEqual(result, 1) # one thread state modified
244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000247 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000248 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000250 if t.finished:
251 t.join()
252 # else the thread is still running, and we have no way to kill it
253
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000254 def test_limbo_cleanup(self):
255 # Issue 7481: Failure to start thread should cleanup the limbo map.
256 def fail_new_thread(*args):
257 raise threading.ThreadError()
258 _start_new_thread = threading._start_new_thread
259 threading._start_new_thread = fail_new_thread
260 try:
261 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000262 self.assertRaises(threading.ThreadError, t.start)
263 self.assertFalse(
264 t in threading._limbo,
265 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000266 finally:
267 threading._start_new_thread = _start_new_thread
268
Christian Heimes7d2ff882007-11-30 14:35:04 +0000269 def test_finalize_runnning_thread(self):
270 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
271 # very late on python exit: on deallocation of a running thread for
272 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200273 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000274
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200275 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000276 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000277
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000278 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000279 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000280 ready.acquire()
281
Christian Heimes7d2ff882007-11-30 14:35:04 +0000282 # Module globals are cleared before __del__ is run
283 # So we save the functions in class dict
284 class C:
285 ensure = ctypes.pythonapi.PyGILState_Ensure
286 release = ctypes.pythonapi.PyGILState_Release
287 def __del__(self):
288 state = self.ensure()
289 self.release(state)
290
291 def waitingThread():
292 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000293 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000294 time.sleep(100)
295
Georg Brandl2067bfd2008-05-25 13:05:15 +0000296 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000297 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000298 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200299 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000300 self.assertEqual(rc, 42)
301
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000302 def test_finalize_with_trace(self):
303 # Issue1733757
304 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200305 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000306 import sys, threading
307
308 # A deadlock-killer, to prevent the
309 # testsuite to hang forever
310 def killer():
311 import os, time
312 time.sleep(2)
313 print('program blocked; aborting')
314 os._exit(2)
315 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000316 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000317 t.start()
318
319 # This is the trace function
320 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000321 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000322 return func
323
324 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200325 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000326
Antoine Pitrou011bd622009-10-20 21:52:47 +0000327 def test_join_nondaemon_on_shutdown(self):
328 # Issue 1722344
329 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200330 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000331 import threading
332 from time import sleep
333
334 def child():
335 sleep(1)
336 # As a non-daemon thread we SHOULD wake up and nothing
337 # should be torn down yet
338 print("Woke up, sleep function is:", sleep)
339
340 threading.Thread(target=child).start()
341 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200342 """)
343 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000344 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200345 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000346
Christian Heimes1af737c2008-01-23 08:24:23 +0000347 def test_enumerate_after_join(self):
348 # Try hard to trigger #1703448: a thread is still returned in
349 # threading.enumerate() after it has been join()ed.
350 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000351 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000352 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000353 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000354 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000355 t = threading.Thread(target=lambda: None)
356 t.start()
357 t.join()
358 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000359 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000360 "#1703448 triggered after %d trials: %s" % (i, l))
361 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000362 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000363
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000364 def test_no_refcycle_through_target(self):
365 class RunSelfFunction(object):
366 def __init__(self, should_raise):
367 # The links in this refcycle from Thread back to self
368 # should be cleaned up when the thread completes.
369 self.should_raise = should_raise
370 self.thread = threading.Thread(target=self._run,
371 args=(self,),
372 kwargs={'yet_another':self})
373 self.thread.start()
374
375 def _run(self, other_ref, yet_another):
376 if self.should_raise:
377 raise SystemExit
378
379 cyclic_object = RunSelfFunction(should_raise=False)
380 weak_cyclic_object = weakref.ref(cyclic_object)
381 cyclic_object.thread.join()
382 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000383 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000384 msg=('%d references still around' %
385 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000386
387 raising_cyclic_object = RunSelfFunction(should_raise=True)
388 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
389 raising_cyclic_object.thread.join()
390 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000391 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000392 msg=('%d references still around' %
393 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000394
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000395 def test_old_threading_api(self):
396 # Just a quick sanity check to make sure the old method names are
397 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000398 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000399 t.isDaemon()
400 t.setDaemon(True)
401 t.getName()
402 t.setName("name")
403 t.isAlive()
404 e = threading.Event()
405 e.isSet()
406 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000407
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000408 def test_repr_daemon(self):
409 t = threading.Thread()
410 self.assertFalse('daemon' in repr(t))
411 t.daemon = True
412 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000413
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000414 def test_deamon_param(self):
415 t = threading.Thread()
416 self.assertFalse(t.daemon)
417 t = threading.Thread(daemon=False)
418 self.assertFalse(t.daemon)
419 t = threading.Thread(daemon=True)
420 self.assertTrue(t.daemon)
421
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200422 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
423 def test_dummy_thread_after_fork(self):
424 # Issue #14308: a dummy thread in the active list doesn't mess up
425 # the after-fork mechanism.
426 code = """if 1:
427 import _thread, threading, os, time
428
429 def background_thread(evt):
430 # Creates and registers the _DummyThread instance
431 threading.current_thread()
432 evt.set()
433 time.sleep(10)
434
435 evt = threading.Event()
436 _thread.start_new_thread(background_thread, (evt,))
437 evt.wait()
438 assert threading.active_count() == 2, threading.active_count()
439 if os.fork() == 0:
440 assert threading.active_count() == 1, threading.active_count()
441 os._exit(0)
442 else:
443 os.wait()
444 """
445 _, out, err = assert_python_ok("-c", code)
446 self.assertEqual(out, b'')
447 self.assertEqual(err, b'')
448
Charles-François Natali9939cc82013-08-30 23:32:53 +0200449 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
450 def test_is_alive_after_fork(self):
451 # Try hard to trigger #18418: is_alive() could sometimes be True on
452 # threads that vanished after a fork.
453 old_interval = sys.getswitchinterval()
454 self.addCleanup(sys.setswitchinterval, old_interval)
455
456 # Make the bug more likely to manifest.
457 sys.setswitchinterval(1e-6)
458
459 for i in range(20):
460 t = threading.Thread(target=lambda: None)
461 t.start()
462 self.addCleanup(t.join)
463 pid = os.fork()
464 if pid == 0:
465 os._exit(1 if t.is_alive() else 0)
466 else:
467 pid, status = os.waitpid(pid, 0)
468 self.assertEqual(0, status)
469
Christian Heimes1af737c2008-01-23 08:24:23 +0000470
Tim Peters7634e1c2013-10-08 20:55:51 -0500471 def test_BoundedSemaphore_limit(self):
472 # BoundedSemaphore should raise ValueError if released too often.
473 for limit in range(1, 10):
474 bs = threading.BoundedSemaphore(limit)
475 threads = [threading.Thread(target=bs.acquire)
476 for _ in range(limit)]
477 for t in threads:
478 t.start()
479 for t in threads:
480 t.join()
481 threads = [threading.Thread(target=bs.release)
482 for _ in range(limit)]
483 for t in threads:
484 t.start()
485 for t in threads:
486 t.join()
487 self.assertRaises(ValueError, bs.release)
488
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000489class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000490
Victor Stinner26d31862011-07-01 14:26:24 +0200491 # Between fork() and exec(), only async-safe functions are allowed (issues
492 # #12316 and #11870), and fork() from a worker thread is known to trigger
493 # problems with some operating systems (issue #3863): skip problematic tests
494 # on platforms known to behave badly.
495 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
Stefan Krahfc4aa762013-01-17 23:29:54 +0100496 'os2emx', 'hp-ux11')
Victor Stinner26d31862011-07-01 14:26:24 +0200497
Jesse Nollera8513972008-07-17 16:49:17 +0000498 def _run_and_join(self, script):
499 script = """if 1:
500 import sys, os, time, threading
501
502 # a thread, which waits for the main program to terminate
503 def joiningfunc(mainthread):
504 mainthread.join()
505 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000506 # stdout is fully buffered because not a tty, we have to flush
507 # before exit.
508 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000509 \n""" + script
510
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200511 rc, out, err = assert_python_ok("-c", script)
512 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000513 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000514
515 def test_1_join_on_shutdown(self):
516 # The usual case: on exit, wait for a non-daemon thread
517 script = """if 1:
518 import os
519 t = threading.Thread(target=joiningfunc,
520 args=(threading.current_thread(),))
521 t.start()
522 time.sleep(0.1)
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")
Jesse Nollera8513972008-07-17 16:49:17 +0000529 def test_2_join_in_forked_process(self):
530 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000531 script = """if 1:
532 childpid = os.fork()
533 if childpid != 0:
534 os.waitpid(childpid, 0)
535 sys.exit(0)
536
537 t = threading.Thread(target=joiningfunc,
538 args=(threading.current_thread(),))
539 t.start()
540 print('end of main')
541 """
542 self._run_and_join(script)
543
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000544 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200545 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000546 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000547 # Like the test above, but fork() was called from a worker thread
548 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000549
Jesse Nollera8513972008-07-17 16:49:17 +0000550 script = """if 1:
551 main_thread = threading.current_thread()
552 def worker():
553 childpid = os.fork()
554 if childpid != 0:
555 os.waitpid(childpid, 0)
556 sys.exit(0)
557
558 t = threading.Thread(target=joiningfunc,
559 args=(main_thread,))
560 print('end of main')
561 t.start()
562 t.join() # Should not block: main_thread is already stopped
563
564 w = threading.Thread(target=worker)
565 w.start()
566 """
567 self._run_and_join(script)
568
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000569 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200570 rc, out, err = assert_python_ok("-c", script)
571 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000572 self.assertEqual(data, expected_output)
573
574 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200575 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000576 def test_4_joining_across_fork_in_worker_thread(self):
577 # There used to be a possible deadlock when forking from a child
578 # thread. See http://bugs.python.org/issue6643.
579
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000580 # The script takes the following steps:
581 # - The main thread in the parent process starts a new thread and then
582 # tries to join it.
583 # - The join operation acquires the Lock inside the thread's _block
584 # Condition. (See threading.py:Thread.join().)
585 # - We stub out the acquire method on the condition to force it to wait
586 # until the child thread forks. (See LOCK ACQUIRED HERE)
587 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
588 # HERE)
589 # - The main thread of the parent process enters Condition.wait(),
590 # which releases the lock on the child thread.
591 # - The child process returns. Without the necessary fix, when the
592 # main thread of the child process (which used to be the child thread
593 # in the parent process) attempts to exit, it will try to acquire the
594 # lock in the Thread._block Condition object and hang, because the
595 # lock was held across the fork.
596
597 script = """if 1:
598 import os, time, threading
599
600 finish_join = False
601 start_fork = False
602
603 def worker():
604 # Wait until this thread's lock is acquired before forking to
605 # create the deadlock.
606 global finish_join
607 while not start_fork:
608 time.sleep(0.01)
609 # LOCK HELD: Main thread holds lock across this call.
610 childpid = os.fork()
611 finish_join = True
612 if childpid != 0:
613 # Parent process just waits for child.
614 os.waitpid(childpid, 0)
615 # Child process should just return.
616
617 w = threading.Thread(target=worker)
618
619 # Stub out the private condition variable's lock acquire method.
620 # This acquires the lock and then waits until the child has forked
621 # before returning, which will release the lock soon after. If
622 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200623 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000624 # deadlock when it shouldn't.
625 condition = w._block
626 orig_acquire = condition.acquire
627 call_count_lock = threading.Lock()
628 call_count = 0
629 def my_acquire():
630 global call_count
631 global start_fork
632 orig_acquire() # LOCK ACQUIRED HERE
633 start_fork = True
634 if call_count == 0:
635 while not finish_join:
636 time.sleep(0.01) # WORKER THREAD FORKS HERE
637 with call_count_lock:
638 call_count += 1
639 condition.acquire = my_acquire
640
641 w.start()
642 w.join()
643 print('end of main')
644 """
645 self.assertScriptHasOutput(script, "end of main\n")
646
647 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200648 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000649 def test_5_clear_waiter_locks_to_avoid_crash(self):
650 # Check that a spawned thread that forks doesn't segfault on certain
651 # platforms, namely OS X. This used to happen if there was a waiter
652 # lock in the thread's condition variable's waiters list. Even though
653 # we know the lock will be held across the fork, it is not safe to
654 # release locks held across forks on all platforms, so releasing the
655 # waiter lock caused a segfault on OS X. Furthermore, since locks on
656 # OS X are (as of this writing) implemented with a mutex + condition
657 # variable instead of a semaphore, while we know that the Python-level
658 # lock will be acquired, we can't know if the internal mutex will be
659 # acquired at the time of the fork.
660
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000661 script = """if True:
662 import os, time, threading
663
664 start_fork = False
665
666 def worker():
667 # Wait until the main thread has attempted to join this thread
668 # before continuing.
669 while not start_fork:
670 time.sleep(0.01)
671 childpid = os.fork()
672 if childpid != 0:
673 # Parent process just waits for child.
674 (cpid, rc) = os.waitpid(childpid, 0)
675 assert cpid == childpid
676 assert rc == 0
677 print('end of worker thread')
678 else:
679 # Child process should just return.
680 pass
681
682 w = threading.Thread(target=worker)
683
684 # Stub out the private condition variable's _release_save method.
685 # This releases the condition's lock and flips the global that
686 # causes the worker to fork. At this point, the problematic waiter
687 # lock has been acquired once by the waiter and has been put onto
688 # the waiters list.
689 condition = w._block
690 orig_release_save = condition._release_save
691 def my_release_save():
692 global start_fork
693 orig_release_save()
694 # Waiter lock held here, condition lock released.
695 start_fork = True
696 condition._release_save = my_release_save
697
698 w.start()
699 w.join()
700 print('end of main thread')
701 """
702 output = "end of worker thread\nend of main thread\n"
703 self.assertScriptHasOutput(script, output)
704
Charles-François Natali8e6fe642012-03-24 20:36:09 +0100705 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200706 def test_6_daemon_threads(self):
707 # Check that a daemon thread cannot crash the interpreter on shutdown
708 # by manipulating internal structures that are being disposed of in
709 # the main thread.
710 script = """if True:
711 import os
712 import random
713 import sys
714 import time
715 import threading
716
717 thread_has_run = set()
718
719 def random_io():
720 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200721 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200722 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200723 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200724 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200725 null_f.write(stuff)
726 time.sleep(random.random() / 1995)
727 null_f.close()
728 in_f.close()
729 thread_has_run.add(threading.current_thread())
730
731 def main():
732 count = 0
733 for _ in range(40):
734 new_thread = threading.Thread(target=random_io)
735 new_thread.daemon = True
736 new_thread.start()
737 count += 1
738 while len(thread_has_run) < count:
739 time.sleep(0.001)
740 # Trigger process shutdown
741 sys.exit(0)
742
743 main()
744 """
745 rc, out, err = assert_python_ok('-c', script)
746 self.assertFalse(err)
747
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100748 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100749 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100750 def test_reinit_tls_after_fork(self):
751 # Issue #13817: fork() would deadlock in a multithreaded program with
752 # the ad-hoc TLS implementation.
753
754 def do_fork_and_wait():
755 # just fork a child process and wait it
756 pid = os.fork()
757 if pid > 0:
758 os.waitpid(pid, 0)
759 else:
760 os._exit(0)
761
762 # start a bunch of threads that will fork() child processes
763 threads = []
764 for i in range(16):
765 t = threading.Thread(target=do_fork_and_wait)
766 threads.append(t)
767 t.start()
768
769 for t in threads:
770 t.join()
771
Jesse Nollera8513972008-07-17 16:49:17 +0000772
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000773class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000774 # A RuntimeError should be raised if Thread.start() is called
775 # multiple times.
776 def test_start_thread_again(self):
777 thread = threading.Thread()
778 thread.start()
779 self.assertRaises(RuntimeError, thread.start)
780
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000781 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000782 current_thread = threading.current_thread()
783 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000784
785 def test_joining_inactive_thread(self):
786 thread = threading.Thread()
787 self.assertRaises(RuntimeError, thread.join)
788
789 def test_daemonize_active_thread(self):
790 thread = threading.Thread()
791 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000792 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000793
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000794 def test_releasing_unacquired_lock(self):
795 lock = threading.Lock()
796 self.assertRaises(RuntimeError, lock.release)
797
Łukasz Langa20ea96f2013-04-24 01:29:26 +0200798 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
799 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700800 def test_recursion_limit(self):
801 # Issue 9670
802 # test that excessive recursion within a non-main thread causes
803 # an exception rather than crashing the interpreter on platforms
804 # like Mac OS X or FreeBSD which have small default stack sizes
805 # for threads
806 script = """if True:
807 import threading
808
809 def recurse():
810 return recurse()
811
812 def outer():
813 try:
814 recurse()
815 except RuntimeError:
816 pass
817
818 w = threading.Thread(target=outer)
819 w.start()
820 w.join()
821 print('end of main thread')
822 """
823 expected_output = "end of main thread\n"
824 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200825 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700826 stdout, stderr = p.communicate()
827 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200828 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700829 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000830
R David Murray19aeb432013-03-30 17:19:38 -0400831class TimerTests(BaseTestCase):
832
833 def setUp(self):
834 BaseTestCase.setUp(self)
835 self.callback_args = []
836 self.callback_event = threading.Event()
837
838 def test_init_immutable_default_args(self):
839 # Issue 17435: constructor defaults were mutable objects, they could be
840 # mutated via the object attributes and affect other Timer objects.
841 timer1 = threading.Timer(0.01, self._callback_spy)
842 timer1.start()
843 self.callback_event.wait()
844 timer1.args.append("blah")
845 timer1.kwargs["foo"] = "bar"
846 self.callback_event.clear()
847 timer2 = threading.Timer(0.01, self._callback_spy)
848 timer2.start()
849 self.callback_event.wait()
850 self.assertEqual(len(self.callback_args), 2)
851 self.assertEqual(self.callback_args, [((), {}), ((), {})])
852
853 def _callback_spy(self, *args, **kwargs):
854 self.callback_args.append((args[:], kwargs.copy()))
855 self.callback_event.set()
856
Antoine Pitrou557934f2009-11-06 22:41:14 +0000857class LockTests(lock_tests.LockTests):
858 locktype = staticmethod(threading.Lock)
859
Antoine Pitrou434736a2009-11-10 18:46:01 +0000860class PyRLockTests(lock_tests.RLockTests):
861 locktype = staticmethod(threading._PyRLock)
862
Charles-François Natali6b671b22012-01-28 11:36:04 +0100863@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +0000864class CRLockTests(lock_tests.RLockTests):
865 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000866
867class EventTests(lock_tests.EventTests):
868 eventtype = staticmethod(threading.Event)
869
870class ConditionAsRLockTests(lock_tests.RLockTests):
871 # An Condition uses an RLock by default and exports its API.
872 locktype = staticmethod(threading.Condition)
873
874class ConditionTests(lock_tests.ConditionTests):
875 condtype = staticmethod(threading.Condition)
876
877class SemaphoreTests(lock_tests.SemaphoreTests):
878 semtype = staticmethod(threading.Semaphore)
879
880class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
881 semtype = staticmethod(threading.BoundedSemaphore)
882
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000883class BarrierTests(lock_tests.BarrierTests):
884 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000885
Tim Peters84d54892005-01-08 06:03:17 +0000886if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -0400887 unittest.main()