blob: c39d5e26c76d90ca147cb5bad0743c365b05d986 [file] [log] [blame]
Antoine Pitrou4c8ce842013-09-01 19:51:49 +02001"""
2Tests for the threading module.
3"""
Skip Montanaro4533f602001-08-20 20:28:48 +00004
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005import test.support
Antoine Pitrouc4d78642011-05-05 20:17:32 +02006from test.support import verbose, strip_python_stderr, import_module
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02007from test.script_helper import assert_python_ok
8
Skip Montanaro4533f602001-08-20 20:28:48 +00009import random
Georg Brandl0c77a822008-06-10 16:37:50 +000010import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011import sys
Antoine Pitrouc4d78642011-05-05 20:17:32 +020012_thread = import_module('_thread')
13threading = import_module('threading')
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +020014import _testcapi
Skip Montanaro4533f602001-08-20 20:28:48 +000015import time
Tim Peters84d54892005-01-08 06:03:17 +000016import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000017import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000018import os
Antoine Pitrouc4d78642011-05-05 20:17:32 +020019from test.script_helper import assert_python_ok, assert_python_failure
Gregory P. Smith4b129d22011-01-04 00:51:50 +000020import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000021
Antoine Pitrou557934f2009-11-06 22:41:14 +000022from test import lock_tests
23
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030024
25# Between fork() and exec(), only async-safe functions are allowed (issues
26# #12316 and #11870), and fork() from a worker thread is known to trigger
27# problems with some operating systems (issue #3863): skip problematic tests
28# on platforms known to behave badly.
29platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
30 'hp-ux11')
31
32
Tim Peters84d54892005-01-08 06:03:17 +000033# A trivial mutable counter.
34class Counter(object):
35 def __init__(self):
36 self.value = 0
37 def inc(self):
38 self.value += 1
39 def dec(self):
40 self.value -= 1
41 def get(self):
42 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000043
44class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000045 def __init__(self, name, testcase, sema, mutex, nrunning):
46 threading.Thread.__init__(self, name=name)
47 self.testcase = testcase
48 self.sema = sema
49 self.mutex = mutex
50 self.nrunning = nrunning
51
Skip Montanaro4533f602001-08-20 20:28:48 +000052 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000054 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000055 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000056 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000057
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 with self.sema:
59 with self.mutex:
60 self.nrunning.inc()
61 if verbose:
62 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000063 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000064
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 time.sleep(delay)
66 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000067 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000068
Christian Heimes4fbc72b2008-03-22 00:47:35 +000069 with self.mutex:
70 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000071 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000072 if verbose:
73 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000074 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000075
Skip Montanaro4533f602001-08-20 20:28:48 +000076
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000077class BaseTestCase(unittest.TestCase):
78 def setUp(self):
79 self._threads = test.support.threading_setup()
80
81 def tearDown(self):
82 test.support.threading_cleanup(*self._threads)
83 test.support.reap_children()
84
85
86class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000087
Tim Peters84d54892005-01-08 06:03:17 +000088 # Create a bunch of threads, let each do some work, wait until all are
89 # done.
90 def test_various_ops(self):
91 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
92 # times about 1 second per clump).
93 NUMTASKS = 10
94
95 # no more than 3 of the 10 can run at once
96 sema = threading.BoundedSemaphore(value=3)
97 mutex = threading.RLock()
98 numrunning = Counter()
99
100 threads = []
101
102 for i in range(NUMTASKS):
103 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
104 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000105 self.assertEqual(t.ident, None)
106 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000107 t.start()
108
109 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000111 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200112 t.join()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertTrue(not t.is_alive())
114 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000115 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000116 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
117 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000118 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000119 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000120 self.assertEqual(numrunning.get(), 0)
121
Benjamin Petersond23f8222009-04-05 19:13:16 +0000122 def test_ident_of_no_threading_threads(self):
123 # The ident still must work for the main thread and dummy threads.
124 self.assertFalse(threading.currentThread().ident is None)
125 def f():
126 ident.append(threading.currentThread().ident)
127 done.set()
128 done = threading.Event()
129 ident = []
130 _thread.start_new_thread(f, ())
131 done.wait()
132 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000133 # Kill the "immortal" _DummyThread
134 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000135
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 # run with a small(ish) thread stack size (256kB)
137 def test_various_ops_small_stack(self):
138 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000139 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140 try:
141 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000142 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000143 raise unittest.SkipTest(
144 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 self.test_various_ops()
146 threading.stack_size(0)
147
148 # run with a large thread stack size (1MB)
149 def test_various_ops_large_stack(self):
150 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000151 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000152 try:
153 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000154 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000155 raise unittest.SkipTest(
156 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157 self.test_various_ops()
158 threading.stack_size(0)
159
Tim Peters711906e2005-01-08 07:30:42 +0000160 def test_foreign_thread(self):
161 # Check that a "foreign" thread can use the threading module.
162 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000163 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000164 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000165 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000166 mutex.release()
167
168 mutex = threading.Lock()
169 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000170 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000171 # Wait for the thread to finish.
172 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000173 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000174 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000175 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000176
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
178 # exposed at the Python level. This test relies on ctypes to get at it.
179 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200180 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000181
182 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
183
184 class AsyncExc(Exception):
185 pass
186
187 exception = ctypes.py_object(AsyncExc)
188
Antoine Pitroube4d8092009-10-18 18:27:17 +0000189 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200190 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000191
192 try:
193 result = set_async_exc(ctypes.c_long(tid), exception)
194 # The exception is async, so we might have to keep the VM busy until
195 # it notices.
196 while True:
197 pass
198 except AsyncExc:
199 pass
200 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000201 # This code is unreachable but it reflects the intent. If we wanted
202 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000203 self.fail("AsyncExc not raised")
204 try:
205 self.assertEqual(result, 1) # one thread state modified
206 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000207 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000208 pass
209
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000210 # `worker_started` is set by the thread when it's inside a try/except
211 # block waiting to catch the asynchronously set AsyncExc exception.
212 # `worker_saw_exception` is set by the thread upon catching that
213 # exception.
214 worker_started = threading.Event()
215 worker_saw_exception = threading.Event()
216
217 class Worker(threading.Thread):
218 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200219 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220 self.finished = False
221
222 try:
223 while True:
224 worker_started.set()
225 time.sleep(0.1)
226 except AsyncExc:
227 self.finished = True
228 worker_saw_exception.set()
229
230 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000231 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 t.start()
233 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000234 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000235
236 # Try a thread id that doesn't make sense.
237 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000238 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000239 result = set_async_exc(ctypes.c_long(-1), exception)
240 self.assertEqual(result, 0) # no thread states modified
241
242 # Now raise an exception in the worker thread.
243 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000245 ret = worker_started.wait()
246 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000248 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000249 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000250 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000251 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000252 result = set_async_exc(ctypes.c_long(t.id), exception)
253 self.assertEqual(result, 1) # one thread state modified
254 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000255 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000256 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000257 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000258 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000259 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000260 if t.finished:
261 t.join()
262 # else the thread is still running, and we have no way to kill it
263
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000264 def test_limbo_cleanup(self):
265 # Issue 7481: Failure to start thread should cleanup the limbo map.
266 def fail_new_thread(*args):
267 raise threading.ThreadError()
268 _start_new_thread = threading._start_new_thread
269 threading._start_new_thread = fail_new_thread
270 try:
271 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000272 self.assertRaises(threading.ThreadError, t.start)
273 self.assertFalse(
274 t in threading._limbo,
275 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000276 finally:
277 threading._start_new_thread = _start_new_thread
278
Christian Heimes7d2ff882007-11-30 14:35:04 +0000279 def test_finalize_runnning_thread(self):
280 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
281 # very late on python exit: on deallocation of a running thread for
282 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200283 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000284
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200285 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000286 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000287
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000288 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000289 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000290 ready.acquire()
291
Christian Heimes7d2ff882007-11-30 14:35:04 +0000292 # Module globals are cleared before __del__ is run
293 # So we save the functions in class dict
294 class C:
295 ensure = ctypes.pythonapi.PyGILState_Ensure
296 release = ctypes.pythonapi.PyGILState_Release
297 def __del__(self):
298 state = self.ensure()
299 self.release(state)
300
301 def waitingThread():
302 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000303 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000304 time.sleep(100)
305
Georg Brandl2067bfd2008-05-25 13:05:15 +0000306 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000307 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000308 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200309 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000310 self.assertEqual(rc, 42)
311
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000312 def test_finalize_with_trace(self):
313 # Issue1733757
314 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200315 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000316 import sys, threading
317
318 # A deadlock-killer, to prevent the
319 # testsuite to hang forever
320 def killer():
321 import os, time
322 time.sleep(2)
323 print('program blocked; aborting')
324 os._exit(2)
325 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000326 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000327 t.start()
328
329 # This is the trace function
330 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000331 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000332 return func
333
334 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200335 """)
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 Pitrouc4d78642011-05-05 20:17:32 +0200340 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000341 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
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200352 """)
353 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000354 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200355 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000356
Christian Heimes1af737c2008-01-23 08:24:23 +0000357 def test_enumerate_after_join(self):
358 # Try hard to trigger #1703448: a thread is still returned in
359 # threading.enumerate() after it has been join()ed.
360 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000361 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000362 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000363 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000364 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000365 t = threading.Thread(target=lambda: None)
366 t.start()
367 t.join()
368 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000369 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000370 "#1703448 triggered after %d trials: %s" % (i, l))
371 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000372 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000373
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000374 def test_no_refcycle_through_target(self):
375 class RunSelfFunction(object):
376 def __init__(self, should_raise):
377 # The links in this refcycle from Thread back to self
378 # should be cleaned up when the thread completes.
379 self.should_raise = should_raise
380 self.thread = threading.Thread(target=self._run,
381 args=(self,),
382 kwargs={'yet_another':self})
383 self.thread.start()
384
385 def _run(self, other_ref, yet_another):
386 if self.should_raise:
387 raise SystemExit
388
389 cyclic_object = RunSelfFunction(should_raise=False)
390 weak_cyclic_object = weakref.ref(cyclic_object)
391 cyclic_object.thread.join()
392 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000393 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000394 msg=('%d references still around' %
395 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000396
397 raising_cyclic_object = RunSelfFunction(should_raise=True)
398 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
399 raising_cyclic_object.thread.join()
400 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000401 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000402 msg=('%d references still around' %
403 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000404
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000405 def test_old_threading_api(self):
406 # Just a quick sanity check to make sure the old method names are
407 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000408 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000409 t.isDaemon()
410 t.setDaemon(True)
411 t.getName()
412 t.setName("name")
413 t.isAlive()
414 e = threading.Event()
415 e.isSet()
416 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000417
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000418 def test_repr_daemon(self):
419 t = threading.Thread()
420 self.assertFalse('daemon' in repr(t))
421 t.daemon = True
422 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000423
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000424 def test_deamon_param(self):
425 t = threading.Thread()
426 self.assertFalse(t.daemon)
427 t = threading.Thread(daemon=False)
428 self.assertFalse(t.daemon)
429 t = threading.Thread(daemon=True)
430 self.assertTrue(t.daemon)
431
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200432 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
433 def test_dummy_thread_after_fork(self):
434 # Issue #14308: a dummy thread in the active list doesn't mess up
435 # the after-fork mechanism.
436 code = """if 1:
437 import _thread, threading, os, time
438
439 def background_thread(evt):
440 # Creates and registers the _DummyThread instance
441 threading.current_thread()
442 evt.set()
443 time.sleep(10)
444
445 evt = threading.Event()
446 _thread.start_new_thread(background_thread, (evt,))
447 evt.wait()
448 assert threading.active_count() == 2, threading.active_count()
449 if os.fork() == 0:
450 assert threading.active_count() == 1, threading.active_count()
451 os._exit(0)
452 else:
453 os.wait()
454 """
455 _, out, err = assert_python_ok("-c", code)
456 self.assertEqual(out, b'')
457 self.assertEqual(err, b'')
458
Charles-François Natali9939cc82013-08-30 23:32:53 +0200459 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
460 def test_is_alive_after_fork(self):
461 # Try hard to trigger #18418: is_alive() could sometimes be True on
462 # threads that vanished after a fork.
463 old_interval = sys.getswitchinterval()
464 self.addCleanup(sys.setswitchinterval, old_interval)
465
466 # Make the bug more likely to manifest.
467 sys.setswitchinterval(1e-6)
468
469 for i in range(20):
470 t = threading.Thread(target=lambda: None)
471 t.start()
472 self.addCleanup(t.join)
473 pid = os.fork()
474 if pid == 0:
475 os._exit(1 if t.is_alive() else 0)
476 else:
477 pid, status = os.waitpid(pid, 0)
478 self.assertEqual(0, status)
479
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300480 def test_main_thread(self):
481 main = threading.main_thread()
482 self.assertEqual(main.name, 'MainThread')
483 self.assertEqual(main.ident, threading.current_thread().ident)
484 self.assertEqual(main.ident, threading.get_ident())
485
486 def f():
487 self.assertNotEqual(threading.main_thread().ident,
488 threading.current_thread().ident)
489 th = threading.Thread(target=f)
490 th.start()
491 th.join()
492
493 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
494 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
495 def test_main_thread_after_fork(self):
496 code = """if 1:
497 import os, threading
498
499 pid = os.fork()
500 if pid == 0:
501 main = threading.main_thread()
502 print(main.name)
503 print(main.ident == threading.current_thread().ident)
504 print(main.ident == threading.get_ident())
505 else:
506 os.waitpid(pid, 0)
507 """
508 _, out, err = assert_python_ok("-c", code)
509 data = out.decode().replace('\r', '')
510 self.assertEqual(err, b"")
511 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
512
513 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
514 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
515 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
516 def test_main_thread_after_fork_from_nonmain_thread(self):
517 code = """if 1:
518 import os, threading, sys
519
520 def f():
521 pid = os.fork()
522 if pid == 0:
523 main = threading.main_thread()
524 print(main.name)
525 print(main.ident == threading.current_thread().ident)
526 print(main.ident == threading.get_ident())
527 # stdout is fully buffered because not a tty,
528 # we have to flush before exit.
529 sys.stdout.flush()
530 else:
531 os.waitpid(pid, 0)
532
533 th = threading.Thread(target=f)
534 th.start()
535 th.join()
536 """
537 _, out, err = assert_python_ok("-c", code)
538 data = out.decode().replace('\r', '')
539 self.assertEqual(err, b"")
540 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
541
Antoine Pitrou7b476992013-09-07 23:38:37 +0200542 def test_tstate_lock(self):
543 # Test an implementation detail of Thread objects.
544 started = _thread.allocate_lock()
545 finish = _thread.allocate_lock()
546 started.acquire()
547 finish.acquire()
548 def f():
549 started.release()
550 finish.acquire()
551 time.sleep(0.01)
552 # The tstate lock is None until the thread is started
553 t = threading.Thread(target=f)
554 self.assertIs(t._tstate_lock, None)
555 t.start()
556 started.acquire()
557 self.assertTrue(t.is_alive())
558 # The tstate lock can't be acquired when the thread is running
559 # (or suspended).
560 tstate_lock = t._tstate_lock
561 self.assertFalse(tstate_lock.acquire(timeout=0), False)
562 finish.release()
563 # When the thread ends, the state_lock can be successfully
564 # acquired.
565 self.assertTrue(tstate_lock.acquire(timeout=5), False)
566 # But is_alive() is still True: we hold _tstate_lock now, which
567 # prevents is_alive() from knowing the thread's end-of-life C code
568 # is done.
569 self.assertTrue(t.is_alive())
570 # Let is_alive() find out the C code is done.
571 tstate_lock.release()
572 self.assertFalse(t.is_alive())
573 # And verify the thread disposed of _tstate_lock.
574 self.assertTrue(t._tstate_lock is None)
575
Tim Peters72460fa2013-09-09 18:48:24 -0500576 def test_repr_stopped(self):
577 # Verify that "stopped" shows up in repr(Thread) appropriately.
578 started = _thread.allocate_lock()
579 finish = _thread.allocate_lock()
580 started.acquire()
581 finish.acquire()
582 def f():
583 started.release()
584 finish.acquire()
585 t = threading.Thread(target=f)
586 t.start()
587 started.acquire()
588 self.assertIn("started", repr(t))
589 finish.release()
590 # "stopped" should appear in the repr in a reasonable amount of time.
591 # Implementation detail: as of this writing, that's trivially true
592 # if .join() is called, and almost trivially true if .is_alive() is
593 # called. The detail we're testing here is that "stopped" shows up
594 # "all on its own".
595 LOOKING_FOR = "stopped"
596 for i in range(500):
597 if LOOKING_FOR in repr(t):
598 break
599 time.sleep(0.01)
600 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Christian Heimes1af737c2008-01-23 08:24:23 +0000601
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000602class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000603
604 def _run_and_join(self, script):
605 script = """if 1:
606 import sys, os, time, threading
607
608 # a thread, which waits for the main program to terminate
609 def joiningfunc(mainthread):
610 mainthread.join()
611 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000612 # stdout is fully buffered because not a tty, we have to flush
613 # before exit.
614 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000615 \n""" + script
616
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200617 rc, out, err = assert_python_ok("-c", script)
618 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000619 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000620
621 def test_1_join_on_shutdown(self):
622 # The usual case: on exit, wait for a non-daemon thread
623 script = """if 1:
624 import os
625 t = threading.Thread(target=joiningfunc,
626 args=(threading.current_thread(),))
627 t.start()
628 time.sleep(0.1)
629 print('end of main')
630 """
631 self._run_and_join(script)
632
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000633 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200634 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000635 def test_2_join_in_forked_process(self):
636 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000637 script = """if 1:
638 childpid = os.fork()
639 if childpid != 0:
640 os.waitpid(childpid, 0)
641 sys.exit(0)
642
643 t = threading.Thread(target=joiningfunc,
644 args=(threading.current_thread(),))
645 t.start()
646 print('end of main')
647 """
648 self._run_and_join(script)
649
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000650 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200651 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000652 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000653 # Like the test above, but fork() was called from a worker thread
654 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000655
Jesse Nollera8513972008-07-17 16:49:17 +0000656 script = """if 1:
657 main_thread = threading.current_thread()
658 def worker():
659 childpid = os.fork()
660 if childpid != 0:
661 os.waitpid(childpid, 0)
662 sys.exit(0)
663
664 t = threading.Thread(target=joiningfunc,
665 args=(main_thread,))
666 print('end of main')
667 t.start()
668 t.join() # Should not block: main_thread is already stopped
669
670 w = threading.Thread(target=worker)
671 w.start()
672 """
673 self._run_and_join(script)
674
Victor Stinner26d31862011-07-01 14:26:24 +0200675 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500676 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200677 # Check that a daemon thread cannot crash the interpreter on shutdown
678 # by manipulating internal structures that are being disposed of in
679 # the main thread.
680 script = """if True:
681 import os
682 import random
683 import sys
684 import time
685 import threading
686
687 thread_has_run = set()
688
689 def random_io():
690 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200691 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200692 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200693 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200694 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200695 null_f.write(stuff)
696 time.sleep(random.random() / 1995)
697 null_f.close()
698 in_f.close()
699 thread_has_run.add(threading.current_thread())
700
701 def main():
702 count = 0
703 for _ in range(40):
704 new_thread = threading.Thread(target=random_io)
705 new_thread.daemon = True
706 new_thread.start()
707 count += 1
708 while len(thread_has_run) < count:
709 time.sleep(0.001)
710 # Trigger process shutdown
711 sys.exit(0)
712
713 main()
714 """
715 rc, out, err = assert_python_ok('-c', script)
716 self.assertFalse(err)
717
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100718 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100719 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100720 def test_reinit_tls_after_fork(self):
721 # Issue #13817: fork() would deadlock in a multithreaded program with
722 # the ad-hoc TLS implementation.
723
724 def do_fork_and_wait():
725 # just fork a child process and wait it
726 pid = os.fork()
727 if pid > 0:
728 os.waitpid(pid, 0)
729 else:
730 os._exit(0)
731
732 # start a bunch of threads that will fork() child processes
733 threads = []
734 for i in range(16):
735 t = threading.Thread(target=do_fork_and_wait)
736 threads.append(t)
737 t.start()
738
739 for t in threads:
740 t.join()
741
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200742 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
743 def test_clear_threads_states_after_fork(self):
744 # Issue #17094: check that threads states are cleared after fork()
745
746 # start a bunch of threads
747 threads = []
748 for i in range(16):
749 t = threading.Thread(target=lambda : time.sleep(0.3))
750 threads.append(t)
751 t.start()
752
753 pid = os.fork()
754 if pid == 0:
755 # check that threads states have been cleared
756 if len(sys._current_frames()) == 1:
757 os._exit(0)
758 else:
759 os._exit(1)
760 else:
761 _, status = os.waitpid(pid, 0)
762 self.assertEqual(0, status)
763
764 for t in threads:
765 t.join()
766
Jesse Nollera8513972008-07-17 16:49:17 +0000767
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200768class SubinterpThreadingTests(BaseTestCase):
769
770 def test_threads_join(self):
771 # Non-daemon threads should be joined at subinterpreter shutdown
772 # (issue #18808)
773 r, w = os.pipe()
774 self.addCleanup(os.close, r)
775 self.addCleanup(os.close, w)
776 code = r"""if 1:
777 import os
778 import threading
779 import time
780
781 def f():
782 # Sleep a bit so that the thread is still running when
783 # Py_EndInterpreter is called.
784 time.sleep(0.05)
785 os.write(%d, b"x")
786 threading.Thread(target=f).start()
787 """ % (w,)
788 ret = _testcapi.run_in_subinterp(code)
789 self.assertEqual(ret, 0)
790 # The thread was joined properly.
791 self.assertEqual(os.read(r, 1), b"x")
792
Antoine Pitrou7b476992013-09-07 23:38:37 +0200793 def test_threads_join_2(self):
794 # Same as above, but a delay gets introduced after the thread's
795 # Python code returned but before the thread state is deleted.
796 # To achieve this, we register a thread-local object which sleeps
797 # a bit when deallocated.
798 r, w = os.pipe()
799 self.addCleanup(os.close, r)
800 self.addCleanup(os.close, w)
801 code = r"""if 1:
802 import os
803 import threading
804 import time
805
806 class Sleeper:
807 def __del__(self):
808 time.sleep(0.05)
809
810 tls = threading.local()
811
812 def f():
813 # Sleep a bit so that the thread is still running when
814 # Py_EndInterpreter is called.
815 time.sleep(0.05)
816 tls.x = Sleeper()
817 os.write(%d, b"x")
818 threading.Thread(target=f).start()
819 """ % (w,)
820 ret = _testcapi.run_in_subinterp(code)
821 self.assertEqual(ret, 0)
822 # The thread was joined properly.
823 self.assertEqual(os.read(r, 1), b"x")
824
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200825 def test_daemon_threads_fatal_error(self):
826 subinterp_code = r"""if 1:
827 import os
828 import threading
829 import time
830
831 def f():
832 # Make sure the daemon thread is still running when
833 # Py_EndInterpreter is called.
834 time.sleep(10)
835 threading.Thread(target=f, daemon=True).start()
836 """
837 script = r"""if 1:
838 import _testcapi
839
840 _testcapi.run_in_subinterp(%r)
841 """ % (subinterp_code,)
842 rc, out, err = assert_python_failure("-c", script)
843 self.assertIn("Fatal Python error: Py_EndInterpreter: "
844 "not the last thread", err.decode())
845
846
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000847class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000848 # A RuntimeError should be raised if Thread.start() is called
849 # multiple times.
850 def test_start_thread_again(self):
851 thread = threading.Thread()
852 thread.start()
853 self.assertRaises(RuntimeError, thread.start)
854
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000855 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000856 current_thread = threading.current_thread()
857 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000858
859 def test_joining_inactive_thread(self):
860 thread = threading.Thread()
861 self.assertRaises(RuntimeError, thread.join)
862
863 def test_daemonize_active_thread(self):
864 thread = threading.Thread()
865 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000866 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000867
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000868 def test_releasing_unacquired_lock(self):
869 lock = threading.Lock()
870 self.assertRaises(RuntimeError, lock.release)
871
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400872 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
873 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700874 def test_recursion_limit(self):
875 # Issue 9670
876 # test that excessive recursion within a non-main thread causes
877 # an exception rather than crashing the interpreter on platforms
878 # like Mac OS X or FreeBSD which have small default stack sizes
879 # for threads
880 script = """if True:
881 import threading
882
883 def recurse():
884 return recurse()
885
886 def outer():
887 try:
888 recurse()
889 except RuntimeError:
890 pass
891
892 w = threading.Thread(target=outer)
893 w.start()
894 w.join()
895 print('end of main thread')
896 """
897 expected_output = "end of main thread\n"
898 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200899 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700900 stdout, stderr = p.communicate()
901 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200902 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700903 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000904
R David Murray19aeb432013-03-30 17:19:38 -0400905class TimerTests(BaseTestCase):
906
907 def setUp(self):
908 BaseTestCase.setUp(self)
909 self.callback_args = []
910 self.callback_event = threading.Event()
911
912 def test_init_immutable_default_args(self):
913 # Issue 17435: constructor defaults were mutable objects, they could be
914 # mutated via the object attributes and affect other Timer objects.
915 timer1 = threading.Timer(0.01, self._callback_spy)
916 timer1.start()
917 self.callback_event.wait()
918 timer1.args.append("blah")
919 timer1.kwargs["foo"] = "bar"
920 self.callback_event.clear()
921 timer2 = threading.Timer(0.01, self._callback_spy)
922 timer2.start()
923 self.callback_event.wait()
924 self.assertEqual(len(self.callback_args), 2)
925 self.assertEqual(self.callback_args, [((), {}), ((), {})])
926
927 def _callback_spy(self, *args, **kwargs):
928 self.callback_args.append((args[:], kwargs.copy()))
929 self.callback_event.set()
930
Antoine Pitrou557934f2009-11-06 22:41:14 +0000931class LockTests(lock_tests.LockTests):
932 locktype = staticmethod(threading.Lock)
933
Antoine Pitrou434736a2009-11-10 18:46:01 +0000934class PyRLockTests(lock_tests.RLockTests):
935 locktype = staticmethod(threading._PyRLock)
936
Charles-François Natali6b671b22012-01-28 11:36:04 +0100937@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +0000938class CRLockTests(lock_tests.RLockTests):
939 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000940
941class EventTests(lock_tests.EventTests):
942 eventtype = staticmethod(threading.Event)
943
944class ConditionAsRLockTests(lock_tests.RLockTests):
945 # An Condition uses an RLock by default and exports its API.
946 locktype = staticmethod(threading.Condition)
947
948class ConditionTests(lock_tests.ConditionTests):
949 condtype = staticmethod(threading.Condition)
950
951class SemaphoreTests(lock_tests.SemaphoreTests):
952 semtype = staticmethod(threading.Semaphore)
953
954class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
955 semtype = staticmethod(threading.BoundedSemaphore)
956
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000957class BarrierTests(lock_tests.BarrierTests):
958 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000959
Tim Peters84d54892005-01-08 06:03:17 +0000960if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -0400961 unittest.main()