blob: c6682d6baceba045d42fc319bf7a83ba535291f7 [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
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000431 def test_deamon_param(self):
432 t = threading.Thread()
433 self.assertFalse(t.daemon)
434 t = threading.Thread(daemon=False)
435 self.assertFalse(t.daemon)
436 t = threading.Thread(daemon=True)
437 self.assertTrue(t.daemon)
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
442 def _run_and_join(self, script):
443 script = """if 1:
444 import sys, os, time, threading
445
446 # a thread, which waits for the main program to terminate
447 def joiningfunc(mainthread):
448 mainthread.join()
449 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000450 # stdout is fully buffered because not a tty, we have to flush
451 # before exit.
452 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000453 \n""" + script
454
Jesse Nollera8513972008-07-17 16:49:17 +0000455 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
456 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000457 data = p.stdout.read().decode().replace('\r', '')
Brian Curtinb68928b2010-11-02 03:59:09 +0000458 p.stdout.close()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000459 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000460 self.assertFalse(rc == 2, "interpreter was blocked")
461 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000462
463 def test_1_join_on_shutdown(self):
464 # The usual case: on exit, wait for a non-daemon thread
465 script = """if 1:
466 import os
467 t = threading.Thread(target=joiningfunc,
468 args=(threading.current_thread(),))
469 t.start()
470 time.sleep(0.1)
471 print('end of main')
472 """
473 self._run_and_join(script)
474
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000475 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000476 def test_2_join_in_forked_process(self):
477 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000478 script = """if 1:
479 childpid = os.fork()
480 if childpid != 0:
481 os.waitpid(childpid, 0)
482 sys.exit(0)
483
484 t = threading.Thread(target=joiningfunc,
485 args=(threading.current_thread(),))
486 t.start()
487 print('end of main')
488 """
489 self._run_and_join(script)
490
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000491 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000492 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000493 # Like the test above, but fork() was called from a worker thread
494 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000495
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000496 # Skip platforms with known problems forking from a worker thread.
497 # See http://bugs.python.org/issue3863.
Gregory P. Smithfeedda22010-10-17 03:09:12 +0000498 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
499 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000500 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
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):
521 p = subprocess.Popen([sys.executable, "-c", script],
522 stdout=subprocess.PIPE)
Victor Stinnerc932b652011-01-05 03:54:28 +0000523 stdout, stderr = p.communicate()
524 data = stdout.decode().replace('\r', '')
525 self.assertEqual(p.returncode, 0, "Unexpected error")
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000526 self.assertEqual(data, expected_output)
527
528 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
529 def test_4_joining_across_fork_in_worker_thread(self):
530 # There used to be a possible deadlock when forking from a child
531 # thread. See http://bugs.python.org/issue6643.
532
533 # Skip platforms with known problems forking from a worker thread.
534 # See http://bugs.python.org/issue3863.
535 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
536 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
537
538 # The script takes the following steps:
539 # - The main thread in the parent process starts a new thread and then
540 # tries to join it.
541 # - The join operation acquires the Lock inside the thread's _block
542 # Condition. (See threading.py:Thread.join().)
543 # - We stub out the acquire method on the condition to force it to wait
544 # until the child thread forks. (See LOCK ACQUIRED HERE)
545 # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
546 # HERE)
547 # - The main thread of the parent process enters Condition.wait(),
548 # which releases the lock on the child thread.
549 # - The child process returns. Without the necessary fix, when the
550 # main thread of the child process (which used to be the child thread
551 # in the parent process) attempts to exit, it will try to acquire the
552 # lock in the Thread._block Condition object and hang, because the
553 # lock was held across the fork.
554
555 script = """if 1:
556 import os, time, threading
557
558 finish_join = False
559 start_fork = False
560
561 def worker():
562 # Wait until this thread's lock is acquired before forking to
563 # create the deadlock.
564 global finish_join
565 while not start_fork:
566 time.sleep(0.01)
567 # LOCK HELD: Main thread holds lock across this call.
568 childpid = os.fork()
569 finish_join = True
570 if childpid != 0:
571 # Parent process just waits for child.
572 os.waitpid(childpid, 0)
573 # Child process should just return.
574
575 w = threading.Thread(target=worker)
576
577 # Stub out the private condition variable's lock acquire method.
578 # This acquires the lock and then waits until the child has forked
579 # before returning, which will release the lock soon after. If
580 # someone else tries to fix this test case by acquiring this lock
Ezio Melotti13925002011-03-16 11:05:33 +0200581 # before forking instead of resetting it, the test case will
Gregory P. Smith96c886c2011-01-03 21:06:12 +0000582 # deadlock when it shouldn't.
583 condition = w._block
584 orig_acquire = condition.acquire
585 call_count_lock = threading.Lock()
586 call_count = 0
587 def my_acquire():
588 global call_count
589 global start_fork
590 orig_acquire() # LOCK ACQUIRED HERE
591 start_fork = True
592 if call_count == 0:
593 while not finish_join:
594 time.sleep(0.01) # WORKER THREAD FORKS HERE
595 with call_count_lock:
596 call_count += 1
597 condition.acquire = my_acquire
598
599 w.start()
600 w.join()
601 print('end of main')
602 """
603 self.assertScriptHasOutput(script, "end of main\n")
604
605 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
606 def test_5_clear_waiter_locks_to_avoid_crash(self):
607 # Check that a spawned thread that forks doesn't segfault on certain
608 # platforms, namely OS X. This used to happen if there was a waiter
609 # lock in the thread's condition variable's waiters list. Even though
610 # we know the lock will be held across the fork, it is not safe to
611 # release locks held across forks on all platforms, so releasing the
612 # waiter lock caused a segfault on OS X. Furthermore, since locks on
613 # OS X are (as of this writing) implemented with a mutex + condition
614 # variable instead of a semaphore, while we know that the Python-level
615 # lock will be acquired, we can't know if the internal mutex will be
616 # acquired at the time of the fork.
617
618 # Skip platforms with known problems forking from a worker thread.
619 # See http://bugs.python.org/issue3863.
620 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
621 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
622 script = """if True:
623 import os, time, threading
624
625 start_fork = False
626
627 def worker():
628 # Wait until the main thread has attempted to join this thread
629 # before continuing.
630 while not start_fork:
631 time.sleep(0.01)
632 childpid = os.fork()
633 if childpid != 0:
634 # Parent process just waits for child.
635 (cpid, rc) = os.waitpid(childpid, 0)
636 assert cpid == childpid
637 assert rc == 0
638 print('end of worker thread')
639 else:
640 # Child process should just return.
641 pass
642
643 w = threading.Thread(target=worker)
644
645 # Stub out the private condition variable's _release_save method.
646 # This releases the condition's lock and flips the global that
647 # causes the worker to fork. At this point, the problematic waiter
648 # lock has been acquired once by the waiter and has been put onto
649 # the waiters list.
650 condition = w._block
651 orig_release_save = condition._release_save
652 def my_release_save():
653 global start_fork
654 orig_release_save()
655 # Waiter lock held here, condition lock released.
656 start_fork = True
657 condition._release_save = my_release_save
658
659 w.start()
660 w.join()
661 print('end of main thread')
662 """
663 output = "end of worker thread\nend of main thread\n"
664 self.assertScriptHasOutput(script, output)
665
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200666 def test_6_daemon_threads(self):
667 # Check that a daemon thread cannot crash the interpreter on shutdown
668 # by manipulating internal structures that are being disposed of in
669 # the main thread.
670 script = """if True:
671 import os
672 import random
673 import sys
674 import time
675 import threading
676
677 thread_has_run = set()
678
679 def random_io():
680 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
681 blank = b'x' * 200
682 while True:
683 in_f = open(os.__file__, 'r')
684 stuff = in_f.read(200)
685 null_f = open(os.devnull, 'w')
686 null_f.write(stuff)
687 time.sleep(random.random() / 1995)
688 null_f.close()
689 in_f.close()
690 thread_has_run.add(threading.current_thread())
691
692 def main():
693 count = 0
694 for _ in range(40):
695 new_thread = threading.Thread(target=random_io)
696 new_thread.daemon = True
697 new_thread.start()
698 count += 1
699 while len(thread_has_run) < count:
700 time.sleep(0.001)
701 # Trigger process shutdown
702 sys.exit(0)
703
704 main()
705 """
706 rc, out, err = assert_python_ok('-c', script)
707 self.assertFalse(err)
708
Jesse Nollera8513972008-07-17 16:49:17 +0000709
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000710class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000711 # A RuntimeError should be raised if Thread.start() is called
712 # multiple times.
713 def test_start_thread_again(self):
714 thread = threading.Thread()
715 thread.start()
716 self.assertRaises(RuntimeError, thread.start)
717
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000718 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000719 current_thread = threading.current_thread()
720 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000721
722 def test_joining_inactive_thread(self):
723 thread = threading.Thread()
724 self.assertRaises(RuntimeError, thread.join)
725
726 def test_daemonize_active_thread(self):
727 thread = threading.Thread()
728 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000729 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000730
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000731 def test_releasing_unacquired_lock(self):
732 lock = threading.Lock()
733 self.assertRaises(RuntimeError, lock.release)
734
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000735
Antoine Pitrou557934f2009-11-06 22:41:14 +0000736class LockTests(lock_tests.LockTests):
737 locktype = staticmethod(threading.Lock)
738
Antoine Pitrou434736a2009-11-10 18:46:01 +0000739class PyRLockTests(lock_tests.RLockTests):
740 locktype = staticmethod(threading._PyRLock)
741
742class CRLockTests(lock_tests.RLockTests):
743 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000744
745class EventTests(lock_tests.EventTests):
746 eventtype = staticmethod(threading.Event)
747
748class ConditionAsRLockTests(lock_tests.RLockTests):
749 # An Condition uses an RLock by default and exports its API.
750 locktype = staticmethod(threading.Condition)
751
752class ConditionTests(lock_tests.ConditionTests):
753 condtype = staticmethod(threading.Condition)
754
755class SemaphoreTests(lock_tests.SemaphoreTests):
756 semtype = staticmethod(threading.Semaphore)
757
758class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
759 semtype = staticmethod(threading.BoundedSemaphore)
760
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000761class BarrierTests(lock_tests.BarrierTests):
762 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000763
Victor Stinner754851f2011-04-19 23:58:51 +0200764
Tim Peters84d54892005-01-08 06:03:17 +0000765def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000766 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000767 ConditionAsRLockTests, ConditionTests,
768 SemaphoreTests, BoundedSemaphoreTests,
769 ThreadTests,
770 ThreadJoinOnShutdown,
771 ThreadingExceptionTests,
Victor Stinnerd5c355c2011-04-30 14:53:09 +0200772 BarrierTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000773 )
Tim Peters84d54892005-01-08 06:03:17 +0000774
775if __name__ == "__main__":
776 test_main()