blob: 1c946dab127f276855c85a685264e773c0fe4d18 [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 Pitrou62f68ed2010-08-04 11:48:56 +00004from test.support import verbose, strip_python_stderr
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
Victor Stinner45df8202010-04-28 22:31:17 +00008_thread = test.support.import_module('_thread')
9threading = test.support.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
Gregory P. Smith96c886c2011-01-03 21:06:12 +000014import subprocess
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020015from test.script_helper import assert_python_ok
Skip Montanaro4533f602001-08-20 20:28:48 +000016
Antoine Pitrou557934f2009-11-06 22:41:14 +000017from test import lock_tests
18
Tim Peters84d54892005-01-08 06:03:17 +000019# A trivial mutable counter.
20class Counter(object):
21 def __init__(self):
22 self.value = 0
23 def inc(self):
24 self.value += 1
25 def dec(self):
26 self.value -= 1
27 def get(self):
28 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000029
30class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000031 def __init__(self, name, testcase, sema, mutex, nrunning):
32 threading.Thread.__init__(self, name=name)
33 self.testcase = testcase
34 self.sema = sema
35 self.mutex = mutex
36 self.nrunning = nrunning
37
Skip Montanaro4533f602001-08-20 20:28:48 +000038 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000039 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000040 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000041 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000042 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000043
Christian Heimes4fbc72b2008-03-22 00:47:35 +000044 with self.sema:
45 with self.mutex:
46 self.nrunning.inc()
47 if verbose:
48 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000049 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000050
Christian Heimes4fbc72b2008-03-22 00:47:35 +000051 time.sleep(delay)
52 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000053 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000054
Christian Heimes4fbc72b2008-03-22 00:47:35 +000055 with self.mutex:
56 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000057 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 if verbose:
59 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000060 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000061
Skip Montanaro4533f602001-08-20 20:28:48 +000062
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000063class BaseTestCase(unittest.TestCase):
64 def setUp(self):
65 self._threads = test.support.threading_setup()
66
67 def tearDown(self):
68 test.support.threading_cleanup(*self._threads)
69 test.support.reap_children()
70
71
72class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000073
Tim Peters84d54892005-01-08 06:03:17 +000074 # Create a bunch of threads, let each do some work, wait until all are
75 # done.
76 def test_various_ops(self):
77 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
78 # times about 1 second per clump).
79 NUMTASKS = 10
80
81 # no more than 3 of the 10 can run at once
82 sema = threading.BoundedSemaphore(value=3)
83 mutex = threading.RLock()
84 numrunning = Counter()
85
86 threads = []
87
88 for i in range(NUMTASKS):
89 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
90 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 self.assertEqual(t.ident, None)
92 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000093 t.start()
94
95 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000096 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000097 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000098 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertTrue(not t.is_alive())
100 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000101 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000102 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
103 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000104 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000106 self.assertEqual(numrunning.get(), 0)
107
Benjamin Petersond23f8222009-04-05 19:13:16 +0000108 def test_ident_of_no_threading_threads(self):
109 # The ident still must work for the main thread and dummy threads.
110 self.assertFalse(threading.currentThread().ident is None)
111 def f():
112 ident.append(threading.currentThread().ident)
113 done.set()
114 done = threading.Event()
115 ident = []
116 _thread.start_new_thread(f, ())
117 done.wait()
118 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000119 # Kill the "immortal" _DummyThread
120 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000121
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 # run with a small(ish) thread stack size (256kB)
123 def test_various_ops_small_stack(self):
124 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000125 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 try:
127 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000128 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000129 raise unittest.SkipTest(
130 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000131 self.test_various_ops()
132 threading.stack_size(0)
133
134 # run with a large thread stack size (1MB)
135 def test_various_ops_large_stack(self):
136 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000137 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 try:
139 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000140 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000141 raise unittest.SkipTest(
142 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 self.test_various_ops()
144 threading.stack_size(0)
145
Tim Peters711906e2005-01-08 07:30:42 +0000146 def test_foreign_thread(self):
147 # Check that a "foreign" thread can use the threading module.
148 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000149 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000150 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000151 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000152 mutex.release()
153
154 mutex = threading.Lock()
155 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000156 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000157 # Wait for the thread to finish.
158 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000159 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000160 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000161 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000162
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000163 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
164 # exposed at the Python level. This test relies on ctypes to get at it.
165 def test_PyThreadState_SetAsyncExc(self):
166 try:
167 import ctypes
168 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000169 raise unittest.SkipTest("cannot import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000170
171 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
172
173 class AsyncExc(Exception):
174 pass
175
176 exception = ctypes.py_object(AsyncExc)
177
Antoine Pitroube4d8092009-10-18 18:27:17 +0000178 # First check it works when setting the exception from the same thread.
179 tid = _thread.get_ident()
180
181 try:
182 result = set_async_exc(ctypes.c_long(tid), exception)
183 # The exception is async, so we might have to keep the VM busy until
184 # it notices.
185 while True:
186 pass
187 except AsyncExc:
188 pass
189 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000190 # This code is unreachable but it reflects the intent. If we wanted
191 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000192 self.fail("AsyncExc not raised")
193 try:
194 self.assertEqual(result, 1) # one thread state modified
195 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000196 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000197 pass
198
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000199 # `worker_started` is set by the thread when it's inside a try/except
200 # block waiting to catch the asynchronously set AsyncExc exception.
201 # `worker_saw_exception` is set by the thread upon catching that
202 # exception.
203 worker_started = threading.Event()
204 worker_saw_exception = threading.Event()
205
206 class Worker(threading.Thread):
207 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000208 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000209 self.finished = False
210
211 try:
212 while True:
213 worker_started.set()
214 time.sleep(0.1)
215 except AsyncExc:
216 self.finished = True
217 worker_saw_exception.set()
218
219 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000220 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221 t.start()
222 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000223 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000224
225 # Try a thread id that doesn't make sense.
226 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000227 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000228 result = set_async_exc(ctypes.c_long(-1), exception)
229 self.assertEqual(result, 0) # no thread states modified
230
231 # Now raise an exception in the worker thread.
232 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000233 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000234 ret = worker_started.wait()
235 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000237 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000238 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000239 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 result = set_async_exc(ctypes.c_long(t.id), exception)
242 self.assertEqual(result, 1) # one thread state modified
243 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000246 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000248 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000249 if t.finished:
250 t.join()
251 # else the thread is still running, and we have no way to kill it
252
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000253 def test_limbo_cleanup(self):
254 # Issue 7481: Failure to start thread should cleanup the limbo map.
255 def fail_new_thread(*args):
256 raise threading.ThreadError()
257 _start_new_thread = threading._start_new_thread
258 threading._start_new_thread = fail_new_thread
259 try:
260 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000261 self.assertRaises(threading.ThreadError, t.start)
262 self.assertFalse(
263 t in threading._limbo,
264 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000265 finally:
266 threading._start_new_thread = _start_new_thread
267
Christian Heimes7d2ff882007-11-30 14:35:04 +0000268 def test_finalize_runnning_thread(self):
269 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
270 # very late on python exit: on deallocation of a running thread for
271 # example.
272 try:
273 import ctypes
274 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000275 raise unittest.SkipTest("cannot import ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000276
Christian Heimes7d2ff882007-11-30 14:35:04 +0000277 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000278 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000279
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000280 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000281 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000282 ready.acquire()
283
Christian Heimes7d2ff882007-11-30 14:35:04 +0000284 # Module globals are cleared before __del__ is run
285 # So we save the functions in class dict
286 class C:
287 ensure = ctypes.pythonapi.PyGILState_Ensure
288 release = ctypes.pythonapi.PyGILState_Release
289 def __del__(self):
290 state = self.ensure()
291 self.release(state)
292
293 def waitingThread():
294 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000295 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000296 time.sleep(100)
297
Georg Brandl2067bfd2008-05-25 13:05:15 +0000298 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000299 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000300 sys.exit(42)
301 """])
302 self.assertEqual(rc, 42)
303
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000304 def test_finalize_with_trace(self):
305 # Issue1733757
306 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrou7c087442010-09-19 23:28:30 +0000307 p = subprocess.Popen([sys.executable, "-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000308 import sys, threading
309
310 # A deadlock-killer, to prevent the
311 # testsuite to hang forever
312 def killer():
313 import os, time
314 time.sleep(2)
315 print('program blocked; aborting')
316 os._exit(2)
317 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000318 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000319 t.start()
320
321 # This is the trace function
322 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000323 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324 return func
325
326 sys.settrace(func)
Antoine Pitrou7c087442010-09-19 23:28:30 +0000327 """],
328 stdout=subprocess.PIPE,
329 stderr=subprocess.PIPE)
Brian Curtinde11b182010-11-05 17:22:46 +0000330 self.addCleanup(p.stdout.close)
331 self.addCleanup(p.stderr.close)
Antoine Pitrou7c087442010-09-19 23:28:30 +0000332 stdout, stderr = p.communicate()
333 rc = p.returncode
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000334 self.assertFalse(rc == 2, "interpreted was blocked")
Antoine Pitrou7c087442010-09-19 23:28:30 +0000335 self.assertTrue(rc == 0,
336 "Unexpected error: " + ascii(stderr))
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000337
Antoine Pitrou011bd622009-10-20 21:52:47 +0000338 def test_join_nondaemon_on_shutdown(self):
339 # Issue 1722344
340 # Raising SystemExit skipped threading._shutdown
Antoine Pitrou011bd622009-10-20 21:52:47 +0000341 p = subprocess.Popen([sys.executable, "-c", """if 1:
342 import threading
343 from time import sleep
344
345 def child():
346 sleep(1)
347 # As a non-daemon thread we SHOULD wake up and nothing
348 # should be torn down yet
349 print("Woke up, sleep function is:", sleep)
350
351 threading.Thread(target=child).start()
352 raise SystemExit
353 """],
354 stdout=subprocess.PIPE,
355 stderr=subprocess.PIPE)
Brian Curtinde11b182010-11-05 17:22:46 +0000356 self.addCleanup(p.stdout.close)
357 self.addCleanup(p.stderr.close)
Antoine Pitrou011bd622009-10-20 21:52:47 +0000358 stdout, stderr = p.communicate()
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000359 self.assertEqual(stdout.strip(),
360 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou62f68ed2010-08-04 11:48:56 +0000361 stderr = strip_python_stderr(stderr)
Antoine Pitrou011bd622009-10-20 21:52:47 +0000362 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000363
Christian Heimes1af737c2008-01-23 08:24:23 +0000364 def test_enumerate_after_join(self):
365 # Try hard to trigger #1703448: a thread is still returned in
366 # threading.enumerate() after it has been join()ed.
367 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000368 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000369 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000370 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000371 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000372 t = threading.Thread(target=lambda: None)
373 t.start()
374 t.join()
375 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000376 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000377 "#1703448 triggered after %d trials: %s" % (i, l))
378 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000379 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000380
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000381 def test_no_refcycle_through_target(self):
382 class RunSelfFunction(object):
383 def __init__(self, should_raise):
384 # The links in this refcycle from Thread back to self
385 # should be cleaned up when the thread completes.
386 self.should_raise = should_raise
387 self.thread = threading.Thread(target=self._run,
388 args=(self,),
389 kwargs={'yet_another':self})
390 self.thread.start()
391
392 def _run(self, other_ref, yet_another):
393 if self.should_raise:
394 raise SystemExit
395
396 cyclic_object = RunSelfFunction(should_raise=False)
397 weak_cyclic_object = weakref.ref(cyclic_object)
398 cyclic_object.thread.join()
399 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000400 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000401 msg=('%d references still around' %
402 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000403
404 raising_cyclic_object = RunSelfFunction(should_raise=True)
405 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
406 raising_cyclic_object.thread.join()
407 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000408 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000409 msg=('%d references still around' %
410 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000411
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000412 def test_old_threading_api(self):
413 # Just a quick sanity check to make sure the old method names are
414 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000415 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000416 t.isDaemon()
417 t.setDaemon(True)
418 t.getName()
419 t.setName("name")
420 t.isAlive()
421 e = threading.Event()
422 e.isSet()
423 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000424
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000425 def test_repr_daemon(self):
426 t = threading.Thread()
427 self.assertFalse('daemon' in repr(t))
428 t.daemon = True
429 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000430
Christian Heimes1af737c2008-01-23 08:24:23 +0000431
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000432class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000433
434 def _run_and_join(self, script):
435 script = """if 1:
436 import sys, os, time, threading
437
438 # a thread, which waits for the main program to terminate
439 def joiningfunc(mainthread):
440 mainthread.join()
441 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000442 # stdout is fully buffered because not a tty, we have to flush
443 # before exit.
444 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000445 \n""" + script
446
Jesse Nollera8513972008-07-17 16:49:17 +0000447 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
448 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000449 data = p.stdout.read().decode().replace('\r', '')
Brian Curtinb68928b2010-11-02 03:59:09 +0000450 p.stdout.close()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000451 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000452 self.assertFalse(rc == 2, "interpreter was blocked")
453 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000454
455 def test_1_join_on_shutdown(self):
456 # The usual case: on exit, wait for a non-daemon thread
457 script = """if 1:
458 import os
459 t = threading.Thread(target=joiningfunc,
460 args=(threading.current_thread(),))
461 t.start()
462 time.sleep(0.1)
463 print('end of main')
464 """
465 self._run_and_join(script)
466
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000467 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000468 def test_2_join_in_forked_process(self):
469 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000470 script = """if 1:
471 childpid = os.fork()
472 if childpid != 0:
473 os.waitpid(childpid, 0)
474 sys.exit(0)
475
476 t = threading.Thread(target=joiningfunc,
477 args=(threading.current_thread(),))
478 t.start()
479 print('end of main')
480 """
481 self._run_and_join(script)
482
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000483 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000484 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000485 # Like the test above, but fork() was called from a worker thread
486 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000487
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000488 # Skip platforms with known problems forking from a worker thread.
489 # See http://bugs.python.org/issue3863.
Gregory P. Smithfeedda22010-10-17 03:09:12 +0000490 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
491 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000492 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000493 script = """if 1:
494 main_thread = threading.current_thread()
495 def worker():
496 childpid = os.fork()
497 if childpid != 0:
498 os.waitpid(childpid, 0)
499 sys.exit(0)
500
501 t = threading.Thread(target=joiningfunc,
502 args=(main_thread,))
503 print('end of main')
504 t.start()
505 t.join() # Should not block: main_thread is already stopped
506
507 w = threading.Thread(target=worker)
508 w.start()
509 """
510 self._run_and_join(script)
511
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000512 def assertScriptHasOutput(self, script, expected_output):
513 p = subprocess.Popen([sys.executable, "-c", script],
514 stdout=subprocess.PIPE)
Victor Stinnerc932b652011-01-05 03:54:28 +0000515 stdout, stderr = p.communicate()
516 data = stdout.decode().replace('\r', '')
517 self.assertEqual(p.returncode, 0, "Unexpected error")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000518 self.assertEqual(data, expected_output)
519
520 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
521 def test_4_joining_across_fork_in_worker_thread(self):
522 # There used to be a possible deadlock when forking from a child
523 # thread. See http://bugs.python.org/issue6643.
524
525 # Skip platforms with known problems forking from a worker thread.
526 # See http://bugs.python.org/issue3863.
527 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
528 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
529
530 # The script takes the following steps:
531 # - The main thread in the parent process starts a new thread and then
532 # tries to join it.
533 # - The join operation acquires the Lock inside the thread's _block
534 # Condition. (See threading.py:Thread.join().)
535 # - We stub out the acquire method on the condition to force it to wait
536 # until the child thread forks. (See LOCK ACQUIRED HERE)
537 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
538 # HERE)
539 # - The main thread of the parent process enters Condition.wait(),
540 # which releases the lock on the child thread.
541 # - The child process returns. Without the necessary fix, when the
542 # main thread of the child process (which used to be the child thread
543 # in the parent process) attempts to exit, it will try to acquire the
544 # lock in the Thread._block Condition object and hang, because the
545 # lock was held across the fork.
546
547 script = """if 1:
548 import os, time, threading
549
550 finish_join = False
551 start_fork = False
552
553 def worker():
554 # Wait until this thread's lock is acquired before forking to
555 # create the deadlock.
556 global finish_join
557 while not start_fork:
558 time.sleep(0.01)
559 # LOCK HELD: Main thread holds lock across this call.
560 childpid = os.fork()
561 finish_join = True
562 if childpid != 0:
563 # Parent process just waits for child.
564 os.waitpid(childpid, 0)
565 # Child process should just return.
566
567 w = threading.Thread(target=worker)
568
569 # Stub out the private condition variable's lock acquire method.
570 # This acquires the lock and then waits until the child has forked
571 # before returning, which will release the lock soon after. If
572 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200573 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000574 # deadlock when it shouldn't.
575 condition = w._block
576 orig_acquire = condition.acquire
577 call_count_lock = threading.Lock()
578 call_count = 0
579 def my_acquire():
580 global call_count
581 global start_fork
582 orig_acquire() # LOCK ACQUIRED HERE
583 start_fork = True
584 if call_count == 0:
585 while not finish_join:
586 time.sleep(0.01) # WORKER THREAD FORKS HERE
587 with call_count_lock:
588 call_count += 1
589 condition.acquire = my_acquire
590
591 w.start()
592 w.join()
593 print('end of main')
594 """
595 self.assertScriptHasOutput(script, "end of main\n")
596
597 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
598 def test_5_clear_waiter_locks_to_avoid_crash(self):
599 # Check that a spawned thread that forks doesn't segfault on certain
600 # platforms, namely OS X. This used to happen if there was a waiter
601 # lock in the thread's condition variable's waiters list. Even though
602 # we know the lock will be held across the fork, it is not safe to
603 # release locks held across forks on all platforms, so releasing the
604 # waiter lock caused a segfault on OS X. Furthermore, since locks on
605 # OS X are (as of this writing) implemented with a mutex + condition
606 # variable instead of a semaphore, while we know that the Python-level
607 # lock will be acquired, we can't know if the internal mutex will be
608 # acquired at the time of the fork.
609
610 # Skip platforms with known problems forking from a worker thread.
611 # See http://bugs.python.org/issue3863.
612 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
613 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
614 script = """if True:
615 import os, time, threading
616
617 start_fork = False
618
619 def worker():
620 # Wait until the main thread has attempted to join this thread
621 # before continuing.
622 while not start_fork:
623 time.sleep(0.01)
624 childpid = os.fork()
625 if childpid != 0:
626 # Parent process just waits for child.
627 (cpid, rc) = os.waitpid(childpid, 0)
628 assert cpid == childpid
629 assert rc == 0
630 print('end of worker thread')
631 else:
632 # Child process should just return.
633 pass
634
635 w = threading.Thread(target=worker)
636
637 # Stub out the private condition variable's _release_save method.
638 # This releases the condition's lock and flips the global that
639 # causes the worker to fork. At this point, the problematic waiter
640 # lock has been acquired once by the waiter and has been put onto
641 # the waiters list.
642 condition = w._block
643 orig_release_save = condition._release_save
644 def my_release_save():
645 global start_fork
646 orig_release_save()
647 # Waiter lock held here, condition lock released.
648 start_fork = True
649 condition._release_save = my_release_save
650
651 w.start()
652 w.join()
653 print('end of main thread')
654 """
655 output = "end of worker thread\nend of main thread\n"
656 self.assertScriptHasOutput(script, output)
657
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200658 def test_6_daemon_threads(self):
659 # Check that a daemon thread cannot crash the interpreter on shutdown
660 # by manipulating internal structures that are being disposed of in
661 # the main thread.
662 script = """if True:
663 import os
664 import random
665 import sys
666 import time
667 import threading
668
669 thread_has_run = set()
670
671 def random_io():
672 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
673 blank = b'x' * 200
674 while True:
675 in_f = open(os.__file__, 'r')
676 stuff = in_f.read(200)
677 null_f = open(os.devnull, 'w')
678 null_f.write(stuff)
679 time.sleep(random.random() / 1995)
680 null_f.close()
681 in_f.close()
682 thread_has_run.add(threading.current_thread())
683
684 def main():
685 count = 0
686 for _ in range(40):
687 new_thread = threading.Thread(target=random_io)
688 new_thread.daemon = True
689 new_thread.start()
690 count += 1
691 while len(thread_has_run) < count:
692 time.sleep(0.001)
693 # Trigger process shutdown
694 sys.exit(0)
695
696 main()
697 """
698 rc, out, err = assert_python_ok('-c', script)
699 self.assertFalse(err)
700
Jesse Nollera8513972008-07-17 16:49:17 +0000701
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000702class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000703 # A RuntimeError should be raised if Thread.start() is called
704 # multiple times.
705 def test_start_thread_again(self):
706 thread = threading.Thread()
707 thread.start()
708 self.assertRaises(RuntimeError, thread.start)
709
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000710 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000711 current_thread = threading.current_thread()
712 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000713
714 def test_joining_inactive_thread(self):
715 thread = threading.Thread()
716 self.assertRaises(RuntimeError, thread.join)
717
718 def test_daemonize_active_thread(self):
719 thread = threading.Thread()
720 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000721 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000722
723
Antoine Pitrou557934f2009-11-06 22:41:14 +0000724class LockTests(lock_tests.LockTests):
725 locktype = staticmethod(threading.Lock)
726
Antoine Pitrou434736a2009-11-10 18:46:01 +0000727class PyRLockTests(lock_tests.RLockTests):
728 locktype = staticmethod(threading._PyRLock)
729
730class CRLockTests(lock_tests.RLockTests):
731 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000732
733class EventTests(lock_tests.EventTests):
734 eventtype = staticmethod(threading.Event)
735
736class ConditionAsRLockTests(lock_tests.RLockTests):
737 # An Condition uses an RLock by default and exports its API.
738 locktype = staticmethod(threading.Condition)
739
740class ConditionTests(lock_tests.ConditionTests):
741 condtype = staticmethod(threading.Condition)
742
743class SemaphoreTests(lock_tests.SemaphoreTests):
744 semtype = staticmethod(threading.Semaphore)
745
746class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
747 semtype = staticmethod(threading.BoundedSemaphore)
748
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000749class BarrierTests(lock_tests.BarrierTests):
750 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000751
Tim Peters84d54892005-01-08 06:03:17 +0000752def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000753 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000754 ConditionAsRLockTests, ConditionTests,
755 SemaphoreTests, BoundedSemaphoreTests,
756 ThreadTests,
757 ThreadJoinOnShutdown,
758 ThreadingExceptionTests,
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000759 BarrierTests
Antoine Pitrou557934f2009-11-06 22:41:14 +0000760 )
Tim Peters84d54892005-01-08 06:03:17 +0000761
762if __name__ == "__main__":
763 test_main()