blob: 2dc77733f758d0ccf116603bde51caf8f5652738 [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
Skip Montanaro4533f602001-08-20 20:28:48 +000015
Antoine Pitrou557934f2009-11-06 22:41:14 +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):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000038 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000039 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000040 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000041 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000042
Christian Heimes4fbc72b2008-03-22 00:47:35 +000043 with self.sema:
44 with self.mutex:
45 self.nrunning.inc()
46 if verbose:
47 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000048 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000049
Christian Heimes4fbc72b2008-03-22 00:47:35 +000050 time.sleep(delay)
51 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000052 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000053
Christian Heimes4fbc72b2008-03-22 00:47:35 +000054 with self.mutex:
55 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000056 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000057 if verbose:
58 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000059 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000060
Skip Montanaro4533f602001-08-20 20:28:48 +000061
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000062class BaseTestCase(unittest.TestCase):
63 def setUp(self):
64 self._threads = test.support.threading_setup()
65
66 def tearDown(self):
67 test.support.threading_cleanup(*self._threads)
68 test.support.reap_children()
69
70
71class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000072
Tim Peters84d54892005-01-08 06:03:17 +000073 # Create a bunch of threads, let each do some work, wait until all are
74 # done.
75 def test_various_ops(self):
76 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
77 # times about 1 second per clump).
78 NUMTASKS = 10
79
80 # no more than 3 of the 10 can run at once
81 sema = threading.BoundedSemaphore(value=3)
82 mutex = threading.RLock()
83 numrunning = Counter()
84
85 threads = []
86
87 for i in range(NUMTASKS):
88 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
89 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000090 self.assertEqual(t.ident, None)
91 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000092 t.start()
93
94 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000095 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000096 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000097 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000098 self.assertTrue(not t.is_alive())
99 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000100 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000101 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
102 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000103 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000105 self.assertEqual(numrunning.get(), 0)
106
Benjamin Petersond23f8222009-04-05 19:13:16 +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 Pitrouca13a0d2009-11-08 00:30:04 +0000118 # Kill the "immortal" _DummyThread
119 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000120
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000121 # run with a small(ish) thread stack size (256kB)
122 def test_various_ops_small_stack(self):
123 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000124 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125 try:
126 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000127 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000128 raise unittest.SkipTest(
129 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 self.test_various_ops()
131 threading.stack_size(0)
132
133 # run with a large thread stack size (1MB)
134 def test_various_ops_large_stack(self):
135 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000136 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 try:
138 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000139 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000140 raise unittest.SkipTest(
141 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 Pitroub0872682009-11-09 16:08:16 +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 Pitroub0872682009-11-09 16:08:16 +0000150 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000151 mutex.release()
152
153 mutex = threading.Lock()
154 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000155 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000156 # Wait for the thread to finish.
157 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000158 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +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
Thomas Wouters00ee7ba2006-08-21 19:07:27 +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):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200165 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000166
167 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
168
169 class AsyncExc(Exception):
170 pass
171
172 exception = ctypes.py_object(AsyncExc)
173
Antoine Pitroube4d8092009-10-18 18:27:17 +0000174 # First check it works when setting the exception from the same thread.
175 tid = _thread.get_ident()
176
177 try:
178 result = set_async_exc(ctypes.c_long(tid), exception)
179 # The exception is async, so we might have to keep the VM busy until
180 # it notices.
181 while True:
182 pass
183 except AsyncExc:
184 pass
185 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000186 # This code is unreachable but it reflects the intent. If we wanted
187 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000188 self.fail("AsyncExc not raised")
189 try:
190 self.assertEqual(result, 1) # one thread state modified
191 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000192 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000193 pass
194
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000195 # `worker_started` is set by the thread when it's inside a try/except
196 # block waiting to catch the asynchronously set AsyncExc exception.
197 # `worker_saw_exception` is set by the thread upon catching that
198 # exception.
199 worker_started = threading.Event()
200 worker_saw_exception = threading.Event()
201
202 class Worker(threading.Thread):
203 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000204 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000205 self.finished = False
206
207 try:
208 while True:
209 worker_started.set()
210 time.sleep(0.1)
211 except AsyncExc:
212 self.finished = True
213 worker_saw_exception.set()
214
215 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000216 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000217 t.start()
218 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220
221 # Try a thread id that doesn't make sense.
222 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000223 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000224 result = set_async_exc(ctypes.c_long(-1), exception)
225 self.assertEqual(result, 0) # no thread states modified
226
227 # Now raise an exception in the worker thread.
228 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000230 ret = worker_started.wait()
231 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000233 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000234 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000235 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000236 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000237 result = set_async_exc(ctypes.c_long(t.id), exception)
238 self.assertEqual(result, 1) # one thread state modified
239 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000242 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000243 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 if t.finished:
246 t.join()
247 # else the thread is still running, and we have no way to kill it
248
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000249 def test_limbo_cleanup(self):
250 # Issue 7481: Failure to start thread should cleanup the limbo map.
251 def fail_new_thread(*args):
252 raise threading.ThreadError()
253 _start_new_thread = threading._start_new_thread
254 threading._start_new_thread = fail_new_thread
255 try:
256 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000257 self.assertRaises(threading.ThreadError, t.start)
258 self.assertFalse(
259 t in threading._limbo,
260 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000261 finally:
262 threading._start_new_thread = _start_new_thread
263
Christian Heimes7d2ff882007-11-30 14:35:04 +0000264 def test_finalize_runnning_thread(self):
265 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
266 # very late on python exit: on deallocation of a running thread for
267 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200268 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000269
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200270 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000271 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000272
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000273 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000274 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000275 ready.acquire()
276
Christian Heimes7d2ff882007-11-30 14:35:04 +0000277 # Module globals are cleared before __del__ is run
278 # So we save the functions in class dict
279 class C:
280 ensure = ctypes.pythonapi.PyGILState_Ensure
281 release = ctypes.pythonapi.PyGILState_Release
282 def __del__(self):
283 state = self.ensure()
284 self.release(state)
285
286 def waitingThread():
287 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000288 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000289 time.sleep(100)
290
Georg Brandl2067bfd2008-05-25 13:05:15 +0000291 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000292 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000293 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200294 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000295 self.assertEqual(rc, 42)
296
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000297 def test_finalize_with_trace(self):
298 # Issue1733757
299 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200300 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000301 import sys, threading
302
303 # A deadlock-killer, to prevent the
304 # testsuite to hang forever
305 def killer():
306 import os, time
307 time.sleep(2)
308 print('program blocked; aborting')
309 os._exit(2)
310 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000311 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000312 t.start()
313
314 # This is the trace function
315 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000316 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000317 return func
318
319 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200320 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000321
Antoine Pitrou011bd622009-10-20 21:52:47 +0000322 def test_join_nondaemon_on_shutdown(self):
323 # Issue 1722344
324 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200325 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000326 import threading
327 from time import sleep
328
329 def child():
330 sleep(1)
331 # As a non-daemon thread we SHOULD wake up and nothing
332 # should be torn down yet
333 print("Woke up, sleep function is:", sleep)
334
335 threading.Thread(target=child).start()
336 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200337 """)
338 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000339 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200340 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000341
Christian Heimes1af737c2008-01-23 08:24:23 +0000342 def test_enumerate_after_join(self):
343 # Try hard to trigger #1703448: a thread is still returned in
344 # threading.enumerate() after it has been join()ed.
345 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000346 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000347 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000348 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000349 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000350 t = threading.Thread(target=lambda: None)
351 t.start()
352 t.join()
353 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000354 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000355 "#1703448 triggered after %d trials: %s" % (i, l))
356 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000357 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000358
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000359 def test_no_refcycle_through_target(self):
360 class RunSelfFunction(object):
361 def __init__(self, should_raise):
362 # The links in this refcycle from Thread back to self
363 # should be cleaned up when the thread completes.
364 self.should_raise = should_raise
365 self.thread = threading.Thread(target=self._run,
366 args=(self,),
367 kwargs={'yet_another':self})
368 self.thread.start()
369
370 def _run(self, other_ref, yet_another):
371 if self.should_raise:
372 raise SystemExit
373
374 cyclic_object = RunSelfFunction(should_raise=False)
375 weak_cyclic_object = weakref.ref(cyclic_object)
376 cyclic_object.thread.join()
377 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000378 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000379 msg=('%d references still around' %
380 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000381
382 raising_cyclic_object = RunSelfFunction(should_raise=True)
383 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
384 raising_cyclic_object.thread.join()
385 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000386 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000387 msg=('%d references still around' %
388 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000389
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000390 def test_old_threading_api(self):
391 # Just a quick sanity check to make sure the old method names are
392 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000393 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000394 t.isDaemon()
395 t.setDaemon(True)
396 t.getName()
397 t.setName("name")
398 t.isAlive()
399 e = threading.Event()
400 e.isSet()
401 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000402
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000403 def test_repr_daemon(self):
404 t = threading.Thread()
405 self.assertFalse('daemon' in repr(t))
406 t.daemon = True
407 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000408
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000409 def test_deamon_param(self):
410 t = threading.Thread()
411 self.assertFalse(t.daemon)
412 t = threading.Thread(daemon=False)
413 self.assertFalse(t.daemon)
414 t = threading.Thread(daemon=True)
415 self.assertTrue(t.daemon)
416
Christian Heimes1af737c2008-01-23 08:24:23 +0000417
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000418class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000419
420 def _run_and_join(self, script):
421 script = """if 1:
422 import sys, os, time, threading
423
424 # a thread, which waits for the main program to terminate
425 def joiningfunc(mainthread):
426 mainthread.join()
427 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000428 # stdout is fully buffered because not a tty, we have to flush
429 # before exit.
430 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000431 \n""" + script
432
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200433 rc, out, err = assert_python_ok("-c", script)
434 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000435 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000436
437 def test_1_join_on_shutdown(self):
438 # The usual case: on exit, wait for a non-daemon thread
439 script = """if 1:
440 import os
441 t = threading.Thread(target=joiningfunc,
442 args=(threading.current_thread(),))
443 t.start()
444 time.sleep(0.1)
445 print('end of main')
446 """
447 self._run_and_join(script)
448
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000449 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000450 def test_2_join_in_forked_process(self):
451 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000452 script = """if 1:
453 childpid = os.fork()
454 if childpid != 0:
455 os.waitpid(childpid, 0)
456 sys.exit(0)
457
458 t = threading.Thread(target=joiningfunc,
459 args=(threading.current_thread(),))
460 t.start()
461 print('end of main')
462 """
463 self._run_and_join(script)
464
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000465 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000466 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000467 # Like the test above, but fork() was called from a worker thread
468 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000469
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000470 # Skip platforms with known problems forking from a worker thread.
471 # See http://bugs.python.org/issue3863.
Gregory P. Smithfeedda22010-10-17 03:09:12 +0000472 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
473 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000474 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000475 script = """if 1:
476 main_thread = threading.current_thread()
477 def worker():
478 childpid = os.fork()
479 if childpid != 0:
480 os.waitpid(childpid, 0)
481 sys.exit(0)
482
483 t = threading.Thread(target=joiningfunc,
484 args=(main_thread,))
485 print('end of main')
486 t.start()
487 t.join() # Should not block: main_thread is already stopped
488
489 w = threading.Thread(target=worker)
490 w.start()
491 """
492 self._run_and_join(script)
493
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000494 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200495 rc, out, err = assert_python_ok("-c", script)
496 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000497 self.assertEqual(data, expected_output)
498
499 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
500 def test_4_joining_across_fork_in_worker_thread(self):
501 # There used to be a possible deadlock when forking from a child
502 # thread. See http://bugs.python.org/issue6643.
503
504 # Skip platforms with known problems forking from a worker thread.
505 # See http://bugs.python.org/issue3863.
506 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
507 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
508
509 # The script takes the following steps:
510 # - The main thread in the parent process starts a new thread and then
511 # tries to join it.
512 # - The join operation acquires the Lock inside the thread's _block
513 # Condition. (See threading.py:Thread.join().)
514 # - We stub out the acquire method on the condition to force it to wait
515 # until the child thread forks. (See LOCK ACQUIRED HERE)
516 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
517 # HERE)
518 # - The main thread of the parent process enters Condition.wait(),
519 # which releases the lock on the child thread.
520 # - The child process returns. Without the necessary fix, when the
521 # main thread of the child process (which used to be the child thread
522 # in the parent process) attempts to exit, it will try to acquire the
523 # lock in the Thread._block Condition object and hang, because the
524 # lock was held across the fork.
525
526 script = """if 1:
527 import os, time, threading
528
529 finish_join = False
530 start_fork = False
531
532 def worker():
533 # Wait until this thread's lock is acquired before forking to
534 # create the deadlock.
535 global finish_join
536 while not start_fork:
537 time.sleep(0.01)
538 # LOCK HELD: Main thread holds lock across this call.
539 childpid = os.fork()
540 finish_join = True
541 if childpid != 0:
542 # Parent process just waits for child.
543 os.waitpid(childpid, 0)
544 # Child process should just return.
545
546 w = threading.Thread(target=worker)
547
548 # Stub out the private condition variable's lock acquire method.
549 # This acquires the lock and then waits until the child has forked
550 # before returning, which will release the lock soon after. If
551 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200552 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000553 # deadlock when it shouldn't.
554 condition = w._block
555 orig_acquire = condition.acquire
556 call_count_lock = threading.Lock()
557 call_count = 0
558 def my_acquire():
559 global call_count
560 global start_fork
561 orig_acquire() # LOCK ACQUIRED HERE
562 start_fork = True
563 if call_count == 0:
564 while not finish_join:
565 time.sleep(0.01) # WORKER THREAD FORKS HERE
566 with call_count_lock:
567 call_count += 1
568 condition.acquire = my_acquire
569
570 w.start()
571 w.join()
572 print('end of main')
573 """
574 self.assertScriptHasOutput(script, "end of main\n")
575
576 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
577 def test_5_clear_waiter_locks_to_avoid_crash(self):
578 # Check that a spawned thread that forks doesn't segfault on certain
579 # platforms, namely OS X. This used to happen if there was a waiter
580 # lock in the thread's condition variable's waiters list. Even though
581 # we know the lock will be held across the fork, it is not safe to
582 # release locks held across forks on all platforms, so releasing the
583 # waiter lock caused a segfault on OS X. Furthermore, since locks on
584 # OS X are (as of this writing) implemented with a mutex + condition
585 # variable instead of a semaphore, while we know that the Python-level
586 # lock will be acquired, we can't know if the internal mutex will be
587 # acquired at the time of the fork.
588
589 # Skip platforms with known problems forking from a worker thread.
590 # See http://bugs.python.org/issue3863.
591 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
592 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
593 script = """if True:
594 import os, time, threading
595
596 start_fork = False
597
598 def worker():
599 # Wait until the main thread has attempted to join this thread
600 # before continuing.
601 while not start_fork:
602 time.sleep(0.01)
603 childpid = os.fork()
604 if childpid != 0:
605 # Parent process just waits for child.
606 (cpid, rc) = os.waitpid(childpid, 0)
607 assert cpid == childpid
608 assert rc == 0
609 print('end of worker thread')
610 else:
611 # Child process should just return.
612 pass
613
614 w = threading.Thread(target=worker)
615
616 # Stub out the private condition variable's _release_save method.
617 # This releases the condition's lock and flips the global that
618 # causes the worker to fork. At this point, the problematic waiter
619 # lock has been acquired once by the waiter and has been put onto
620 # the waiters list.
621 condition = w._block
622 orig_release_save = condition._release_save
623 def my_release_save():
624 global start_fork
625 orig_release_save()
626 # Waiter lock held here, condition lock released.
627 start_fork = True
628 condition._release_save = my_release_save
629
630 w.start()
631 w.join()
632 print('end of main thread')
633 """
634 output = "end of worker thread\nend of main thread\n"
635 self.assertScriptHasOutput(script, output)
636
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200637 def test_6_daemon_threads(self):
638 # Check that a daemon thread cannot crash the interpreter on shutdown
639 # by manipulating internal structures that are being disposed of in
640 # the main thread.
641 script = """if True:
642 import os
643 import random
644 import sys
645 import time
646 import threading
647
648 thread_has_run = set()
649
650 def random_io():
651 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
652 blank = b'x' * 200
653 while True:
654 in_f = open(os.__file__, 'r')
655 stuff = in_f.read(200)
656 null_f = open(os.devnull, 'w')
657 null_f.write(stuff)
658 time.sleep(random.random() / 1995)
659 null_f.close()
660 in_f.close()
661 thread_has_run.add(threading.current_thread())
662
663 def main():
664 count = 0
665 for _ in range(40):
666 new_thread = threading.Thread(target=random_io)
667 new_thread.daemon = True
668 new_thread.start()
669 count += 1
670 while len(thread_has_run) < count:
671 time.sleep(0.001)
672 # Trigger process shutdown
673 sys.exit(0)
674
675 main()
676 """
677 rc, out, err = assert_python_ok('-c', script)
678 self.assertFalse(err)
679
Jesse Nollera8513972008-07-17 16:49:17 +0000680
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000681class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000682 # A RuntimeError should be raised if Thread.start() is called
683 # multiple times.
684 def test_start_thread_again(self):
685 thread = threading.Thread()
686 thread.start()
687 self.assertRaises(RuntimeError, thread.start)
688
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000689 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000690 current_thread = threading.current_thread()
691 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000692
693 def test_joining_inactive_thread(self):
694 thread = threading.Thread()
695 self.assertRaises(RuntimeError, thread.join)
696
697 def test_daemonize_active_thread(self):
698 thread = threading.Thread()
699 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000700 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000701
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000702 def test_releasing_unacquired_lock(self):
703 lock = threading.Lock()
704 self.assertRaises(RuntimeError, lock.release)
705
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000706
Antoine Pitrou557934f2009-11-06 22:41:14 +0000707class LockTests(lock_tests.LockTests):
708 locktype = staticmethod(threading.Lock)
709
Antoine Pitrou434736a2009-11-10 18:46:01 +0000710class PyRLockTests(lock_tests.RLockTests):
711 locktype = staticmethod(threading._PyRLock)
712
713class CRLockTests(lock_tests.RLockTests):
714 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000715
716class EventTests(lock_tests.EventTests):
717 eventtype = staticmethod(threading.Event)
718
719class ConditionAsRLockTests(lock_tests.RLockTests):
720 # An Condition uses an RLock by default and exports its API.
721 locktype = staticmethod(threading.Condition)
722
723class ConditionTests(lock_tests.ConditionTests):
724 condtype = staticmethod(threading.Condition)
725
726class SemaphoreTests(lock_tests.SemaphoreTests):
727 semtype = staticmethod(threading.Semaphore)
728
729class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
730 semtype = staticmethod(threading.BoundedSemaphore)
731
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000732class BarrierTests(lock_tests.BarrierTests):
733 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000734
Victor Stinner754851f2011-04-19 23:58:51 +0200735
Tim Peters84d54892005-01-08 06:03:17 +0000736def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000737 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000738 ConditionAsRLockTests, ConditionTests,
739 SemaphoreTests, BoundedSemaphoreTests,
740 ThreadTests,
741 ThreadJoinOnShutdown,
742 ThreadingExceptionTests,
Victor Stinnerd5c355c2011-04-30 14:53:09 +0200743 BarrierTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000744 )
Tim Peters84d54892005-01-08 06:03:17 +0000745
746if __name__ == "__main__":
747 test_main()