blob: 7ce5af43ad713779d3e580c91dcfbaefb61a49ca [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003import test.support
Antoine Pitrouc4d78642011-05-05 20:17:32 +02004from test.support import verbose, strip_python_stderr, import_module
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Georg Brandl0c77a822008-06-10 16:37:50 +00006import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007import sys
Antoine Pitrouc4d78642011-05-05 20:17:32 +02008_thread = import_module('_thread')
9threading = import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000012import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000013import os
Antoine Pitrouc4d78642011-05-05 20:17:32 +020014from test.script_helper import assert_python_ok, assert_python_failure
Gregory P. Smith4b129d22011-01-04 00:51:50 +000015import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000016
Antoine Pitrou557934f2009-11-06 22:41:14 +000017from test import lock_tests
18
Tim Peters84d54892005-01-08 06:03:17 +000019# A trivial mutable counter.
20class Counter(object):
21 def __init__(self):
22 self.value = 0
23 def inc(self):
24 self.value += 1
25 def dec(self):
26 self.value -= 1
27 def get(self):
28 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000029
30class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000031 def __init__(self, name, testcase, sema, mutex, nrunning):
32 threading.Thread.__init__(self, name=name)
33 self.testcase = testcase
34 self.sema = sema
35 self.mutex = mutex
36 self.nrunning = nrunning
37
Skip Montanaro4533f602001-08-20 20:28:48 +000038 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000039 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000040 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000041 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000042 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000043
Christian Heimes4fbc72b2008-03-22 00:47:35 +000044 with self.sema:
45 with self.mutex:
46 self.nrunning.inc()
47 if verbose:
48 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000049 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000050
Christian Heimes4fbc72b2008-03-22 00:47:35 +000051 time.sleep(delay)
52 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000053 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000054
Christian Heimes4fbc72b2008-03-22 00:47:35 +000055 with self.mutex:
56 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000057 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 if verbose:
59 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000060 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000061
Skip Montanaro4533f602001-08-20 20:28:48 +000062
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000063class BaseTestCase(unittest.TestCase):
64 def setUp(self):
65 self._threads = test.support.threading_setup()
66
67 def tearDown(self):
68 test.support.threading_cleanup(*self._threads)
69 test.support.reap_children()
70
71
72class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000073
Tim Peters84d54892005-01-08 06:03:17 +000074 # Create a bunch of threads, let each do some work, wait until all are
75 # done.
76 def test_various_ops(self):
77 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
78 # times about 1 second per clump).
79 NUMTASKS = 10
80
81 # no more than 3 of the 10 can run at once
82 sema = threading.BoundedSemaphore(value=3)
83 mutex = threading.RLock()
84 numrunning = Counter()
85
86 threads = []
87
88 for i in range(NUMTASKS):
89 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
90 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 self.assertEqual(t.ident, None)
92 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000093 t.start()
94
95 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000096 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000097 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000098 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertTrue(not t.is_alive())
100 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000101 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000102 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
103 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000104 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000106 self.assertEqual(numrunning.get(), 0)
107
Benjamin Petersond23f8222009-04-05 19:13:16 +0000108 def test_ident_of_no_threading_threads(self):
109 # The ident still must work for the main thread and dummy threads.
110 self.assertFalse(threading.currentThread().ident is None)
111 def f():
112 ident.append(threading.currentThread().ident)
113 done.set()
114 done = threading.Event()
115 ident = []
116 _thread.start_new_thread(f, ())
117 done.wait()
118 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000119 # Kill the "immortal" _DummyThread
120 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000121
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 # run with a small(ish) thread stack size (256kB)
123 def test_various_ops_small_stack(self):
124 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000125 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 try:
127 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000128 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000129 raise unittest.SkipTest(
130 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000131 self.test_various_ops()
132 threading.stack_size(0)
133
134 # run with a large thread stack size (1MB)
135 def test_various_ops_large_stack(self):
136 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000137 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 try:
139 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000140 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000141 raise unittest.SkipTest(
142 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 self.test_various_ops()
144 threading.stack_size(0)
145
Tim Peters711906e2005-01-08 07:30:42 +0000146 def test_foreign_thread(self):
147 # Check that a "foreign" thread can use the threading module.
148 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000149 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000150 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000151 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000152 mutex.release()
153
154 mutex = threading.Lock()
155 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000156 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000157 # Wait for the thread to finish.
158 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000159 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000160 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000161 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000162
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000163 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
164 # exposed at the Python level. This test relies on ctypes to get at it.
165 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200166 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000167
168 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
169
170 class AsyncExc(Exception):
171 pass
172
173 exception = ctypes.py_object(AsyncExc)
174
Antoine Pitroube4d8092009-10-18 18:27:17 +0000175 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200176 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000177
178 try:
179 result = set_async_exc(ctypes.c_long(tid), exception)
180 # The exception is async, so we might have to keep the VM busy until
181 # it notices.
182 while True:
183 pass
184 except AsyncExc:
185 pass
186 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000187 # This code is unreachable but it reflects the intent. If we wanted
188 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000189 self.fail("AsyncExc not raised")
190 try:
191 self.assertEqual(result, 1) # one thread state modified
192 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000193 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000194 pass
195
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000196 # `worker_started` is set by the thread when it's inside a try/except
197 # block waiting to catch the asynchronously set AsyncExc exception.
198 # `worker_saw_exception` is set by the thread upon catching that
199 # exception.
200 worker_started = threading.Event()
201 worker_saw_exception = threading.Event()
202
203 class Worker(threading.Thread):
204 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200205 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000206 self.finished = False
207
208 try:
209 while True:
210 worker_started.set()
211 time.sleep(0.1)
212 except AsyncExc:
213 self.finished = True
214 worker_saw_exception.set()
215
216 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000217 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 t.start()
219 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000220 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221
222 # Try a thread id that doesn't make sense.
223 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000224 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000225 result = set_async_exc(ctypes.c_long(-1), exception)
226 self.assertEqual(result, 0) # no thread states modified
227
228 # Now raise an exception in the worker thread.
229 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000230 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000231 ret = worker_started.wait()
232 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000234 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000237 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000238 result = set_async_exc(ctypes.c_long(t.id), exception)
239 self.assertEqual(result, 1) # one thread state modified
240 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000241 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000242 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000243 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 if t.finished:
247 t.join()
248 # else the thread is still running, and we have no way to kill it
249
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000250 def test_limbo_cleanup(self):
251 # Issue 7481: Failure to start thread should cleanup the limbo map.
252 def fail_new_thread(*args):
253 raise threading.ThreadError()
254 _start_new_thread = threading._start_new_thread
255 threading._start_new_thread = fail_new_thread
256 try:
257 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000258 self.assertRaises(threading.ThreadError, t.start)
259 self.assertFalse(
260 t in threading._limbo,
261 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000262 finally:
263 threading._start_new_thread = _start_new_thread
264
Christian Heimes7d2ff882007-11-30 14:35:04 +0000265 def test_finalize_runnning_thread(self):
266 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
267 # very late on python exit: on deallocation of a running thread for
268 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200269 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000270
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200271 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000272 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000273
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000274 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000275 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000276 ready.acquire()
277
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278 # Module globals are cleared before __del__ is run
279 # So we save the functions in class dict
280 class C:
281 ensure = ctypes.pythonapi.PyGILState_Ensure
282 release = ctypes.pythonapi.PyGILState_Release
283 def __del__(self):
284 state = self.ensure()
285 self.release(state)
286
287 def waitingThread():
288 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000289 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000290 time.sleep(100)
291
Georg Brandl2067bfd2008-05-25 13:05:15 +0000292 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000293 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000294 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200295 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296 self.assertEqual(rc, 42)
297
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000298 def test_finalize_with_trace(self):
299 # Issue1733757
300 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200301 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000302 import sys, threading
303
304 # A deadlock-killer, to prevent the
305 # testsuite to hang forever
306 def killer():
307 import os, time
308 time.sleep(2)
309 print('program blocked; aborting')
310 os._exit(2)
311 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000312 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000313 t.start()
314
315 # This is the trace function
316 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000317 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000318 return func
319
320 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200321 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000322
Antoine Pitrou011bd622009-10-20 21:52:47 +0000323 def test_join_nondaemon_on_shutdown(self):
324 # Issue 1722344
325 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200326 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000327 import threading
328 from time import sleep
329
330 def child():
331 sleep(1)
332 # As a non-daemon thread we SHOULD wake up and nothing
333 # should be torn down yet
334 print("Woke up, sleep function is:", sleep)
335
336 threading.Thread(target=child).start()
337 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200338 """)
339 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000340 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200341 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000342
Christian Heimes1af737c2008-01-23 08:24:23 +0000343 def test_enumerate_after_join(self):
344 # Try hard to trigger #1703448: a thread is still returned in
345 # threading.enumerate() after it has been join()ed.
346 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000347 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000348 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000349 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000350 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000351 t = threading.Thread(target=lambda: None)
352 t.start()
353 t.join()
354 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000355 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000356 "#1703448 triggered after %d trials: %s" % (i, l))
357 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000358 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000359
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000360 def test_no_refcycle_through_target(self):
361 class RunSelfFunction(object):
362 def __init__(self, should_raise):
363 # The links in this refcycle from Thread back to self
364 # should be cleaned up when the thread completes.
365 self.should_raise = should_raise
366 self.thread = threading.Thread(target=self._run,
367 args=(self,),
368 kwargs={'yet_another':self})
369 self.thread.start()
370
371 def _run(self, other_ref, yet_another):
372 if self.should_raise:
373 raise SystemExit
374
375 cyclic_object = RunSelfFunction(should_raise=False)
376 weak_cyclic_object = weakref.ref(cyclic_object)
377 cyclic_object.thread.join()
378 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000379 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000380 msg=('%d references still around' %
381 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000382
383 raising_cyclic_object = RunSelfFunction(should_raise=True)
384 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
385 raising_cyclic_object.thread.join()
386 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000387 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000388 msg=('%d references still around' %
389 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000390
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000391 def test_old_threading_api(self):
392 # Just a quick sanity check to make sure the old method names are
393 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000394 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000395 t.isDaemon()
396 t.setDaemon(True)
397 t.getName()
398 t.setName("name")
399 t.isAlive()
400 e = threading.Event()
401 e.isSet()
402 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000403
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000404 def test_repr_daemon(self):
405 t = threading.Thread()
406 self.assertFalse('daemon' in repr(t))
407 t.daemon = True
408 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000409
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000410 def test_deamon_param(self):
411 t = threading.Thread()
412 self.assertFalse(t.daemon)
413 t = threading.Thread(daemon=False)
414 self.assertFalse(t.daemon)
415 t = threading.Thread(daemon=True)
416 self.assertTrue(t.daemon)
417
Christian Heimes1af737c2008-01-23 08:24:23 +0000418
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000419class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000420
Victor Stinner26d31862011-07-01 14:26:24 +0200421 # Between fork() and exec(), only async-safe functions are allowed (issues
422 # #12316 and #11870), and fork() from a worker thread is known to trigger
423 # problems with some operating systems (issue #3863): skip problematic tests
424 # on platforms known to behave badly.
425 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
426 'os2emx')
427
Jesse Nollera8513972008-07-17 16:49:17 +0000428 def _run_and_join(self, script):
429 script = """if 1:
430 import sys, os, time, threading
431
432 # a thread, which waits for the main program to terminate
433 def joiningfunc(mainthread):
434 mainthread.join()
435 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000436 # stdout is fully buffered because not a tty, we have to flush
437 # before exit.
438 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000439 \n""" + script
440
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200441 rc, out, err = assert_python_ok("-c", script)
442 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000443 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000444
445 def test_1_join_on_shutdown(self):
446 # The usual case: on exit, wait for a non-daemon thread
447 script = """if 1:
448 import os
449 t = threading.Thread(target=joiningfunc,
450 args=(threading.current_thread(),))
451 t.start()
452 time.sleep(0.1)
453 print('end of main')
454 """
455 self._run_and_join(script)
456
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000457 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200458 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000459 def test_2_join_in_forked_process(self):
460 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000461 script = """if 1:
462 childpid = os.fork()
463 if childpid != 0:
464 os.waitpid(childpid, 0)
465 sys.exit(0)
466
467 t = threading.Thread(target=joiningfunc,
468 args=(threading.current_thread(),))
469 t.start()
470 print('end of main')
471 """
472 self._run_and_join(script)
473
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000474 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200475 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000476 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000477 # Like the test above, but fork() was called from a worker thread
478 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000479
Jesse Nollera8513972008-07-17 16:49:17 +0000480 script = """if 1:
481 main_thread = threading.current_thread()
482 def worker():
483 childpid = os.fork()
484 if childpid != 0:
485 os.waitpid(childpid, 0)
486 sys.exit(0)
487
488 t = threading.Thread(target=joiningfunc,
489 args=(main_thread,))
490 print('end of main')
491 t.start()
492 t.join() # Should not block: main_thread is already stopped
493
494 w = threading.Thread(target=worker)
495 w.start()
496 """
497 self._run_and_join(script)
498
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000499 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200500 rc, out, err = assert_python_ok("-c", script)
501 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000502 self.assertEqual(data, expected_output)
503
504 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200505 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000506 def test_4_joining_across_fork_in_worker_thread(self):
507 # There used to be a possible deadlock when forking from a child
508 # thread. See http://bugs.python.org/issue6643.
509
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000510 # The script takes the following steps:
511 # - The main thread in the parent process starts a new thread and then
512 # tries to join it.
513 # - The join operation acquires the Lock inside the thread's _block
514 # Condition. (See threading.py:Thread.join().)
515 # - We stub out the acquire method on the condition to force it to wait
516 # until the child thread forks. (See LOCK ACQUIRED HERE)
517 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
518 # HERE)
519 # - The main thread of the parent process enters Condition.wait(),
520 # which releases the lock on the child thread.
521 # - The child process returns. Without the necessary fix, when the
522 # main thread of the child process (which used to be the child thread
523 # in the parent process) attempts to exit, it will try to acquire the
524 # lock in the Thread._block Condition object and hang, because the
525 # lock was held across the fork.
526
527 script = """if 1:
528 import os, time, threading
529
530 finish_join = False
531 start_fork = False
532
533 def worker():
534 # Wait until this thread's lock is acquired before forking to
535 # create the deadlock.
536 global finish_join
537 while not start_fork:
538 time.sleep(0.01)
539 # LOCK HELD: Main thread holds lock across this call.
540 childpid = os.fork()
541 finish_join = True
542 if childpid != 0:
543 # Parent process just waits for child.
544 os.waitpid(childpid, 0)
545 # Child process should just return.
546
547 w = threading.Thread(target=worker)
548
549 # Stub out the private condition variable's lock acquire method.
550 # This acquires the lock and then waits until the child has forked
551 # before returning, which will release the lock soon after. If
552 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200553 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000554 # deadlock when it shouldn't.
555 condition = w._block
556 orig_acquire = condition.acquire
557 call_count_lock = threading.Lock()
558 call_count = 0
559 def my_acquire():
560 global call_count
561 global start_fork
562 orig_acquire() # LOCK ACQUIRED HERE
563 start_fork = True
564 if call_count == 0:
565 while not finish_join:
566 time.sleep(0.01) # WORKER THREAD FORKS HERE
567 with call_count_lock:
568 call_count += 1
569 condition.acquire = my_acquire
570
571 w.start()
572 w.join()
573 print('end of main')
574 """
575 self.assertScriptHasOutput(script, "end of main\n")
576
577 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200578 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000579 def test_5_clear_waiter_locks_to_avoid_crash(self):
580 # Check that a spawned thread that forks doesn't segfault on certain
581 # platforms, namely OS X. This used to happen if there was a waiter
582 # lock in the thread's condition variable's waiters list. Even though
583 # we know the lock will be held across the fork, it is not safe to
584 # release locks held across forks on all platforms, so releasing the
585 # waiter lock caused a segfault on OS X. Furthermore, since locks on
586 # OS X are (as of this writing) implemented with a mutex + condition
587 # variable instead of a semaphore, while we know that the Python-level
588 # lock will be acquired, we can't know if the internal mutex will be
589 # acquired at the time of the fork.
590
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000591 script = """if True:
592 import os, time, threading
593
594 start_fork = False
595
596 def worker():
597 # Wait until the main thread has attempted to join this thread
598 # before continuing.
599 while not start_fork:
600 time.sleep(0.01)
601 childpid = os.fork()
602 if childpid != 0:
603 # Parent process just waits for child.
604 (cpid, rc) = os.waitpid(childpid, 0)
605 assert cpid == childpid
606 assert rc == 0
607 print('end of worker thread')
608 else:
609 # Child process should just return.
610 pass
611
612 w = threading.Thread(target=worker)
613
614 # Stub out the private condition variable's _release_save method.
615 # This releases the condition's lock and flips the global that
616 # causes the worker to fork. At this point, the problematic waiter
617 # lock has been acquired once by the waiter and has been put onto
618 # the waiters list.
619 condition = w._block
620 orig_release_save = condition._release_save
621 def my_release_save():
622 global start_fork
623 orig_release_save()
624 # Waiter lock held here, condition lock released.
625 start_fork = True
626 condition._release_save = my_release_save
627
628 w.start()
629 w.join()
630 print('end of main thread')
631 """
632 output = "end of worker thread\nend of main thread\n"
633 self.assertScriptHasOutput(script, output)
634
Charles-François Natali8e6fe642012-03-24 20:36:09 +0100635 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200636 def test_6_daemon_threads(self):
637 # Check that a daemon thread cannot crash the interpreter on shutdown
638 # by manipulating internal structures that are being disposed of in
639 # the main thread.
640 script = """if True:
641 import os
642 import random
643 import sys
644 import time
645 import threading
646
647 thread_has_run = set()
648
649 def random_io():
650 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200651 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200652 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200653 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200654 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200655 null_f.write(stuff)
656 time.sleep(random.random() / 1995)
657 null_f.close()
658 in_f.close()
659 thread_has_run.add(threading.current_thread())
660
661 def main():
662 count = 0
663 for _ in range(40):
664 new_thread = threading.Thread(target=random_io)
665 new_thread.daemon = True
666 new_thread.start()
667 count += 1
668 while len(thread_has_run) < count:
669 time.sleep(0.001)
670 # Trigger process shutdown
671 sys.exit(0)
672
673 main()
674 """
675 rc, out, err = assert_python_ok('-c', script)
676 self.assertFalse(err)
677
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100678 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100679 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100680 def test_reinit_tls_after_fork(self):
681 # Issue #13817: fork() would deadlock in a multithreaded program with
682 # the ad-hoc TLS implementation.
683
684 def do_fork_and_wait():
685 # just fork a child process and wait it
686 pid = os.fork()
687 if pid > 0:
688 os.waitpid(pid, 0)
689 else:
690 os._exit(0)
691
692 # start a bunch of threads that will fork() child processes
693 threads = []
694 for i in range(16):
695 t = threading.Thread(target=do_fork_and_wait)
696 threads.append(t)
697 t.start()
698
699 for t in threads:
700 t.join()
701
Jesse Nollera8513972008-07-17 16:49:17 +0000702
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000703class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000704 # A RuntimeError should be raised if Thread.start() is called
705 # multiple times.
706 def test_start_thread_again(self):
707 thread = threading.Thread()
708 thread.start()
709 self.assertRaises(RuntimeError, thread.start)
710
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000711 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000712 current_thread = threading.current_thread()
713 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000714
715 def test_joining_inactive_thread(self):
716 thread = threading.Thread()
717 self.assertRaises(RuntimeError, thread.join)
718
719 def test_daemonize_active_thread(self):
720 thread = threading.Thread()
721 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000722 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000723
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000724 def test_releasing_unacquired_lock(self):
725 lock = threading.Lock()
726 self.assertRaises(RuntimeError, lock.release)
727
Ned Deily9a7c5242011-05-28 00:19:56 -0700728 @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
729 def test_recursion_limit(self):
730 # Issue 9670
731 # test that excessive recursion within a non-main thread causes
732 # an exception rather than crashing the interpreter on platforms
733 # like Mac OS X or FreeBSD which have small default stack sizes
734 # for threads
735 script = """if True:
736 import threading
737
738 def recurse():
739 return recurse()
740
741 def outer():
742 try:
743 recurse()
744 except RuntimeError:
745 pass
746
747 w = threading.Thread(target=outer)
748 w.start()
749 w.join()
750 print('end of main thread')
751 """
752 expected_output = "end of main thread\n"
753 p = subprocess.Popen([sys.executable, "-c", script],
754 stdout=subprocess.PIPE)
755 stdout, stderr = p.communicate()
756 data = stdout.decode().replace('\r', '')
757 self.assertEqual(p.returncode, 0, "Unexpected error")
758 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000759
Antoine Pitrou557934f2009-11-06 22:41:14 +0000760class LockTests(lock_tests.LockTests):
761 locktype = staticmethod(threading.Lock)
762
Antoine Pitrou434736a2009-11-10 18:46:01 +0000763class PyRLockTests(lock_tests.RLockTests):
764 locktype = staticmethod(threading._PyRLock)
765
Charles-François Natali6b671b22012-01-28 11:36:04 +0100766@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +0000767class CRLockTests(lock_tests.RLockTests):
768 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000769
770class EventTests(lock_tests.EventTests):
771 eventtype = staticmethod(threading.Event)
772
773class ConditionAsRLockTests(lock_tests.RLockTests):
774 # An Condition uses an RLock by default and exports its API.
775 locktype = staticmethod(threading.Condition)
776
777class ConditionTests(lock_tests.ConditionTests):
778 condtype = staticmethod(threading.Condition)
779
780class SemaphoreTests(lock_tests.SemaphoreTests):
781 semtype = staticmethod(threading.Semaphore)
782
783class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
784 semtype = staticmethod(threading.BoundedSemaphore)
785
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000786class BarrierTests(lock_tests.BarrierTests):
787 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000788
Victor Stinner754851f2011-04-19 23:58:51 +0200789
Tim Peters84d54892005-01-08 06:03:17 +0000790def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000791 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000792 ConditionAsRLockTests, ConditionTests,
793 SemaphoreTests, BoundedSemaphoreTests,
794 ThreadTests,
795 ThreadJoinOnShutdown,
796 ThreadingExceptionTests,
Victor Stinnerd5c355c2011-04-30 14:53:09 +0200797 BarrierTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000798 )
Tim Peters84d54892005-01-08 06:03:17 +0000799
800if __name__ == "__main__":
801 test_main()