blob: 00f73a7f023360e66b4ac3b1cf5a20c10cbe9e35 [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
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02005from test.script_helper import assert_python_ok
6
Skip Montanaro4533f602001-08-20 20:28:48 +00007import random
Georg Brandl0c77a822008-06-10 16:37:50 +00008import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +00009import sys
Antoine Pitrouc4d78642011-05-05 20:17:32 +020010_thread = import_module('_thread')
11threading = import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000012import time
Tim Peters84d54892005-01-08 06:03:17 +000013import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000014import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000015import os
Antoine Pitrouc4d78642011-05-05 20:17:32 +020016from test.script_helper import assert_python_ok, assert_python_failure
Gregory P. Smith4b129d22011-01-04 00:51:50 +000017import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000018
Antoine Pitrou557934f2009-11-06 22:41:14 +000019from test import lock_tests
20
Tim Peters84d54892005-01-08 06:03:17 +000021# A trivial mutable counter.
22class Counter(object):
23 def __init__(self):
24 self.value = 0
25 def inc(self):
26 self.value += 1
27 def dec(self):
28 self.value -= 1
29 def get(self):
30 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000031
32class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000033 def __init__(self, name, testcase, sema, mutex, nrunning):
34 threading.Thread.__init__(self, name=name)
35 self.testcase = testcase
36 self.sema = sema
37 self.mutex = mutex
38 self.nrunning = nrunning
39
Skip Montanaro4533f602001-08-20 20:28:48 +000040 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000041 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000042 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000043 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000044 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000045
Christian Heimes4fbc72b2008-03-22 00:47:35 +000046 with self.sema:
47 with self.mutex:
48 self.nrunning.inc()
49 if verbose:
50 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000051 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000052
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 time.sleep(delay)
54 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000055 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000056
Christian Heimes4fbc72b2008-03-22 00:47:35 +000057 with self.mutex:
58 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000059 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000060 if verbose:
61 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000062 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000063
Skip Montanaro4533f602001-08-20 20:28:48 +000064
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000065class BaseTestCase(unittest.TestCase):
66 def setUp(self):
67 self._threads = test.support.threading_setup()
68
69 def tearDown(self):
70 test.support.threading_cleanup(*self._threads)
71 test.support.reap_children()
72
73
74class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000075
Tim Peters84d54892005-01-08 06:03:17 +000076 # Create a bunch of threads, let each do some work, wait until all are
77 # done.
78 def test_various_ops(self):
79 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
80 # times about 1 second per clump).
81 NUMTASKS = 10
82
83 # no more than 3 of the 10 can run at once
84 sema = threading.BoundedSemaphore(value=3)
85 mutex = threading.RLock()
86 numrunning = Counter()
87
88 threads = []
89
90 for i in range(NUMTASKS):
91 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
92 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000093 self.assertEqual(t.ident, None)
94 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000095 t.start()
96
97 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000098 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000099 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +0000100 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000101 self.assertTrue(not t.is_alive())
102 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000103 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000104 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
105 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000106 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000107 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000108 self.assertEqual(numrunning.get(), 0)
109
Benjamin Petersond23f8222009-04-05 19:13:16 +0000110 def test_ident_of_no_threading_threads(self):
111 # The ident still must work for the main thread and dummy threads.
112 self.assertFalse(threading.currentThread().ident is None)
113 def f():
114 ident.append(threading.currentThread().ident)
115 done.set()
116 done = threading.Event()
117 ident = []
118 _thread.start_new_thread(f, ())
119 done.wait()
120 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000121 # Kill the "immortal" _DummyThread
122 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000123
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124 # run with a small(ish) thread stack size (256kB)
125 def test_various_ops_small_stack(self):
126 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000127 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000128 try:
129 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000130 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000131 raise unittest.SkipTest(
132 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000133 self.test_various_ops()
134 threading.stack_size(0)
135
136 # run with a large thread stack size (1MB)
137 def test_various_ops_large_stack(self):
138 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000139 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140 try:
141 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000142 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000143 raise unittest.SkipTest(
144 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 self.test_various_ops()
146 threading.stack_size(0)
147
Tim Peters711906e2005-01-08 07:30:42 +0000148 def test_foreign_thread(self):
149 # Check that a "foreign" thread can use the threading module.
150 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000151 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000152 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000153 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000154 mutex.release()
155
156 mutex = threading.Lock()
157 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000158 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000159 # Wait for the thread to finish.
160 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000161 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000162 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000163 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000164
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000165 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
166 # exposed at the Python level. This test relies on ctypes to get at it.
167 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200168 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000169
170 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
171
172 class AsyncExc(Exception):
173 pass
174
175 exception = ctypes.py_object(AsyncExc)
176
Antoine Pitroube4d8092009-10-18 18:27:17 +0000177 # First check it works when setting the exception from the same thread.
178 tid = _thread.get_ident()
179
180 try:
181 result = set_async_exc(ctypes.c_long(tid), exception)
182 # The exception is async, so we might have to keep the VM busy until
183 # it notices.
184 while True:
185 pass
186 except AsyncExc:
187 pass
188 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000189 # This code is unreachable but it reflects the intent. If we wanted
190 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000191 self.fail("AsyncExc not raised")
192 try:
193 self.assertEqual(result, 1) # one thread state modified
194 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000195 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000196 pass
197
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000198 # `worker_started` is set by the thread when it's inside a try/except
199 # block waiting to catch the asynchronously set AsyncExc exception.
200 # `worker_saw_exception` is set by the thread upon catching that
201 # exception.
202 worker_started = threading.Event()
203 worker_saw_exception = threading.Event()
204
205 class Worker(threading.Thread):
206 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000207 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000208 self.finished = False
209
210 try:
211 while True:
212 worker_started.set()
213 time.sleep(0.1)
214 except AsyncExc:
215 self.finished = True
216 worker_saw_exception.set()
217
218 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000219 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220 t.start()
221 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000222 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000223
224 # Try a thread id that doesn't make sense.
225 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000226 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000227 result = set_async_exc(ctypes.c_long(-1), exception)
228 self.assertEqual(result, 0) # no thread states modified
229
230 # Now raise an exception in the worker thread.
231 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000232 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000233 ret = worker_started.wait()
234 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000235 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000236 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000237 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000238 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000240 result = set_async_exc(ctypes.c_long(t.id), exception)
241 self.assertEqual(result, 1) # one thread state modified
242 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000245 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000248 if t.finished:
249 t.join()
250 # else the thread is still running, and we have no way to kill it
251
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000252 def test_limbo_cleanup(self):
253 # Issue 7481: Failure to start thread should cleanup the limbo map.
254 def fail_new_thread(*args):
255 raise threading.ThreadError()
256 _start_new_thread = threading._start_new_thread
257 threading._start_new_thread = fail_new_thread
258 try:
259 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000260 self.assertRaises(threading.ThreadError, t.start)
261 self.assertFalse(
262 t in threading._limbo,
263 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000264 finally:
265 threading._start_new_thread = _start_new_thread
266
Christian Heimes7d2ff882007-11-30 14:35:04 +0000267 def test_finalize_runnning_thread(self):
268 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
269 # very late on python exit: on deallocation of a running thread for
270 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200271 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000272
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200273 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000274 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000275
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000276 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000277 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000278 ready.acquire()
279
Christian Heimes7d2ff882007-11-30 14:35:04 +0000280 # Module globals are cleared before __del__ is run
281 # So we save the functions in class dict
282 class C:
283 ensure = ctypes.pythonapi.PyGILState_Ensure
284 release = ctypes.pythonapi.PyGILState_Release
285 def __del__(self):
286 state = self.ensure()
287 self.release(state)
288
289 def waitingThread():
290 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000291 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000292 time.sleep(100)
293
Georg Brandl2067bfd2008-05-25 13:05:15 +0000294 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000295 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200297 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000298 self.assertEqual(rc, 42)
299
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000300 def test_finalize_with_trace(self):
301 # Issue1733757
302 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200303 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000304 import sys, threading
305
306 # A deadlock-killer, to prevent the
307 # testsuite to hang forever
308 def killer():
309 import os, time
310 time.sleep(2)
311 print('program blocked; aborting')
312 os._exit(2)
313 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000314 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000315 t.start()
316
317 # This is the trace function
318 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000319 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000320 return func
321
322 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200323 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324
Antoine Pitrou011bd622009-10-20 21:52:47 +0000325 def test_join_nondaemon_on_shutdown(self):
326 # Issue 1722344
327 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200328 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000329 import threading
330 from time import sleep
331
332 def child():
333 sleep(1)
334 # As a non-daemon thread we SHOULD wake up and nothing
335 # should be torn down yet
336 print("Woke up, sleep function is:", sleep)
337
338 threading.Thread(target=child).start()
339 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200340 """)
341 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000342 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200343 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000344
Christian Heimes1af737c2008-01-23 08:24:23 +0000345 def test_enumerate_after_join(self):
346 # Try hard to trigger #1703448: a thread is still returned in
347 # threading.enumerate() after it has been join()ed.
348 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000349 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000350 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000351 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000352 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000353 t = threading.Thread(target=lambda: None)
354 t.start()
355 t.join()
356 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000357 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000358 "#1703448 triggered after %d trials: %s" % (i, l))
359 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000360 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000361
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000362 def test_no_refcycle_through_target(self):
363 class RunSelfFunction(object):
364 def __init__(self, should_raise):
365 # The links in this refcycle from Thread back to self
366 # should be cleaned up when the thread completes.
367 self.should_raise = should_raise
368 self.thread = threading.Thread(target=self._run,
369 args=(self,),
370 kwargs={'yet_another':self})
371 self.thread.start()
372
373 def _run(self, other_ref, yet_another):
374 if self.should_raise:
375 raise SystemExit
376
377 cyclic_object = RunSelfFunction(should_raise=False)
378 weak_cyclic_object = weakref.ref(cyclic_object)
379 cyclic_object.thread.join()
380 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000381 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000382 msg=('%d references still around' %
383 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000384
385 raising_cyclic_object = RunSelfFunction(should_raise=True)
386 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
387 raising_cyclic_object.thread.join()
388 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000389 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000390 msg=('%d references still around' %
391 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000392
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000393 def test_old_threading_api(self):
394 # Just a quick sanity check to make sure the old method names are
395 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000396 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000397 t.isDaemon()
398 t.setDaemon(True)
399 t.getName()
400 t.setName("name")
401 t.isAlive()
402 e = threading.Event()
403 e.isSet()
404 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000405
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000406 def test_repr_daemon(self):
407 t = threading.Thread()
408 self.assertFalse('daemon' in repr(t))
409 t.daemon = True
410 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000411
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200412 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
413 def test_dummy_thread_after_fork(self):
414 # Issue #14308: a dummy thread in the active list doesn't mess up
415 # the after-fork mechanism.
416 code = """if 1:
417 import _thread, threading, os, time
418
419 def background_thread(evt):
420 # Creates and registers the _DummyThread instance
421 threading.current_thread()
422 evt.set()
423 time.sleep(10)
424
425 evt = threading.Event()
426 _thread.start_new_thread(background_thread, (evt,))
427 evt.wait()
428 assert threading.active_count() == 2, threading.active_count()
429 if os.fork() == 0:
430 assert threading.active_count() == 1, threading.active_count()
431 os._exit(0)
432 else:
433 os.wait()
434 """
435 _, out, err = assert_python_ok("-c", code)
436 self.assertEqual(out, b'')
437 self.assertEqual(err, b'')
438
Christian Heimes1af737c2008-01-23 08:24:23 +0000439
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000440class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000441
Victor Stinner26d31862011-07-01 14:26:24 +0200442 # Between fork() and exec(), only async-safe functions are allowed (issues
443 # #12316 and #11870), and fork() from a worker thread is known to trigger
444 # problems with some operating systems (issue #3863): skip problematic tests
445 # on platforms known to behave badly.
446 platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
447 'os2emx')
448
Jesse Nollera8513972008-07-17 16:49:17 +0000449 def _run_and_join(self, script):
450 script = """if 1:
451 import sys, os, time, threading
452
453 # a thread, which waits for the main program to terminate
454 def joiningfunc(mainthread):
455 mainthread.join()
456 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000457 # stdout is fully buffered because not a tty, we have to flush
458 # before exit.
459 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000460 \n""" + script
461
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200462 rc, out, err = assert_python_ok("-c", script)
463 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000464 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000465
466 def test_1_join_on_shutdown(self):
467 # The usual case: on exit, wait for a non-daemon thread
468 script = """if 1:
469 import os
470 t = threading.Thread(target=joiningfunc,
471 args=(threading.current_thread(),))
472 t.start()
473 time.sleep(0.1)
474 print('end of main')
475 """
476 self._run_and_join(script)
477
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000478 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200479 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000480 def test_2_join_in_forked_process(self):
481 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000482 script = """if 1:
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=(threading.current_thread(),))
490 t.start()
491 print('end of main')
492 """
493 self._run_and_join(script)
494
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000495 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200496 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000497 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000498 # Like the test above, but fork() was called from a worker thread
499 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000500
Jesse Nollera8513972008-07-17 16:49:17 +0000501 script = """if 1:
502 main_thread = threading.current_thread()
503 def worker():
504 childpid = os.fork()
505 if childpid != 0:
506 os.waitpid(childpid, 0)
507 sys.exit(0)
508
509 t = threading.Thread(target=joiningfunc,
510 args=(main_thread,))
511 print('end of main')
512 t.start()
513 t.join() # Should not block: main_thread is already stopped
514
515 w = threading.Thread(target=worker)
516 w.start()
517 """
518 self._run_and_join(script)
519
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000520 def assertScriptHasOutput(self, script, expected_output):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200521 rc, out, err = assert_python_ok("-c", script)
522 data = out.decode().replace('\r', '')
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000523 self.assertEqual(data, expected_output)
524
525 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200526 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000527 def test_4_joining_across_fork_in_worker_thread(self):
528 # There used to be a possible deadlock when forking from a child
529 # thread. See http://bugs.python.org/issue6643.
530
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000531 # The script takes the following steps:
532 # - The main thread in the parent process starts a new thread and then
533 # tries to join it.
534 # - The join operation acquires the Lock inside the thread's _block
535 # Condition. (See threading.py:Thread.join().)
536 # - We stub out the acquire method on the condition to force it to wait
537 # until the child thread forks. (See LOCK ACQUIRED HERE)
538 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
539 # HERE)
540 # - The main thread of the parent process enters Condition.wait(),
541 # which releases the lock on the child thread.
542 # - The child process returns. Without the necessary fix, when the
543 # main thread of the child process (which used to be the child thread
544 # in the parent process) attempts to exit, it will try to acquire the
545 # lock in the Thread._block Condition object and hang, because the
546 # lock was held across the fork.
547
548 script = """if 1:
549 import os, time, threading
550
551 finish_join = False
552 start_fork = False
553
554 def worker():
555 # Wait until this thread's lock is acquired before forking to
556 # create the deadlock.
557 global finish_join
558 while not start_fork:
559 time.sleep(0.01)
560 # LOCK HELD: Main thread holds lock across this call.
561 childpid = os.fork()
562 finish_join = True
563 if childpid != 0:
564 # Parent process just waits for child.
565 os.waitpid(childpid, 0)
566 # Child process should just return.
567
568 w = threading.Thread(target=worker)
569
570 # Stub out the private condition variable's lock acquire method.
571 # This acquires the lock and then waits until the child has forked
572 # before returning, which will release the lock soon after. If
573 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200574 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000575 # deadlock when it shouldn't.
576 condition = w._block
577 orig_acquire = condition.acquire
578 call_count_lock = threading.Lock()
579 call_count = 0
580 def my_acquire():
581 global call_count
582 global start_fork
583 orig_acquire() # LOCK ACQUIRED HERE
584 start_fork = True
585 if call_count == 0:
586 while not finish_join:
587 time.sleep(0.01) # WORKER THREAD FORKS HERE
588 with call_count_lock:
589 call_count += 1
590 condition.acquire = my_acquire
591
592 w.start()
593 w.join()
594 print('end of main')
595 """
596 self.assertScriptHasOutput(script, "end of main\n")
597
598 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200599 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000600 def test_5_clear_waiter_locks_to_avoid_crash(self):
601 # Check that a spawned thread that forks doesn't segfault on certain
602 # platforms, namely OS X. This used to happen if there was a waiter
603 # lock in the thread's condition variable's waiters list. Even though
604 # we know the lock will be held across the fork, it is not safe to
605 # release locks held across forks on all platforms, so releasing the
606 # waiter lock caused a segfault on OS X. Furthermore, since locks on
607 # OS X are (as of this writing) implemented with a mutex + condition
608 # variable instead of a semaphore, while we know that the Python-level
609 # lock will be acquired, we can't know if the internal mutex will be
610 # acquired at the time of the fork.
611
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000612 script = """if True:
613 import os, time, threading
614
615 start_fork = False
616
617 def worker():
618 # Wait until the main thread has attempted to join this thread
619 # before continuing.
620 while not start_fork:
621 time.sleep(0.01)
622 childpid = os.fork()
623 if childpid != 0:
624 # Parent process just waits for child.
625 (cpid, rc) = os.waitpid(childpid, 0)
626 assert cpid == childpid
627 assert rc == 0
628 print('end of worker thread')
629 else:
630 # Child process should just return.
631 pass
632
633 w = threading.Thread(target=worker)
634
635 # Stub out the private condition variable's _release_save method.
636 # This releases the condition's lock and flips the global that
637 # causes the worker to fork. At this point, the problematic waiter
638 # lock has been acquired once by the waiter and has been put onto
639 # the waiters list.
640 condition = w._block
641 orig_release_save = condition._release_save
642 def my_release_save():
643 global start_fork
644 orig_release_save()
645 # Waiter lock held here, condition lock released.
646 start_fork = True
647 condition._release_save = my_release_save
648
649 w.start()
650 w.join()
651 print('end of main thread')
652 """
653 output = "end of worker thread\nend of main thread\n"
654 self.assertScriptHasOutput(script, output)
655
Charles-François Natali8e6fe642012-03-24 20:36:09 +0100656 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200657 def test_6_daemon_threads(self):
658 # Check that a daemon thread cannot crash the interpreter on shutdown
659 # by manipulating internal structures that are being disposed of in
660 # the main thread.
661 script = """if True:
662 import os
663 import random
664 import sys
665 import time
666 import threading
667
668 thread_has_run = set()
669
670 def random_io():
671 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200672 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200673 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200674 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200675 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200676 null_f.write(stuff)
677 time.sleep(random.random() / 1995)
678 null_f.close()
679 in_f.close()
680 thread_has_run.add(threading.current_thread())
681
682 def main():
683 count = 0
684 for _ in range(40):
685 new_thread = threading.Thread(target=random_io)
686 new_thread.daemon = True
687 new_thread.start()
688 count += 1
689 while len(thread_has_run) < count:
690 time.sleep(0.001)
691 # Trigger process shutdown
692 sys.exit(0)
693
694 main()
695 """
696 rc, out, err = assert_python_ok('-c', script)
697 self.assertFalse(err)
698
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100699 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100700 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100701 def test_reinit_tls_after_fork(self):
702 # Issue #13817: fork() would deadlock in a multithreaded program with
703 # the ad-hoc TLS implementation.
704
705 def do_fork_and_wait():
706 # just fork a child process and wait it
707 pid = os.fork()
708 if pid > 0:
709 os.waitpid(pid, 0)
710 else:
711 os._exit(0)
712
713 # start a bunch of threads that will fork() child processes
714 threads = []
715 for i in range(16):
716 t = threading.Thread(target=do_fork_and_wait)
717 threads.append(t)
718 t.start()
719
720 for t in threads:
721 t.join()
722
Jesse Nollera8513972008-07-17 16:49:17 +0000723
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000724class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000725 # A RuntimeError should be raised if Thread.start() is called
726 # multiple times.
727 def test_start_thread_again(self):
728 thread = threading.Thread()
729 thread.start()
730 self.assertRaises(RuntimeError, thread.start)
731
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000732 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000733 current_thread = threading.current_thread()
734 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000735
736 def test_joining_inactive_thread(self):
737 thread = threading.Thread()
738 self.assertRaises(RuntimeError, thread.join)
739
740 def test_daemonize_active_thread(self):
741 thread = threading.Thread()
742 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000743 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000744
Ned Deily9a7c5242011-05-28 00:19:56 -0700745 @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
746 def test_recursion_limit(self):
747 # Issue 9670
748 # test that excessive recursion within a non-main thread causes
749 # an exception rather than crashing the interpreter on platforms
750 # like Mac OS X or FreeBSD which have small default stack sizes
751 # for threads
752 script = """if True:
753 import threading
754
755 def recurse():
756 return recurse()
757
758 def outer():
759 try:
760 recurse()
761 except RuntimeError:
762 pass
763
764 w = threading.Thread(target=outer)
765 w.start()
766 w.join()
767 print('end of main thread')
768 """
769 expected_output = "end of main thread\n"
770 p = subprocess.Popen([sys.executable, "-c", script],
771 stdout=subprocess.PIPE)
772 stdout, stderr = p.communicate()
773 data = stdout.decode().replace('\r', '')
774 self.assertEqual(p.returncode, 0, "Unexpected error")
775 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000776
Antoine Pitrou557934f2009-11-06 22:41:14 +0000777class LockTests(lock_tests.LockTests):
778 locktype = staticmethod(threading.Lock)
779
Antoine Pitrou434736a2009-11-10 18:46:01 +0000780class PyRLockTests(lock_tests.RLockTests):
781 locktype = staticmethod(threading._PyRLock)
782
Charles-François Natali6b671b22012-01-28 11:36:04 +0100783@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +0000784class CRLockTests(lock_tests.RLockTests):
785 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000786
787class EventTests(lock_tests.EventTests):
788 eventtype = staticmethod(threading.Event)
789
790class ConditionAsRLockTests(lock_tests.RLockTests):
791 # An Condition uses an RLock by default and exports its API.
792 locktype = staticmethod(threading.Condition)
793
794class ConditionTests(lock_tests.ConditionTests):
795 condtype = staticmethod(threading.Condition)
796
797class SemaphoreTests(lock_tests.SemaphoreTests):
798 semtype = staticmethod(threading.Semaphore)
799
800class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
801 semtype = staticmethod(threading.BoundedSemaphore)
802
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000803class BarrierTests(lock_tests.BarrierTests):
804 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000805
Tim Peters84d54892005-01-08 06:03:17 +0000806def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000807 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000808 ConditionAsRLockTests, ConditionTests,
809 SemaphoreTests, BoundedSemaphoreTests,
810 ThreadTests,
811 ThreadJoinOnShutdown,
812 ThreadingExceptionTests,
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000813 BarrierTests
Antoine Pitrou557934f2009-11-06 22:41:14 +0000814 )
Tim Peters84d54892005-01-08 06:03:17 +0000815
816if __name__ == "__main__":
817 test_main()