blob: 04c3598cba953c6042b6b648954192850548e6b9 [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
Christian Heimes1af737c2008-01-23 08:24:23 +0000409
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000410class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000411
412 def _run_and_join(self, script):
413 script = """if 1:
414 import sys, os, time, threading
415
416 # a thread, which waits for the main program to terminate
417 def joiningfunc(mainthread):
418 mainthread.join()
419 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000420 # stdout is fully buffered because not a tty, we have to flush
421 # before exit.
422 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000423 \n""" + script
424
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200425 rc, out, err = assert_python_ok("-c", script)
426 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000427 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000428
429 def test_1_join_on_shutdown(self):
430 # The usual case: on exit, wait for a non-daemon thread
431 script = """if 1:
432 import os
433 t = threading.Thread(target=joiningfunc,
434 args=(threading.current_thread(),))
435 t.start()
436 time.sleep(0.1)
437 print('end of main')
438 """
439 self._run_and_join(script)
440
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000441 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000442 def test_2_join_in_forked_process(self):
443 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000444 script = """if 1:
445 childpid = os.fork()
446 if childpid != 0:
447 os.waitpid(childpid, 0)
448 sys.exit(0)
449
450 t = threading.Thread(target=joiningfunc,
451 args=(threading.current_thread(),))
452 t.start()
453 print('end of main')
454 """
455 self._run_and_join(script)
456
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000457 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000458 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000459 # Like the test above, but fork() was called from a worker thread
460 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000461
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000462 # Skip platforms with known problems forking from a worker thread.
463 # See http://bugs.python.org/issue3863.
Gregory P. Smithfeedda22010-10-17 03:09:12 +0000464 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
465 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000466 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000467 script = """if 1:
468 main_thread = threading.current_thread()
469 def worker():
470 childpid = os.fork()
471 if childpid != 0:
472 os.waitpid(childpid, 0)
473 sys.exit(0)
474
475 t = threading.Thread(target=joiningfunc,
476 args=(main_thread,))
477 print('end of main')
478 t.start()
479 t.join() # Should not block: main_thread is already stopped
480
481 w = threading.Thread(target=worker)
482 w.start()
483 """
484 self._run_and_join(script)
485
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000486 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200487 rc, out, err = assert_python_ok("-c", script)
488 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000489 self.assertEqual(data, expected_output)
490
491 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
492 def test_4_joining_across_fork_in_worker_thread(self):
493 # There used to be a possible deadlock when forking from a child
494 # thread. See http://bugs.python.org/issue6643.
495
496 # Skip platforms with known problems forking from a worker thread.
497 # See http://bugs.python.org/issue3863.
498 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
499 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
500
501 # The script takes the following steps:
502 # - The main thread in the parent process starts a new thread and then
503 # tries to join it.
504 # - The join operation acquires the Lock inside the thread's _block
505 # Condition. (See threading.py:Thread.join().)
506 # - We stub out the acquire method on the condition to force it to wait
507 # until the child thread forks. (See LOCK ACQUIRED HERE)
508 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
509 # HERE)
510 # - The main thread of the parent process enters Condition.wait(),
511 # which releases the lock on the child thread.
512 # - The child process returns. Without the necessary fix, when the
513 # main thread of the child process (which used to be the child thread
514 # in the parent process) attempts to exit, it will try to acquire the
515 # lock in the Thread._block Condition object and hang, because the
516 # lock was held across the fork.
517
518 script = """if 1:
519 import os, time, threading
520
521 finish_join = False
522 start_fork = False
523
524 def worker():
525 # Wait until this thread's lock is acquired before forking to
526 # create the deadlock.
527 global finish_join
528 while not start_fork:
529 time.sleep(0.01)
530 # LOCK HELD: Main thread holds lock across this call.
531 childpid = os.fork()
532 finish_join = True
533 if childpid != 0:
534 # Parent process just waits for child.
535 os.waitpid(childpid, 0)
536 # Child process should just return.
537
538 w = threading.Thread(target=worker)
539
540 # Stub out the private condition variable's lock acquire method.
541 # This acquires the lock and then waits until the child has forked
542 # before returning, which will release the lock soon after. If
543 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200544 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000545 # deadlock when it shouldn't.
546 condition = w._block
547 orig_acquire = condition.acquire
548 call_count_lock = threading.Lock()
549 call_count = 0
550 def my_acquire():
551 global call_count
552 global start_fork
553 orig_acquire() # LOCK ACQUIRED HERE
554 start_fork = True
555 if call_count == 0:
556 while not finish_join:
557 time.sleep(0.01) # WORKER THREAD FORKS HERE
558 with call_count_lock:
559 call_count += 1
560 condition.acquire = my_acquire
561
562 w.start()
563 w.join()
564 print('end of main')
565 """
566 self.assertScriptHasOutput(script, "end of main\n")
567
568 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
569 def test_5_clear_waiter_locks_to_avoid_crash(self):
570 # Check that a spawned thread that forks doesn't segfault on certain
571 # platforms, namely OS X. This used to happen if there was a waiter
572 # lock in the thread's condition variable's waiters list. Even though
573 # we know the lock will be held across the fork, it is not safe to
574 # release locks held across forks on all platforms, so releasing the
575 # waiter lock caused a segfault on OS X. Furthermore, since locks on
576 # OS X are (as of this writing) implemented with a mutex + condition
577 # variable instead of a semaphore, while we know that the Python-level
578 # lock will be acquired, we can't know if the internal mutex will be
579 # acquired at the time of the fork.
580
581 # Skip platforms with known problems forking from a worker thread.
582 # See http://bugs.python.org/issue3863.
583 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
584 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
585 script = """if True:
586 import os, time, threading
587
588 start_fork = False
589
590 def worker():
591 # Wait until the main thread has attempted to join this thread
592 # before continuing.
593 while not start_fork:
594 time.sleep(0.01)
595 childpid = os.fork()
596 if childpid != 0:
597 # Parent process just waits for child.
598 (cpid, rc) = os.waitpid(childpid, 0)
599 assert cpid == childpid
600 assert rc == 0
601 print('end of worker thread')
602 else:
603 # Child process should just return.
604 pass
605
606 w = threading.Thread(target=worker)
607
608 # Stub out the private condition variable's _release_save method.
609 # This releases the condition's lock and flips the global that
610 # causes the worker to fork. At this point, the problematic waiter
611 # lock has been acquired once by the waiter and has been put onto
612 # the waiters list.
613 condition = w._block
614 orig_release_save = condition._release_save
615 def my_release_save():
616 global start_fork
617 orig_release_save()
618 # Waiter lock held here, condition lock released.
619 start_fork = True
620 condition._release_save = my_release_save
621
622 w.start()
623 w.join()
624 print('end of main thread')
625 """
626 output = "end of worker thread\nend of main thread\n"
627 self.assertScriptHasOutput(script, output)
628
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200629 def test_6_daemon_threads(self):
630 # Check that a daemon thread cannot crash the interpreter on shutdown
631 # by manipulating internal structures that are being disposed of in
632 # the main thread.
633 script = """if True:
634 import os
635 import random
636 import sys
637 import time
638 import threading
639
640 thread_has_run = set()
641
642 def random_io():
643 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
644 blank = b'x' * 200
645 while True:
646 in_f = open(os.__file__, 'r')
647 stuff = in_f.read(200)
648 null_f = open(os.devnull, 'w')
649 null_f.write(stuff)
650 time.sleep(random.random() / 1995)
651 null_f.close()
652 in_f.close()
653 thread_has_run.add(threading.current_thread())
654
655 def main():
656 count = 0
657 for _ in range(40):
658 new_thread = threading.Thread(target=random_io)
659 new_thread.daemon = True
660 new_thread.start()
661 count += 1
662 while len(thread_has_run) < count:
663 time.sleep(0.001)
664 # Trigger process shutdown
665 sys.exit(0)
666
667 main()
668 """
669 rc, out, err = assert_python_ok('-c', script)
670 self.assertFalse(err)
671
Jesse Nollera8513972008-07-17 16:49:17 +0000672
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000673class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000674 # A RuntimeError should be raised if Thread.start() is called
675 # multiple times.
676 def test_start_thread_again(self):
677 thread = threading.Thread()
678 thread.start()
679 self.assertRaises(RuntimeError, thread.start)
680
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000681 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000682 current_thread = threading.current_thread()
683 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000684
685 def test_joining_inactive_thread(self):
686 thread = threading.Thread()
687 self.assertRaises(RuntimeError, thread.join)
688
689 def test_daemonize_active_thread(self):
690 thread = threading.Thread()
691 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000692 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000693
694
Antoine Pitrou557934f2009-11-06 22:41:14 +0000695class LockTests(lock_tests.LockTests):
696 locktype = staticmethod(threading.Lock)
697
Antoine Pitrou434736a2009-11-10 18:46:01 +0000698class PyRLockTests(lock_tests.RLockTests):
699 locktype = staticmethod(threading._PyRLock)
700
701class CRLockTests(lock_tests.RLockTests):
702 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000703
704class EventTests(lock_tests.EventTests):
705 eventtype = staticmethod(threading.Event)
706
707class ConditionAsRLockTests(lock_tests.RLockTests):
708 # An Condition uses an RLock by default and exports its API.
709 locktype = staticmethod(threading.Condition)
710
711class ConditionTests(lock_tests.ConditionTests):
712 condtype = staticmethod(threading.Condition)
713
714class SemaphoreTests(lock_tests.SemaphoreTests):
715 semtype = staticmethod(threading.Semaphore)
716
717class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
718 semtype = staticmethod(threading.BoundedSemaphore)
719
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000720class BarrierTests(lock_tests.BarrierTests):
721 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000722
Tim Peters84d54892005-01-08 06:03:17 +0000723def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000724 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000725 ConditionAsRLockTests, ConditionTests,
726 SemaphoreTests, BoundedSemaphoreTests,
727 ThreadTests,
728 ThreadJoinOnShutdown,
729 ThreadingExceptionTests,
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000730 BarrierTests
Antoine Pitrou557934f2009-11-06 22:41:14 +0000731 )
Tim Peters84d54892005-01-08 06:03:17 +0000732
733if __name__ == "__main__":
734 test_main()