blob: e617fa1275a56d85be00f135117fd742bcd0245c [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
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Gregory P. Smith8856dda2008-06-01 23:48:47 +00006import re
Collin Winter50b79ce2007-06-06 00:17:35 +00007import sys
Victor Stinner6a102812010-04-27 23:55:59 +00008thread = test.test_support.import_module('thread')
9threading = test.test_support.import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +000012import weakref
Gregory P. Smith2b79a812011-01-04 01:10:08 +000013import os
14import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000015
Antoine Pitrouc98efe02009-11-06 22:34:35 +000016from test import lock_tests
17
Tim Peters84d54892005-01-08 06:03:17 +000018# A trivial mutable counter.
19class Counter(object):
20 def __init__(self):
21 self.value = 0
22 def inc(self):
23 self.value += 1
24 def dec(self):
25 self.value -= 1
26 def get(self):
27 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000028
29class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000030 def __init__(self, name, testcase, sema, mutex, nrunning):
31 threading.Thread.__init__(self, name=name)
32 self.testcase = testcase
33 self.sema = sema
34 self.mutex = mutex
35 self.nrunning = nrunning
36
Skip Montanaro4533f602001-08-20 20:28:48 +000037 def run(self):
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000038 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000039 if verbose:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000040 print 'task %s will run for %.1f usec' % (
Benjamin Petersoncbae8692008-08-18 17:45:09 +000041 self.name, delay * 1e6)
Tim Peters84d54892005-01-08 06:03:17 +000042
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000043 with self.sema:
44 with self.mutex:
45 self.nrunning.inc()
46 if verbose:
47 print self.nrunning.get(), 'tasks are running'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000048 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000049
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000050 time.sleep(delay)
51 if verbose:
Benjamin Petersoncbae8692008-08-18 17:45:09 +000052 print 'task', self.name, 'done'
Tim Peters84d54892005-01-08 06:03:17 +000053
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000054 with self.mutex:
55 self.nrunning.dec()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000056 self.testcase.assertTrue(self.nrunning.get() >= 0)
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000057 if verbose:
58 print '%s is finished. %d tasks are running' % (
Benjamin Petersoncbae8692008-08-18 17:45:09 +000059 self.name, self.nrunning.get())
Skip Montanaro4533f602001-08-20 20:28:48 +000060
Antoine Pitroubb0bb302009-10-27 20:02:23 +000061class BaseTestCase(unittest.TestCase):
62 def setUp(self):
63 self._threads = test.test_support.threading_setup()
64
65 def tearDown(self):
66 test.test_support.threading_cleanup(*self._threads)
67 test.test_support.reap_children()
68
69
70class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000071
Tim Peters84d54892005-01-08 06:03:17 +000072 # Create a bunch of threads, let each do some work, wait until all are
73 # done.
74 def test_various_ops(self):
75 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
76 # times about 1 second per clump).
77 NUMTASKS = 10
78
79 # no more than 3 of the 10 can run at once
80 sema = threading.BoundedSemaphore(value=3)
81 mutex = threading.RLock()
82 numrunning = Counter()
83
84 threads = []
85
86 for i in range(NUMTASKS):
87 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
88 threads.append(t)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000089 self.assertEqual(t.ident, None)
90 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000091 t.start()
92
93 if verbose:
94 print 'waiting for all tasks to complete'
95 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000096 t.join(NUMTASKS)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000097 self.assertTrue(not t.is_alive())
98 self.assertNotEqual(t.ident, 0)
Benjamin Petersond906ea62009-03-31 21:34:42 +000099 self.assertFalse(t.ident is None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000100 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000101 if verbose:
102 print 'all tasks done'
103 self.assertEqual(numrunning.get(), 0)
104
Benjamin Petersond906ea62009-03-31 21:34:42 +0000105 def test_ident_of_no_threading_threads(self):
106 # The ident still must work for the main thread and dummy threads.
107 self.assertFalse(threading.currentThread().ident is None)
108 def f():
109 ident.append(threading.currentThread().ident)
110 done.set()
111 done = threading.Event()
112 ident = []
113 thread.start_new_thread(f, ())
114 done.wait()
115 self.assertFalse(ident[0] is None)
Antoine Pitrou00253302009-11-08 00:24:12 +0000116 # Kill the "immortal" _DummyThread
117 del threading._active[ident[0]]
Benjamin Petersond906ea62009-03-31 21:34:42 +0000118
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +0000119 # run with a small(ish) thread stack size (256kB)
Andrew MacIntyre92913322006-06-13 15:04:24 +0000120 def test_various_ops_small_stack(self):
121 if verbose:
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +0000122 print 'with 256kB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000123 try:
124 threading.stack_size(262144)
125 except thread.error:
126 if verbose:
127 print 'platform does not support changing thread stack size'
128 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000129 self.test_various_ops()
130 threading.stack_size(0)
131
132 # run with a large thread stack size (1MB)
133 def test_various_ops_large_stack(self):
134 if verbose:
135 print 'with 1MB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000136 try:
137 threading.stack_size(0x100000)
138 except thread.error:
139 if verbose:
140 print 'platform does not support changing thread stack size'
141 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000142 self.test_various_ops()
143 threading.stack_size(0)
144
Tim Peters711906e2005-01-08 07:30:42 +0000145 def test_foreign_thread(self):
146 # Check that a "foreign" thread can use the threading module.
147 def f(mutex):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000148 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000149 # thread to get made in the threading._active map.
Antoine Pitroud7158d42009-11-09 16:00:11 +0000150 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000151 mutex.release()
152
153 mutex = threading.Lock()
154 mutex.acquire()
155 tid = thread.start_new_thread(f, (mutex,))
156 # Wait for the thread to finish.
157 mutex.acquire()
Ezio Melottiaa980582010-01-23 23:04:36 +0000158 self.assertIn(tid, threading._active)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000159 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000160 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000161
Tim Peters4643c2f2006-08-10 22:45:34 +0000162 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
163 # exposed at the Python level. This test relies on ctypes to get at it.
164 def test_PyThreadState_SetAsyncExc(self):
165 try:
166 import ctypes
167 except ImportError:
168 if verbose:
169 print "test_PyThreadState_SetAsyncExc can't import ctypes"
170 return # can't do anything
171
172 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
173
174 class AsyncExc(Exception):
175 pass
176
177 exception = ctypes.py_object(AsyncExc)
178
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000179 # First check it works when setting the exception from the same thread.
180 tid = thread.get_ident()
181
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:
Antoine Pitrou603acf92009-10-18 18:37:11 +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 Pitrou8a172b12009-10-18 18:22:04 +0000193 self.fail("AsyncExc not raised")
194 try:
195 self.assertEqual(result, 1) # one thread state modified
196 except UnboundLocalError:
Antoine Pitrou603acf92009-10-18 18:37:11 +0000197 # The exception was raised too quickly for us to get the result.
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000198 pass
199
Tim Peters4643c2f2006-08-10 22:45:34 +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):
209 self.id = thread.get_ident()
210 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 Petersoncbae8692008-08-18 17:45:09 +0000221 t.daemon = True # so if this fails, we don't hang Python at shutdown
Tim Peters08574772006-08-11 00:49:01 +0000222 t.start()
Tim Peters4643c2f2006-08-10 22:45:34 +0000223 if verbose:
224 print " started worker thread"
Tim Peters4643c2f2006-08-10 22:45:34 +0000225
226 # Try a thread id that doesn't make sense.
227 if verbose:
228 print " trying nonsensical thread id"
Tim Peters08574772006-08-11 00:49:01 +0000229 result = set_async_exc(ctypes.c_long(-1), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000230 self.assertEqual(result, 0) # no thread states modified
231
232 # Now raise an exception in the worker thread.
233 if verbose:
234 print " waiting for worker thread to get started"
Georg Brandlef660e82009-03-31 20:41:08 +0000235 ret = worker_started.wait()
236 self.assertTrue(ret)
Tim Peters4643c2f2006-08-10 22:45:34 +0000237 if verbose:
238 print " verifying worker hasn't exited"
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000239 self.assertTrue(not t.finished)
Tim Peters4643c2f2006-08-10 22:45:34 +0000240 if verbose:
241 print " attempting to raise asynch exception in worker"
Tim Peters08574772006-08-11 00:49:01 +0000242 result = set_async_exc(ctypes.c_long(t.id), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000243 self.assertEqual(result, 1) # one thread state modified
244 if verbose:
245 print " waiting for worker to say it caught the exception"
246 worker_saw_exception.wait(timeout=10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000247 self.assertTrue(t.finished)
Tim Peters4643c2f2006-08-10 22:45:34 +0000248 if verbose:
249 print " all OK -- joining worker"
250 if t.finished:
251 t.join()
252 # else the thread is still running, and we have no way to kill it
253
Gregory P. Smith613c7a52010-02-28 18:36:09 +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 thread.error()
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. Smith3c1586a2010-03-01 03:09:19 +0000262 self.assertRaises(thread.error, t.start)
263 self.assertFalse(
264 t in threading._limbo,
265 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith613c7a52010-02-28 18:36:09 +0000266 finally:
267 threading._start_new_thread = _start_new_thread
268
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +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.
273 try:
274 import ctypes
275 except ImportError:
276 if verbose:
277 print("test_finalize_with_runnning_thread can't import ctypes")
278 return # can't do anything
279
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000280 rc = subprocess.call([sys.executable, "-c", """if 1:
281 import ctypes, sys, time, thread
282
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000283 # This lock is used as a simple event variable.
284 ready = thread.allocate_lock()
285 ready.acquire()
286
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000287 # Module globals are cleared before __del__ is run
288 # So we save the functions in class dict
289 class C:
290 ensure = ctypes.pythonapi.PyGILState_Ensure
291 release = ctypes.pythonapi.PyGILState_Release
292 def __del__(self):
293 state = self.ensure()
294 self.release(state)
295
296 def waitingThread():
297 x = C()
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000298 ready.release()
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000299 time.sleep(100)
300
301 thread.start_new_thread(waitingThread, ())
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000302 ready.acquire() # Be sure the other thread is waiting.
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000303 sys.exit(42)
304 """])
305 self.assertEqual(rc, 42)
306
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000307 def test_finalize_with_trace(self):
308 # Issue1733757
309 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitroua6166da2010-09-20 11:20:44 +0000310 p = subprocess.Popen([sys.executable, "-c", """if 1:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000311 import sys, threading
312
313 # A deadlock-killer, to prevent the
314 # testsuite to hang forever
315 def killer():
316 import os, time
317 time.sleep(2)
318 print 'program blocked; aborting'
319 os._exit(2)
320 t = threading.Thread(target=killer)
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000321 t.daemon = True
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000322 t.start()
323
324 # This is the trace function
325 def func(frame, event, arg):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000326 threading.current_thread()
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000327 return func
328
329 sys.settrace(func)
Antoine Pitroua6166da2010-09-20 11:20:44 +0000330 """],
331 stdout=subprocess.PIPE,
332 stderr=subprocess.PIPE)
Brian Curtin51c9b512010-11-05 17:24:20 +0000333 self.addCleanup(p.stdout.close)
334 self.addCleanup(p.stderr.close)
Antoine Pitroua6166da2010-09-20 11:20:44 +0000335 stdout, stderr = p.communicate()
336 rc = p.returncode
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000337 self.assertFalse(rc == 2, "interpreted was blocked")
Antoine Pitroua6166da2010-09-20 11:20:44 +0000338 self.assertTrue(rc == 0,
339 "Unexpected error: " + repr(stderr))
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000340
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000341 def test_join_nondaemon_on_shutdown(self):
342 # Issue 1722344
343 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000344 p = subprocess.Popen([sys.executable, "-c", """if 1:
345 import threading
346 from time import sleep
347
348 def child():
349 sleep(1)
350 # As a non-daemon thread we SHOULD wake up and nothing
351 # should be torn down yet
352 print "Woke up, sleep function is:", sleep
353
354 threading.Thread(target=child).start()
355 raise SystemExit
356 """],
357 stdout=subprocess.PIPE,
358 stderr=subprocess.PIPE)
Brian Curtin51c9b512010-11-05 17:24:20 +0000359 self.addCleanup(p.stdout.close)
360 self.addCleanup(p.stderr.close)
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000361 stdout, stderr = p.communicate()
Antoine Pitroub119ca92009-10-23 12:01:13 +0000362 self.assertEqual(stdout.strip(),
363 "Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou9bd246b2009-10-20 21:59:25 +0000364 stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip()
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000365 self.assertEqual(stderr, "")
366
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000367 def test_enumerate_after_join(self):
368 # Try hard to trigger #1703448: a thread is still returned in
369 # threading.enumerate() after it has been join()ed.
370 enum = threading.enumerate
371 old_interval = sys.getcheckinterval()
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000372 try:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000373 for i in xrange(1, 100):
374 # Try a couple times at each thread-switching interval
375 # to get more interleavings.
376 sys.setcheckinterval(i // 5)
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000377 t = threading.Thread(target=lambda: None)
378 t.start()
379 t.join()
380 l = enum()
Ezio Melottiaa980582010-01-23 23:04:36 +0000381 self.assertNotIn(t, l,
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000382 "#1703448 triggered after %d trials: %s" % (i, l))
383 finally:
384 sys.setcheckinterval(old_interval)
385
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000386 def test_no_refcycle_through_target(self):
387 class RunSelfFunction(object):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000388 def __init__(self, should_raise):
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000389 # The links in this refcycle from Thread back to self
390 # should be cleaned up when the thread completes.
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000391 self.should_raise = should_raise
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000392 self.thread = threading.Thread(target=self._run,
393 args=(self,),
394 kwargs={'yet_another':self})
395 self.thread.start()
396
397 def _run(self, other_ref, yet_another):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000398 if self.should_raise:
399 raise SystemExit
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000400
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000401 cyclic_object = RunSelfFunction(should_raise=False)
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000402 weak_cyclic_object = weakref.ref(cyclic_object)
403 cyclic_object.thread.join()
404 del cyclic_object
Ezio Melotti2623a372010-11-21 13:34:58 +0000405 self.assertEqual(None, weak_cyclic_object(),
406 msg=('%d references still around' %
407 sys.getrefcount(weak_cyclic_object())))
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000408
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000409 raising_cyclic_object = RunSelfFunction(should_raise=True)
410 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
411 raising_cyclic_object.thread.join()
412 del raising_cyclic_object
Ezio Melotti2623a372010-11-21 13:34:58 +0000413 self.assertEqual(None, weak_raising_cyclic_object(),
414 msg=('%d references still around' %
415 sys.getrefcount(weak_raising_cyclic_object())))
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000416
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000417
Antoine Pitroubb0bb302009-10-27 20:02:23 +0000418class ThreadJoinOnShutdown(BaseTestCase):
Jesse Noller5e62ca42008-07-16 20:03:47 +0000419
Victor Stinner041d2e12011-07-01 15:04:03 +0200420 # Between fork() and exec(), only async-safe functions are allowed (issues
421 # #12316 and #11870), and fork() from a worker thread is known to trigger
422 # problems with some operating systems (issue #3863): skip problematic tests
423 # on platforms known to behave badly.
424 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
425 'os2emx')
426
Jesse Noller5e62ca42008-07-16 20:03:47 +0000427 def _run_and_join(self, script):
428 script = """if 1:
429 import sys, os, time, threading
430
431 # a thread, which waits for the main program to terminate
432 def joiningfunc(mainthread):
433 mainthread.join()
434 print 'end of thread'
435 \n""" + script
436
Jesse Noller5e62ca42008-07-16 20:03:47 +0000437 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
438 rc = p.wait()
Benjamin Petersonf5668f12008-07-17 12:57:22 +0000439 data = p.stdout.read().replace('\r', '')
Brian Curtina54bf8b2010-11-02 04:04:37 +0000440 p.stdout.close()
Benjamin Petersonf5668f12008-07-17 12:57:22 +0000441 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000442 self.assertFalse(rc == 2, "interpreter was blocked")
443 self.assertTrue(rc == 0, "Unexpected error")
Jesse Noller5e62ca42008-07-16 20:03:47 +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
457
Victor Stinner041d2e12011-07-01 15:04:03 +0200458 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
459 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Noller5e62ca42008-07-16 20:03:47 +0000460 def test_2_join_in_forked_process(self):
461 # Like the test above, but from a forked interpreter
Jesse Noller5e62ca42008-07-16 20:03:47 +0000462 script = """if 1:
463 childpid = os.fork()
464 if childpid != 0:
465 os.waitpid(childpid, 0)
466 sys.exit(0)
467
468 t = threading.Thread(target=joiningfunc,
469 args=(threading.current_thread(),))
470 t.start()
471 print 'end of main'
472 """
473 self._run_and_join(script)
474
Victor Stinner041d2e12011-07-01 15:04:03 +0200475 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
476 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Noller5e62ca42008-07-16 20:03:47 +0000477 def test_3_join_in_forked_from_thread(self):
478 # Like the test above, but fork() was called from a worker thread
479 # In the forked process, the main Thread object must be marked as stopped.
Jesse Noller5e62ca42008-07-16 20:03:47 +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. Smith2b79a812011-01-04 01:10:08 +0000499 def assertScriptHasOutput(self, script, expected_output):
500 p = subprocess.Popen([sys.executable, "-c", script],
501 stdout=subprocess.PIPE)
502 rc = p.wait()
503 data = p.stdout.read().decode().replace('\r', '')
504 self.assertEqual(rc, 0, "Unexpected error")
505 self.assertEqual(data, expected_output)
506
507 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner041d2e12011-07-01 15:04:03 +0200508 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000509 def test_4_joining_across_fork_in_worker_thread(self):
510 # There used to be a possible deadlock when forking from a child
511 # thread. See http://bugs.python.org/issue6643.
512
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000513 # The script takes the following steps:
514 # - The main thread in the parent process starts a new thread and then
515 # tries to join it.
516 # - The join operation acquires the Lock inside the thread's _block
517 # Condition. (See threading.py:Thread.join().)
518 # - We stub out the acquire method on the condition to force it to wait
519 # until the child thread forks. (See LOCK ACQUIRED HERE)
520 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
521 # HERE)
522 # - The main thread of the parent process enters Condition.wait(),
523 # which releases the lock on the child thread.
524 # - The child process returns. Without the necessary fix, when the
525 # main thread of the child process (which used to be the child thread
526 # in the parent process) attempts to exit, it will try to acquire the
527 # lock in the Thread._block Condition object and hang, because the
528 # lock was held across the fork.
529
530 script = """if 1:
531 import os, time, threading
532
533 finish_join = False
534 start_fork = False
535
536 def worker():
537 # Wait until this thread's lock is acquired before forking to
538 # create the deadlock.
539 global finish_join
540 while not start_fork:
541 time.sleep(0.01)
542 # LOCK HELD: Main thread holds lock across this call.
543 childpid = os.fork()
544 finish_join = True
545 if childpid != 0:
546 # Parent process just waits for child.
547 os.waitpid(childpid, 0)
548 # Child process should just return.
549
550 w = threading.Thread(target=worker)
551
552 # Stub out the private condition variable's lock acquire method.
553 # This acquires the lock and then waits until the child has forked
554 # before returning, which will release the lock soon after. If
555 # someone else tries to fix this test case by acquiring this lock
Ezio Melottic2077b02011-03-16 12:34:31 +0200556 # before forking instead of resetting it, the test case will
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000557 # deadlock when it shouldn't.
558 condition = w._block
559 orig_acquire = condition.acquire
560 call_count_lock = threading.Lock()
561 call_count = 0
562 def my_acquire():
563 global call_count
564 global start_fork
565 orig_acquire() # LOCK ACQUIRED HERE
566 start_fork = True
567 if call_count == 0:
568 while not finish_join:
569 time.sleep(0.01) # WORKER THREAD FORKS HERE
570 with call_count_lock:
571 call_count += 1
572 condition.acquire = my_acquire
573
574 w.start()
575 w.join()
576 print('end of main')
577 """
578 self.assertScriptHasOutput(script, "end of main\n")
579
580 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner041d2e12011-07-01 15:04:03 +0200581 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000582 def test_5_clear_waiter_locks_to_avoid_crash(self):
583 # Check that a spawned thread that forks doesn't segfault on certain
584 # platforms, namely OS X. This used to happen if there was a waiter
585 # lock in the thread's condition variable's waiters list. Even though
586 # we know the lock will be held across the fork, it is not safe to
587 # release locks held across forks on all platforms, so releasing the
588 # waiter lock caused a segfault on OS X. Furthermore, since locks on
589 # OS X are (as of this writing) implemented with a mutex + condition
590 # variable instead of a semaphore, while we know that the Python-level
591 # lock will be acquired, we can't know if the internal mutex will be
592 # acquired at the time of the fork.
593
Gregory P. Smith2b79a812011-01-04 01:10:08 +0000594 script = """if True:
595 import os, time, threading
596
597 start_fork = False
598
599 def worker():
600 # Wait until the main thread has attempted to join this thread
601 # before continuing.
602 while not start_fork:
603 time.sleep(0.01)
604 childpid = os.fork()
605 if childpid != 0:
606 # Parent process just waits for child.
607 (cpid, rc) = os.waitpid(childpid, 0)
608 assert cpid == childpid
609 assert rc == 0
610 print('end of worker thread')
611 else:
612 # Child process should just return.
613 pass
614
615 w = threading.Thread(target=worker)
616
617 # Stub out the private condition variable's _release_save method.
618 # This releases the condition's lock and flips the global that
619 # causes the worker to fork. At this point, the problematic waiter
620 # lock has been acquired once by the waiter and has been put onto
621 # the waiters list.
622 condition = w._block
623 orig_release_save = condition._release_save
624 def my_release_save():
625 global start_fork
626 orig_release_save()
627 # Waiter lock held here, condition lock released.
628 start_fork = True
629 condition._release_save = my_release_save
630
631 w.start()
632 w.join()
633 print('end of main thread')
634 """
635 output = "end of worker thread\nend of main thread\n"
636 self.assertScriptHasOutput(script, output)
637
Charles-François Natalie0e88b02012-02-02 19:57:19 +0100638 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
639 def test_reinit_tls_after_fork(self):
640 # Issue #13817: fork() would deadlock in a multithreaded program with
641 # the ad-hoc TLS implementation.
642
643 def do_fork_and_wait():
644 # just fork a child process and wait it
645 pid = os.fork()
646 if pid > 0:
647 os.waitpid(pid, 0)
648 else:
649 os._exit(0)
650
651 # start a bunch of threads that will fork() child processes
652 threads = []
653 for i in range(16):
654 t = threading.Thread(target=do_fork_and_wait)
655 threads.append(t)
656 t.start()
657
658 for t in threads:
659 t.join()
660
Jesse Noller5e62ca42008-07-16 20:03:47 +0000661
Antoine Pitroubb0bb302009-10-27 20:02:23 +0000662class ThreadingExceptionTests(BaseTestCase):
Collin Winter50b79ce2007-06-06 00:17:35 +0000663 # A RuntimeError should be raised if Thread.start() is called
664 # multiple times.
665 def test_start_thread_again(self):
666 thread = threading.Thread()
667 thread.start()
668 self.assertRaises(RuntimeError, thread.start)
669
Collin Winter50b79ce2007-06-06 00:17:35 +0000670 def test_joining_current_thread(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000671 current_thread = threading.current_thread()
672 self.assertRaises(RuntimeError, current_thread.join);
Collin Winter50b79ce2007-06-06 00:17:35 +0000673
674 def test_joining_inactive_thread(self):
675 thread = threading.Thread()
676 self.assertRaises(RuntimeError, thread.join)
677
678 def test_daemonize_active_thread(self):
679 thread = threading.Thread()
680 thread.start()
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000681 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Collin Winter50b79ce2007-06-06 00:17:35 +0000682
683
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000684class LockTests(lock_tests.LockTests):
685 locktype = staticmethod(threading.Lock)
686
687class RLockTests(lock_tests.RLockTests):
688 locktype = staticmethod(threading.RLock)
689
690class EventTests(lock_tests.EventTests):
691 eventtype = staticmethod(threading.Event)
692
693class ConditionAsRLockTests(lock_tests.RLockTests):
694 # An Condition uses an RLock by default and exports its API.
695 locktype = staticmethod(threading.Condition)
696
697class ConditionTests(lock_tests.ConditionTests):
698 condtype = staticmethod(threading.Condition)
699
700class SemaphoreTests(lock_tests.SemaphoreTests):
701 semtype = staticmethod(threading.Semaphore)
702
703class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
704 semtype = staticmethod(threading.BoundedSemaphore)
705
Ned Deily482f9082011-05-28 00:11:54 -0700706 @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
707 def test_recursion_limit(self):
708 # Issue 9670
709 # test that excessive recursion within a non-main thread causes
710 # an exception rather than crashing the interpreter on platforms
711 # like Mac OS X or FreeBSD which have small default stack sizes
712 # for threads
713 script = """if True:
714 import threading
715
716 def recurse():
717 return recurse()
718
719 def outer():
720 try:
721 recurse()
722 except RuntimeError:
723 pass
724
725 w = threading.Thread(target=outer)
726 w.start()
727 w.join()
728 print('end of main thread')
729 """
730 expected_output = "end of main thread\n"
731 p = subprocess.Popen([sys.executable, "-c", script],
732 stdout=subprocess.PIPE)
733 stdout, stderr = p.communicate()
734 data = stdout.decode().replace('\r', '')
735 self.assertEqual(p.returncode, 0, "Unexpected error")
736 self.assertEqual(data, expected_output)
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000737
Tim Peters84d54892005-01-08 06:03:17 +0000738def test_main():
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000739 test.test_support.run_unittest(LockTests, RLockTests, EventTests,
740 ConditionAsRLockTests, ConditionTests,
741 SemaphoreTests, BoundedSemaphoreTests,
742 ThreadTests,
Jesse Noller5e62ca42008-07-16 20:03:47 +0000743 ThreadJoinOnShutdown,
744 ThreadingExceptionTests,
745 )
Tim Peters84d54892005-01-08 06:03:17 +0000746
747if __name__ == "__main__":
748 test_main()