blob: 5a765f32083702f468f1b7c7591d1dbc64cc4401 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Tim Peters84d54892005-01-08 06:03:17 +00003import test.test_support
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test.test_support import verbose
Antoine Pitrou52849bf2012-04-19 23:55:01 +02005from test.script_helper import assert_python_ok
6
Skip Montanaro4533f602001-08-20 20:28:48 +00007import random
Gregory P. Smith8856dda2008-06-01 23:48:47 +00008import re
Collin Winter50b79ce2007-06-06 00:17:35 +00009import sys
Victor Stinner6a102812010-04-27 23:55:59 +000010thread = test.test_support.import_module('thread')
11threading = test.test_support.import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000012import time
Tim Peters84d54892005-01-08 06:03:17 +000013import unittest
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +000014import weakref
Gregory P. Smith2b79a812011-01-04 01:10:08 +000015import os
16import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000017
Antoine Pitrouc98efe02009-11-06 22:34:35 +000018from test import lock_tests
19
Tim Peters84d54892005-01-08 06:03:17 +000020# A trivial mutable counter.
21class Counter(object):
22 def __init__(self):
23 self.value = 0
24 def inc(self):
25 self.value += 1
26 def dec(self):
27 self.value -= 1
28 def get(self):
29 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000030
31class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000032 def __init__(self, name, testcase, sema, mutex, nrunning):
33 threading.Thread.__init__(self, name=name)
34 self.testcase = testcase
35 self.sema = sema
36 self.mutex = mutex
37 self.nrunning = nrunning
38
Skip Montanaro4533f602001-08-20 20:28:48 +000039 def run(self):
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000040 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000041 if verbose:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000042 print 'task %s will run for %.1f usec' % (
Benjamin Petersoncbae8692008-08-18 17:45:09 +000043 self.name, delay * 1e6)
Tim Peters84d54892005-01-08 06:03:17 +000044
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000045 with self.sema:
46 with self.mutex:
47 self.nrunning.inc()
48 if verbose:
49 print self.nrunning.get(), 'tasks are running'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000050 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000051
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000052 time.sleep(delay)
53 if verbose:
Benjamin Petersoncbae8692008-08-18 17:45:09 +000054 print 'task', self.name, 'done'
Tim Peters84d54892005-01-08 06:03:17 +000055
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000056 with self.mutex:
57 self.nrunning.dec()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000058 self.testcase.assertTrue(self.nrunning.get() >= 0)
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000059 if verbose:
60 print '%s is finished. %d tasks are running' % (
Benjamin Petersoncbae8692008-08-18 17:45:09 +000061 self.name, self.nrunning.get())
Skip Montanaro4533f602001-08-20 20:28:48 +000062
Antoine Pitroubb0bb302009-10-27 20:02:23 +000063class BaseTestCase(unittest.TestCase):
64 def setUp(self):
65 self._threads = test.test_support.threading_setup()
66
67 def tearDown(self):
68 test.test_support.threading_cleanup(*self._threads)
69 test.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 Peterson5c8da862009-06-30 22:57:08 +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:
96 print 'waiting for all tasks to complete'
97 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000098 t.join(NUMTASKS)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000099 self.assertTrue(not t.is_alive())
100 self.assertNotEqual(t.ident, 0)
Benjamin Petersond906ea62009-03-31 21:34:42 +0000101 self.assertFalse(t.ident is None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000102 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000103 if verbose:
104 print 'all tasks done'
105 self.assertEqual(numrunning.get(), 0)
106
Benjamin Petersond906ea62009-03-31 21:34:42 +0000107 def test_ident_of_no_threading_threads(self):
108 # The ident still must work for the main thread and dummy threads.
109 self.assertFalse(threading.currentThread().ident is None)
110 def f():
111 ident.append(threading.currentThread().ident)
112 done.set()
113 done = threading.Event()
114 ident = []
115 thread.start_new_thread(f, ())
116 done.wait()
117 self.assertFalse(ident[0] is None)
Antoine Pitrou00253302009-11-08 00:24:12 +0000118 # Kill the "immortal" _DummyThread
119 del threading._active[ident[0]]
Benjamin Petersond906ea62009-03-31 21:34:42 +0000120
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +0000121 # run with a small(ish) thread stack size (256kB)
Andrew MacIntyre92913322006-06-13 15:04:24 +0000122 def test_various_ops_small_stack(self):
123 if verbose:
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +0000124 print 'with 256kB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000125 try:
126 threading.stack_size(262144)
127 except thread.error:
128 if verbose:
129 print 'platform does not support changing thread stack size'
130 return
Andrew MacIntyre92913322006-06-13 15:04:24 +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:
137 print 'with 1MB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000138 try:
139 threading.stack_size(0x100000)
140 except thread.error:
141 if verbose:
142 print 'platform does not support changing thread stack size'
143 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000144 self.test_various_ops()
145 threading.stack_size(0)
146
Tim Peters711906e2005-01-08 07:30:42 +0000147 def test_foreign_thread(self):
148 # Check that a "foreign" thread can use the threading module.
149 def f(mutex):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000150 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000151 # thread to get made in the threading._active map.
Antoine Pitroud7158d42009-11-09 16:00:11 +0000152 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000153 mutex.release()
154
155 mutex = threading.Lock()
156 mutex.acquire()
157 tid = thread.start_new_thread(f, (mutex,))
158 # Wait for the thread to finish.
159 mutex.acquire()
Ezio Melottiaa980582010-01-23 23:04:36 +0000160 self.assertIn(tid, threading._active)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000161 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000162 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000163
Tim Peters4643c2f2006-08-10 22:45:34 +0000164 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
165 # exposed at the Python level. This test relies on ctypes to get at it.
166 def test_PyThreadState_SetAsyncExc(self):
167 try:
168 import ctypes
169 except ImportError:
170 if verbose:
171 print "test_PyThreadState_SetAsyncExc can't import ctypes"
172 return # can't do anything
173
174 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
175
176 class AsyncExc(Exception):
177 pass
178
179 exception = ctypes.py_object(AsyncExc)
180
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000181 # First check it works when setting the exception from the same thread.
182 tid = thread.get_ident()
183
184 try:
185 result = set_async_exc(ctypes.c_long(tid), exception)
186 # The exception is async, so we might have to keep the VM busy until
187 # it notices.
188 while True:
189 pass
190 except AsyncExc:
191 pass
192 else:
Antoine Pitrou603acf92009-10-18 18:37:11 +0000193 # This code is unreachable but it reflects the intent. If we wanted
194 # to be smarter the above loop wouldn't be infinite.
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000195 self.fail("AsyncExc not raised")
196 try:
197 self.assertEqual(result, 1) # one thread state modified
198 except UnboundLocalError:
Antoine Pitrou603acf92009-10-18 18:37:11 +0000199 # The exception was raised too quickly for us to get the result.
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000200 pass
201
Tim Peters4643c2f2006-08-10 22:45:34 +0000202 # `worker_started` is set by the thread when it's inside a try/except
203 # block waiting to catch the asynchronously set AsyncExc exception.
204 # `worker_saw_exception` is set by the thread upon catching that
205 # exception.
206 worker_started = threading.Event()
207 worker_saw_exception = threading.Event()
208
209 class Worker(threading.Thread):
210 def run(self):
211 self.id = thread.get_ident()
212 self.finished = False
213
214 try:
215 while True:
216 worker_started.set()
217 time.sleep(0.1)
218 except AsyncExc:
219 self.finished = True
220 worker_saw_exception.set()
221
222 t = Worker()
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000223 t.daemon = True # so if this fails, we don't hang Python at shutdown
Tim Peters08574772006-08-11 00:49:01 +0000224 t.start()
Tim Peters4643c2f2006-08-10 22:45:34 +0000225 if verbose:
226 print " started worker thread"
Tim Peters4643c2f2006-08-10 22:45:34 +0000227
228 # Try a thread id that doesn't make sense.
229 if verbose:
230 print " trying nonsensical thread id"
Tim Peters08574772006-08-11 00:49:01 +0000231 result = set_async_exc(ctypes.c_long(-1), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000232 self.assertEqual(result, 0) # no thread states modified
233
234 # Now raise an exception in the worker thread.
235 if verbose:
236 print " waiting for worker thread to get started"
Georg Brandlef660e82009-03-31 20:41:08 +0000237 ret = worker_started.wait()
238 self.assertTrue(ret)
Tim Peters4643c2f2006-08-10 22:45:34 +0000239 if verbose:
240 print " verifying worker hasn't exited"
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000241 self.assertTrue(not t.finished)
Tim Peters4643c2f2006-08-10 22:45:34 +0000242 if verbose:
243 print " attempting to raise asynch exception in worker"
Tim Peters08574772006-08-11 00:49:01 +0000244 result = set_async_exc(ctypes.c_long(t.id), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000245 self.assertEqual(result, 1) # one thread state modified
246 if verbose:
247 print " waiting for worker to say it caught the exception"
248 worker_saw_exception.wait(timeout=10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000249 self.assertTrue(t.finished)
Tim Peters4643c2f2006-08-10 22:45:34 +0000250 if verbose:
251 print " all OK -- joining worker"
252 if t.finished:
253 t.join()
254 # else the thread is still running, and we have no way to kill it
255
Gregory P. Smith613c7a52010-02-28 18:36:09 +0000256 def test_limbo_cleanup(self):
257 # Issue 7481: Failure to start thread should cleanup the limbo map.
258 def fail_new_thread(*args):
259 raise thread.error()
260 _start_new_thread = threading._start_new_thread
261 threading._start_new_thread = fail_new_thread
262 try:
263 t = threading.Thread(target=lambda: None)
Gregory P. Smith3c1586a2010-03-01 03:09:19 +0000264 self.assertRaises(thread.error, t.start)
265 self.assertFalse(
266 t in threading._limbo,
267 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith613c7a52010-02-28 18:36:09 +0000268 finally:
269 threading._start_new_thread = _start_new_thread
270
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000271 def test_finalize_runnning_thread(self):
272 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
273 # very late on python exit: on deallocation of a running thread for
274 # example.
275 try:
276 import ctypes
277 except ImportError:
278 if verbose:
279 print("test_finalize_with_runnning_thread can't import ctypes")
280 return # can't do anything
281
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000282 rc = subprocess.call([sys.executable, "-c", """if 1:
283 import ctypes, sys, time, thread
284
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000285 # This lock is used as a simple event variable.
286 ready = thread.allocate_lock()
287 ready.acquire()
288
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000289 # Module globals are cleared before __del__ is run
290 # So we save the functions in class dict
291 class C:
292 ensure = ctypes.pythonapi.PyGILState_Ensure
293 release = ctypes.pythonapi.PyGILState_Release
294 def __del__(self):
295 state = self.ensure()
296 self.release(state)
297
298 def waitingThread():
299 x = C()
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000300 ready.release()
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000301 time.sleep(100)
302
303 thread.start_new_thread(waitingThread, ())
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000304 ready.acquire() # Be sure the other thread is waiting.
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000305 sys.exit(42)
306 """])
307 self.assertEqual(rc, 42)
308
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000309 def test_finalize_with_trace(self):
310 # Issue1733757
311 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitroua6166da2010-09-20 11:20:44 +0000312 p = subprocess.Popen([sys.executable, "-c", """if 1:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000313 import sys, threading
314
315 # A deadlock-killer, to prevent the
316 # testsuite to hang forever
317 def killer():
318 import os, time
319 time.sleep(2)
320 print 'program blocked; aborting'
321 os._exit(2)
322 t = threading.Thread(target=killer)
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000323 t.daemon = True
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000324 t.start()
325
326 # This is the trace function
327 def func(frame, event, arg):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000328 threading.current_thread()
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000329 return func
330
331 sys.settrace(func)
Antoine Pitroua6166da2010-09-20 11:20:44 +0000332 """],
333 stdout=subprocess.PIPE,
334 stderr=subprocess.PIPE)
Brian Curtin51c9b512010-11-05 17:24:20 +0000335 self.addCleanup(p.stdout.close)
336 self.addCleanup(p.stderr.close)
Antoine Pitroua6166da2010-09-20 11:20:44 +0000337 stdout, stderr = p.communicate()
338 rc = p.returncode
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000339 self.assertFalse(rc == 2, "interpreted was blocked")
Antoine Pitroua6166da2010-09-20 11:20:44 +0000340 self.assertTrue(rc == 0,
341 "Unexpected error: " + repr(stderr))
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000342
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000343 def test_join_nondaemon_on_shutdown(self):
344 # Issue 1722344
345 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000346 p = subprocess.Popen([sys.executable, "-c", """if 1:
347 import threading
348 from time import sleep
349
350 def child():
351 sleep(1)
352 # As a non-daemon thread we SHOULD wake up and nothing
353 # should be torn down yet
354 print "Woke up, sleep function is:", sleep
355
356 threading.Thread(target=child).start()
357 raise SystemExit
358 """],
359 stdout=subprocess.PIPE,
360 stderr=subprocess.PIPE)
Brian Curtin51c9b512010-11-05 17:24:20 +0000361 self.addCleanup(p.stdout.close)
362 self.addCleanup(p.stderr.close)
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000363 stdout, stderr = p.communicate()
Antoine Pitroub119ca92009-10-23 12:01:13 +0000364 self.assertEqual(stdout.strip(),
365 "Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou9bd246b2009-10-20 21:59:25 +0000366 stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip()
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000367 self.assertEqual(stderr, "")
368
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000369 def test_enumerate_after_join(self):
370 # Try hard to trigger #1703448: a thread is still returned in
371 # threading.enumerate() after it has been join()ed.
372 enum = threading.enumerate
373 old_interval = sys.getcheckinterval()
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000374 try:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000375 for i in xrange(1, 100):
376 # Try a couple times at each thread-switching interval
377 # to get more interleavings.
378 sys.setcheckinterval(i // 5)
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000379 t = threading.Thread(target=lambda: None)
380 t.start()
381 t.join()
382 l = enum()
Ezio Melottiaa980582010-01-23 23:04:36 +0000383 self.assertNotIn(t, l,
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000384 "#1703448 triggered after %d trials: %s" % (i, l))
385 finally:
386 sys.setcheckinterval(old_interval)
387
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000388 def test_no_refcycle_through_target(self):
389 class RunSelfFunction(object):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000390 def __init__(self, should_raise):
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000391 # The links in this refcycle from Thread back to self
392 # should be cleaned up when the thread completes.
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000393 self.should_raise = should_raise
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000394 self.thread = threading.Thread(target=self._run,
395 args=(self,),
396 kwargs={'yet_another':self})
397 self.thread.start()
398
399 def _run(self, other_ref, yet_another):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000400 if self.should_raise:
401 raise SystemExit
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000402
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000403 cyclic_object = RunSelfFunction(should_raise=False)
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000404 weak_cyclic_object = weakref.ref(cyclic_object)
405 cyclic_object.thread.join()
406 del cyclic_object
Ezio Melotti2623a372010-11-21 13:34:58 +0000407 self.assertEqual(None, weak_cyclic_object(),
408 msg=('%d references still around' %
409 sys.getrefcount(weak_cyclic_object())))
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000410
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000411 raising_cyclic_object = RunSelfFunction(should_raise=True)
412 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
413 raising_cyclic_object.thread.join()
414 del raising_cyclic_object
Ezio Melotti2623a372010-11-21 13:34:58 +0000415 self.assertEqual(None, weak_raising_cyclic_object(),
416 msg=('%d references still around' %
417 sys.getrefcount(weak_raising_cyclic_object())))
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000418
Antoine Pitrou52849bf2012-04-19 23:55:01 +0200419 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
420 def test_dummy_thread_after_fork(self):
421 # Issue #14308: a dummy thread in the active list doesn't mess up
422 # the after-fork mechanism.
423 code = """if 1:
424 import thread, threading, os, time
425
426 def background_thread(evt):
427 # Creates and registers the _DummyThread instance
428 threading.current_thread()
429 evt.set()
430 time.sleep(10)
431
432 evt = threading.Event()
433 thread.start_new_thread(background_thread, (evt,))
434 evt.wait()
435 assert threading.active_count() == 2, threading.active_count()
436 if os.fork() == 0:
437 assert threading.active_count() == 1, threading.active_count()
438 os._exit(0)
439 else:
440 os.wait()
441 """
442 _, out, err = assert_python_ok("-c", code)
443 self.assertEqual(out, '')
444 self.assertEqual(err, '')
445
Charles-François Natali30a54452013-08-30 23:30:50 +0200446 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
447 def test_is_alive_after_fork(self):
448 # Try hard to trigger #18418: is_alive() could sometimes be True on
449 # threads that vanished after a fork.
450 old_interval = sys.getcheckinterval()
451
452 # Make the bug more likely to manifest.
453 sys.setcheckinterval(10)
454
455 try:
456 for i in range(20):
457 t = threading.Thread(target=lambda: None)
458 t.start()
459 pid = os.fork()
460 if pid == 0:
461 os._exit(1 if t.is_alive() else 0)
462 else:
463 t.join()
464 pid, status = os.waitpid(pid, 0)
465 self.assertEqual(0, status)
466 finally:
467 sys.setcheckinterval(old_interval)
468
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000469
Antoine Pitroubb0bb302009-10-27 20:02:23 +0000470class ThreadJoinOnShutdown(BaseTestCase):
Jesse Noller5e62ca42008-07-16 20:03:47 +0000471
Victor Stinner041d2e12011-07-01 15:04:03 +0200472 # Between fork() and exec(), only async-safe functions are allowed (issues
473 # #12316 and #11870), and fork() from a worker thread is known to trigger
474 # problems with some operating systems (issue #3863): skip problematic tests
475 # on platforms known to behave badly.
476 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
477 'os2emx')
478
Jesse Noller5e62ca42008-07-16 20:03:47 +0000479 def _run_and_join(self, script):
480 script = """if 1:
481 import sys, os, time, threading
482
483 # a thread, which waits for the main program to terminate
484 def joiningfunc(mainthread):
485 mainthread.join()
486 print 'end of thread'
487 \n""" + script
488
Jesse Noller5e62ca42008-07-16 20:03:47 +0000489 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
490 rc = p.wait()
Benjamin Petersonf5668f12008-07-17 12:57:22 +0000491 data = p.stdout.read().replace('\r', '')
Brian Curtina54bf8b2010-11-02 04:04:37 +0000492 p.stdout.close()
Benjamin Petersonf5668f12008-07-17 12:57:22 +0000493 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000494 self.assertFalse(rc == 2, "interpreter was blocked")
495 self.assertTrue(rc == 0, "Unexpected error")
Jesse Noller5e62ca42008-07-16 20:03:47 +0000496
497 def test_1_join_on_shutdown(self):
498 # The usual case: on exit, wait for a non-daemon thread
499 script = """if 1:
500 import os
501 t = threading.Thread(target=joiningfunc,
502 args=(threading.current_thread(),))
503 t.start()
504 time.sleep(0.1)
505 print 'end of main'
506 """
507 self._run_and_join(script)
508
509
Victor Stinner041d2e12011-07-01 15:04:03 +0200510 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
511 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Noller5e62ca42008-07-16 20:03:47 +0000512 def test_2_join_in_forked_process(self):
513 # Like the test above, but from a forked interpreter
Jesse Noller5e62ca42008-07-16 20:03:47 +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
Victor Stinner041d2e12011-07-01 15:04:03 +0200527 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
528 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Noller5e62ca42008-07-16 20:03:47 +0000529 def test_3_join_in_forked_from_thread(self):
530 # 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.
Jesse Noller5e62ca42008-07-16 20:03:47 +0000532 script = """if 1:
533 main_thread = threading.current_thread()
534 def worker():
535 childpid = os.fork()
536 if childpid != 0:
537 os.waitpid(childpid, 0)
538 sys.exit(0)
539
540 t = threading.Thread(target=joiningfunc,
541 args=(main_thread,))
542 print 'end of main'
543 t.start()
544 t.join() # Should not block: main_thread is already stopped
545
546 w = threading.Thread(target=worker)
547 w.start()
548 """
549 self._run_and_join(script)
550
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000551 def assertScriptHasOutput(self, script, expected_output):
552 p = subprocess.Popen([sys.executable, "-c", script],
553 stdout=subprocess.PIPE)
554 rc = p.wait()
555 data = p.stdout.read().decode().replace('\r', '')
556 self.assertEqual(rc, 0, "Unexpected error")
557 self.assertEqual(data, expected_output)
558
559 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner041d2e12011-07-01 15:04:03 +0200560 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000561 def test_4_joining_across_fork_in_worker_thread(self):
562 # There used to be a possible deadlock when forking from a child
563 # thread. See http://bugs.python.org/issue6643.
564
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000565 # The script takes the following steps:
566 # - The main thread in the parent process starts a new thread and then
567 # tries to join it.
568 # - The join operation acquires the Lock inside the thread's _block
569 # Condition. (See threading.py:Thread.join().)
570 # - We stub out the acquire method on the condition to force it to wait
571 # until the child thread forks. (See LOCK ACQUIRED HERE)
572 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
573 # HERE)
574 # - The main thread of the parent process enters Condition.wait(),
575 # which releases the lock on the child thread.
576 # - The child process returns. Without the necessary fix, when the
577 # main thread of the child process (which used to be the child thread
578 # in the parent process) attempts to exit, it will try to acquire the
579 # lock in the Thread._block Condition object and hang, because the
580 # lock was held across the fork.
581
582 script = """if 1:
583 import os, time, threading
584
585 finish_join = False
586 start_fork = False
587
588 def worker():
589 # Wait until this thread's lock is acquired before forking to
590 # create the deadlock.
591 global finish_join
592 while not start_fork:
593 time.sleep(0.01)
594 # LOCK HELD: Main thread holds lock across this call.
595 childpid = os.fork()
596 finish_join = True
597 if childpid != 0:
598 # Parent process just waits for child.
599 os.waitpid(childpid, 0)
600 # Child process should just return.
601
602 w = threading.Thread(target=worker)
603
604 # Stub out the private condition variable's lock acquire method.
605 # This acquires the lock and then waits until the child has forked
606 # before returning, which will release the lock soon after. If
607 # someone else tries to fix this test case by acquiring this lock
Ezio Melottic2077b02011-03-16 12:34:31 +0200608 # before forking instead of resetting it, the test case will
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000609 # deadlock when it shouldn't.
610 condition = w._block
611 orig_acquire = condition.acquire
612 call_count_lock = threading.Lock()
613 call_count = 0
614 def my_acquire():
615 global call_count
616 global start_fork
617 orig_acquire() # LOCK ACQUIRED HERE
618 start_fork = True
619 if call_count == 0:
620 while not finish_join:
621 time.sleep(0.01) # WORKER THREAD FORKS HERE
622 with call_count_lock:
623 call_count += 1
624 condition.acquire = my_acquire
625
626 w.start()
627 w.join()
628 print('end of main')
629 """
630 self.assertScriptHasOutput(script, "end of main\n")
631
632 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner041d2e12011-07-01 15:04:03 +0200633 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000634 def test_5_clear_waiter_locks_to_avoid_crash(self):
635 # Check that a spawned thread that forks doesn't segfault on certain
636 # platforms, namely OS X. This used to happen if there was a waiter
637 # lock in the thread's condition variable's waiters list. Even though
638 # we know the lock will be held across the fork, it is not safe to
639 # release locks held across forks on all platforms, so releasing the
640 # waiter lock caused a segfault on OS X. Furthermore, since locks on
641 # OS X are (as of this writing) implemented with a mutex + condition
642 # variable instead of a semaphore, while we know that the Python-level
643 # lock will be acquired, we can't know if the internal mutex will be
644 # acquired at the time of the fork.
645
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000646 script = """if True:
647 import os, time, threading
648
649 start_fork = False
650
651 def worker():
652 # Wait until the main thread has attempted to join this thread
653 # before continuing.
654 while not start_fork:
655 time.sleep(0.01)
656 childpid = os.fork()
657 if childpid != 0:
658 # Parent process just waits for child.
659 (cpid, rc) = os.waitpid(childpid, 0)
660 assert cpid == childpid
661 assert rc == 0
662 print('end of worker thread')
663 else:
664 # Child process should just return.
665 pass
666
667 w = threading.Thread(target=worker)
668
669 # Stub out the private condition variable's _release_save method.
670 # This releases the condition's lock and flips the global that
671 # causes the worker to fork. At this point, the problematic waiter
672 # lock has been acquired once by the waiter and has been put onto
673 # the waiters list.
674 condition = w._block
675 orig_release_save = condition._release_save
676 def my_release_save():
677 global start_fork
678 orig_release_save()
679 # Waiter lock held here, condition lock released.
680 start_fork = True
681 condition._release_save = my_release_save
682
683 w.start()
684 w.join()
685 print('end of main thread')
686 """
687 output = "end of worker thread\nend of main thread\n"
688 self.assertScriptHasOutput(script, output)
689
Charles-François Natalie0e88b02012-02-02 19:57:19 +0100690 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Nataliebf691d2012-02-08 21:27:56 +0100691 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natalie0e88b02012-02-02 19:57:19 +0100692 def test_reinit_tls_after_fork(self):
693 # Issue #13817: fork() would deadlock in a multithreaded program with
694 # the ad-hoc TLS implementation.
695
696 def do_fork_and_wait():
697 # just fork a child process and wait it
698 pid = os.fork()
699 if pid > 0:
700 os.waitpid(pid, 0)
701 else:
702 os._exit(0)
703
704 # start a bunch of threads that will fork() child processes
705 threads = []
706 for i in range(16):
707 t = threading.Thread(target=do_fork_and_wait)
708 threads.append(t)
709 t.start()
710
711 for t in threads:
712 t.join()
713
Jesse Noller5e62ca42008-07-16 20:03:47 +0000714
Antoine Pitroubb0bb302009-10-27 20:02:23 +0000715class ThreadingExceptionTests(BaseTestCase):
Collin Winter50b79ce2007-06-06 00:17:35 +0000716 # A RuntimeError should be raised if Thread.start() is called
717 # multiple times.
718 def test_start_thread_again(self):
719 thread = threading.Thread()
720 thread.start()
721 self.assertRaises(RuntimeError, thread.start)
722
Collin Winter50b79ce2007-06-06 00:17:35 +0000723 def test_joining_current_thread(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000724 current_thread = threading.current_thread()
725 self.assertRaises(RuntimeError, current_thread.join);
Collin Winter50b79ce2007-06-06 00:17:35 +0000726
727 def test_joining_inactive_thread(self):
728 thread = threading.Thread()
729 self.assertRaises(RuntimeError, thread.join)
730
731 def test_daemonize_active_thread(self):
732 thread = threading.Thread()
733 thread.start()
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000734 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Collin Winter50b79ce2007-06-06 00:17:35 +0000735
736
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000737class LockTests(lock_tests.LockTests):
738 locktype = staticmethod(threading.Lock)
739
740class RLockTests(lock_tests.RLockTests):
741 locktype = staticmethod(threading.RLock)
742
743class EventTests(lock_tests.EventTests):
744 eventtype = staticmethod(threading.Event)
745
746class ConditionAsRLockTests(lock_tests.RLockTests):
747 # An Condition uses an RLock by default and exports its API.
748 locktype = staticmethod(threading.Condition)
749
750class ConditionTests(lock_tests.ConditionTests):
751 condtype = staticmethod(threading.Condition)
752
753class SemaphoreTests(lock_tests.SemaphoreTests):
754 semtype = staticmethod(threading.Semaphore)
755
756class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
757 semtype = staticmethod(threading.BoundedSemaphore)
758
Ned Deily482f9082011-05-28 00:11:54 -0700759 @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
760 def test_recursion_limit(self):
761 # Issue 9670
762 # test that excessive recursion within a non-main thread causes
763 # an exception rather than crashing the interpreter on platforms
764 # like Mac OS X or FreeBSD which have small default stack sizes
765 # for threads
766 script = """if True:
767 import threading
768
769 def recurse():
770 return recurse()
771
772 def outer():
773 try:
774 recurse()
775 except RuntimeError:
776 pass
777
778 w = threading.Thread(target=outer)
779 w.start()
780 w.join()
781 print('end of main thread')
782 """
783 expected_output = "end of main thread\n"
784 p = subprocess.Popen([sys.executable, "-c", script],
785 stdout=subprocess.PIPE)
786 stdout, stderr = p.communicate()
787 data = stdout.decode().replace('\r', '')
788 self.assertEqual(p.returncode, 0, "Unexpected error")
789 self.assertEqual(data, expected_output)
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000790
Tim Peters84d54892005-01-08 06:03:17 +0000791def test_main():
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000792 test.test_support.run_unittest(LockTests, RLockTests, EventTests,
793 ConditionAsRLockTests, ConditionTests,
794 SemaphoreTests, BoundedSemaphoreTests,
795 ThreadTests,
Jesse Noller5e62ca42008-07-16 20:03:47 +0000796 ThreadJoinOnShutdown,
797 ThreadingExceptionTests,
798 )
Tim Peters84d54892005-01-08 06:03:17 +0000799
800if __name__ == "__main__":
801 test_main()