blob: 029218d21014108dd6795a1da37f8cad361f66aa [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
Skip Montanaro4533f602001-08-20 20:28:48 +000015
Antoine Pitrou557934f2009-11-06 22:41:14 +000016from test import lock_tests
17
Tim Peters84d54892005-01-08 06:03:17 +000018# A trivial mutable counter.
19class Counter(object):
20 def __init__(self):
21 self.value = 0
22 def inc(self):
23 self.value += 1
24 def dec(self):
25 self.value -= 1
26 def get(self):
27 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000028
29class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000030 def __init__(self, name, testcase, sema, mutex, nrunning):
31 threading.Thread.__init__(self, name=name)
32 self.testcase = testcase
33 self.sema = sema
34 self.mutex = mutex
35 self.nrunning = nrunning
36
Skip Montanaro4533f602001-08-20 20:28:48 +000037 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000038 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000039 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000040 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000041 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000042
Christian Heimes4fbc72b2008-03-22 00:47:35 +000043 with self.sema:
44 with self.mutex:
45 self.nrunning.inc()
46 if verbose:
47 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000048 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000049
Christian Heimes4fbc72b2008-03-22 00:47:35 +000050 time.sleep(delay)
51 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000052 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000053
Christian Heimes4fbc72b2008-03-22 00:47:35 +000054 with self.mutex:
55 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000056 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000057 if verbose:
58 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000059 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000060
Skip Montanaro4533f602001-08-20 20:28:48 +000061
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000062class BaseTestCase(unittest.TestCase):
63 def setUp(self):
64 self._threads = test.support.threading_setup()
65
66 def tearDown(self):
67 test.support.threading_cleanup(*self._threads)
68 test.support.reap_children()
69
70
71class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000072
Tim Peters84d54892005-01-08 06:03:17 +000073 # Create a bunch of threads, let each do some work, wait until all are
74 # done.
75 def test_various_ops(self):
76 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
77 # times about 1 second per clump).
78 NUMTASKS = 10
79
80 # no more than 3 of the 10 can run at once
81 sema = threading.BoundedSemaphore(value=3)
82 mutex = threading.RLock()
83 numrunning = Counter()
84
85 threads = []
86
87 for i in range(NUMTASKS):
88 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
89 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000090 self.assertEqual(t.ident, None)
91 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000092 t.start()
93
94 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000095 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000096 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000097 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000098 self.assertTrue(not t.is_alive())
99 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000100 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000101 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
102 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000103 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000105 self.assertEqual(numrunning.get(), 0)
106
Benjamin Petersond23f8222009-04-05 19:13:16 +0000107 def test_ident_of_no_threading_threads(self):
108 # The ident still must work for the main thread and dummy threads.
109 self.assertFalse(threading.currentThread().ident is None)
110 def f():
111 ident.append(threading.currentThread().ident)
112 done.set()
113 done = threading.Event()
114 ident = []
115 _thread.start_new_thread(f, ())
116 done.wait()
117 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000118 # Kill the "immortal" _DummyThread
119 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000120
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000121 # run with a small(ish) thread stack size (256kB)
122 def test_various_ops_small_stack(self):
123 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000124 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125 try:
126 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000127 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000128 raise unittest.SkipTest(
129 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 self.test_various_ops()
131 threading.stack_size(0)
132
133 # run with a large thread stack size (1MB)
134 def test_various_ops_large_stack(self):
135 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000136 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 try:
138 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000139 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000140 raise unittest.SkipTest(
141 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 self.test_various_ops()
143 threading.stack_size(0)
144
Tim Peters711906e2005-01-08 07:30:42 +0000145 def test_foreign_thread(self):
146 # Check that a "foreign" thread can use the threading module.
147 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000148 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000149 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000150 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000151 mutex.release()
152
153 mutex = threading.Lock()
154 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000155 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000156 # Wait for the thread to finish.
157 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000158 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000159 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000160 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000161
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000162 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
163 # exposed at the Python level. This test relies on ctypes to get at it.
164 def test_PyThreadState_SetAsyncExc(self):
165 try:
166 import ctypes
167 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000168 raise unittest.SkipTest("cannot import 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.
271 try:
272 import ctypes
273 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000274 raise unittest.SkipTest("cannot import ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000275
Christian Heimes7d2ff882007-11-30 14:35:04 +0000276 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000277 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000279 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000280 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000281 ready.acquire()
282
Christian Heimes7d2ff882007-11-30 14:35:04 +0000283 # Module globals are cleared before __del__ is run
284 # So we save the functions in class dict
285 class C:
286 ensure = ctypes.pythonapi.PyGILState_Ensure
287 release = ctypes.pythonapi.PyGILState_Release
288 def __del__(self):
289 state = self.ensure()
290 self.release(state)
291
292 def waitingThread():
293 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000294 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000295 time.sleep(100)
296
Georg Brandl2067bfd2008-05-25 13:05:15 +0000297 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000298 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000299 sys.exit(42)
300 """])
301 self.assertEqual(rc, 42)
302
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000303 def test_finalize_with_trace(self):
304 # Issue1733757
305 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrou7c087442010-09-19 23:28:30 +0000306 p = subprocess.Popen([sys.executable, "-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000307 import sys, threading
308
309 # A deadlock-killer, to prevent the
310 # testsuite to hang forever
311 def killer():
312 import os, time
313 time.sleep(2)
314 print('program blocked; aborting')
315 os._exit(2)
316 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000317 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000318 t.start()
319
320 # This is the trace function
321 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000322 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000323 return func
324
325 sys.settrace(func)
Antoine Pitrou7c087442010-09-19 23:28:30 +0000326 """],
327 stdout=subprocess.PIPE,
328 stderr=subprocess.PIPE)
Brian Curtinde11b182010-11-05 17:22:46 +0000329 self.addCleanup(p.stdout.close)
330 self.addCleanup(p.stderr.close)
Antoine Pitrou7c087442010-09-19 23:28:30 +0000331 stdout, stderr = p.communicate()
332 rc = p.returncode
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000333 self.assertFalse(rc == 2, "interpreted was blocked")
Antoine Pitrou7c087442010-09-19 23:28:30 +0000334 self.assertTrue(rc == 0,
335 "Unexpected error: " + ascii(stderr))
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000336
Antoine Pitrou011bd622009-10-20 21:52:47 +0000337 def test_join_nondaemon_on_shutdown(self):
338 # Issue 1722344
339 # Raising SystemExit skipped threading._shutdown
Antoine Pitrou011bd622009-10-20 21:52:47 +0000340 p = subprocess.Popen([sys.executable, "-c", """if 1:
341 import threading
342 from time import sleep
343
344 def child():
345 sleep(1)
346 # As a non-daemon thread we SHOULD wake up and nothing
347 # should be torn down yet
348 print("Woke up, sleep function is:", sleep)
349
350 threading.Thread(target=child).start()
351 raise SystemExit
352 """],
353 stdout=subprocess.PIPE,
354 stderr=subprocess.PIPE)
Brian Curtinde11b182010-11-05 17:22:46 +0000355 self.addCleanup(p.stdout.close)
356 self.addCleanup(p.stderr.close)
Antoine Pitrou011bd622009-10-20 21:52:47 +0000357 stdout, stderr = p.communicate()
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000358 self.assertEqual(stdout.strip(),
359 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou62f68ed2010-08-04 11:48:56 +0000360 stderr = strip_python_stderr(stderr)
Antoine Pitrou011bd622009-10-20 21:52:47 +0000361 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000362
Christian Heimes1af737c2008-01-23 08:24:23 +0000363 def test_enumerate_after_join(self):
364 # Try hard to trigger #1703448: a thread is still returned in
365 # threading.enumerate() after it has been join()ed.
366 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000367 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000368 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000369 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000370 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000371 t = threading.Thread(target=lambda: None)
372 t.start()
373 t.join()
374 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000375 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000376 "#1703448 triggered after %d trials: %s" % (i, l))
377 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000378 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000379
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000380 def test_no_refcycle_through_target(self):
381 class RunSelfFunction(object):
382 def __init__(self, should_raise):
383 # The links in this refcycle from Thread back to self
384 # should be cleaned up when the thread completes.
385 self.should_raise = should_raise
386 self.thread = threading.Thread(target=self._run,
387 args=(self,),
388 kwargs={'yet_another':self})
389 self.thread.start()
390
391 def _run(self, other_ref, yet_another):
392 if self.should_raise:
393 raise SystemExit
394
395 cyclic_object = RunSelfFunction(should_raise=False)
396 weak_cyclic_object = weakref.ref(cyclic_object)
397 cyclic_object.thread.join()
398 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000399 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000400 msg=('%d references still around' %
401 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000402
403 raising_cyclic_object = RunSelfFunction(should_raise=True)
404 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
405 raising_cyclic_object.thread.join()
406 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000407 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000408 msg=('%d references still around' %
409 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000410
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000411 def test_old_threading_api(self):
412 # Just a quick sanity check to make sure the old method names are
413 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000414 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000415 t.isDaemon()
416 t.setDaemon(True)
417 t.getName()
418 t.setName("name")
419 t.isAlive()
420 e = threading.Event()
421 e.isSet()
422 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000423
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000424 def test_repr_daemon(self):
425 t = threading.Thread()
426 self.assertFalse('daemon' in repr(t))
427 t.daemon = True
428 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000429
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000430 def test_deamon_param(self):
431 t = threading.Thread()
432 self.assertFalse(t.daemon)
433 t = threading.Thread(daemon=False)
434 self.assertFalse(t.daemon)
435 t = threading.Thread(daemon=True)
436 self.assertTrue(t.daemon)
437
Christian Heimes1af737c2008-01-23 08:24:23 +0000438
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000439class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000440
441 def _run_and_join(self, script):
442 script = """if 1:
443 import sys, os, time, threading
444
445 # a thread, which waits for the main program to terminate
446 def joiningfunc(mainthread):
447 mainthread.join()
448 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000449 # stdout is fully buffered because not a tty, we have to flush
450 # before exit.
451 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000452 \n""" + script
453
Jesse Nollera8513972008-07-17 16:49:17 +0000454 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
455 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000456 data = p.stdout.read().decode().replace('\r', '')
Brian Curtinb68928b2010-11-02 03:59:09 +0000457 p.stdout.close()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000458 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000459 self.assertFalse(rc == 2, "interpreter was blocked")
460 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000461
462 def test_1_join_on_shutdown(self):
463 # The usual case: on exit, wait for a non-daemon thread
464 script = """if 1:
465 import os
466 t = threading.Thread(target=joiningfunc,
467 args=(threading.current_thread(),))
468 t.start()
469 time.sleep(0.1)
470 print('end of main')
471 """
472 self._run_and_join(script)
473
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
581 # before forking instead of reseting it, the test case will
582 # 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
Jesse Nollera8513972008-07-17 16:49:17 +0000666
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000667class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000668 # A RuntimeError should be raised if Thread.start() is called
669 # multiple times.
670 def test_start_thread_again(self):
671 thread = threading.Thread()
672 thread.start()
673 self.assertRaises(RuntimeError, thread.start)
674
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000675 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000676 current_thread = threading.current_thread()
677 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000678
679 def test_joining_inactive_thread(self):
680 thread = threading.Thread()
681 self.assertRaises(RuntimeError, thread.join)
682
683 def test_daemonize_active_thread(self):
684 thread = threading.Thread()
685 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000686 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000687
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000688 def test_releasing_unacquired_lock(self):
689 lock = threading.Lock()
690 self.assertRaises(RuntimeError, lock.release)
691
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000692
Antoine Pitrou557934f2009-11-06 22:41:14 +0000693class LockTests(lock_tests.LockTests):
694 locktype = staticmethod(threading.Lock)
695
Antoine Pitrou434736a2009-11-10 18:46:01 +0000696class PyRLockTests(lock_tests.RLockTests):
697 locktype = staticmethod(threading._PyRLock)
698
699class CRLockTests(lock_tests.RLockTests):
700 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000701
702class EventTests(lock_tests.EventTests):
703 eventtype = staticmethod(threading.Event)
704
705class ConditionAsRLockTests(lock_tests.RLockTests):
706 # An Condition uses an RLock by default and exports its API.
707 locktype = staticmethod(threading.Condition)
708
709class ConditionTests(lock_tests.ConditionTests):
710 condtype = staticmethod(threading.Condition)
711
712class SemaphoreTests(lock_tests.SemaphoreTests):
713 semtype = staticmethod(threading.Semaphore)
714
715class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
716 semtype = staticmethod(threading.BoundedSemaphore)
717
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000718class BarrierTests(lock_tests.BarrierTests):
719 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000720
Tim Peters84d54892005-01-08 06:03:17 +0000721def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000722 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000723 ConditionAsRLockTests, ConditionTests,
724 SemaphoreTests, BoundedSemaphoreTests,
725 ThreadTests,
726 ThreadJoinOnShutdown,
727 ThreadingExceptionTests,
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000728 BarrierTests
Antoine Pitrou557934f2009-11-06 22:41:14 +0000729 )
Tim Peters84d54892005-01-08 06:03:17 +0000730
731if __name__ == "__main__":
732 test_main()