blob: 0db028864d203a849663715462e5a7aa4d93b6d8 [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
Serhiy Storchakaa7930372016-07-03 22:27:26 +03006from test.support import (verbose, import_module, cpython_only,
7 requires_type_collecting)
Berker Peksagce643912015-05-06 06:33:17 +03008from test.support.script_helper import assert_python_ok, assert_python_failure
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +02009
Skip Montanaro4533f602001-08-20 20:28:48 +000010import random
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')
Skip Montanaro4533f602001-08-20 20:28:48 +000014import time
Tim Peters84d54892005-01-08 06:03:17 +000015import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000016import weakref
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000017import os
Gregory P. Smith4b129d22011-01-04 00:51:50 +000018import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000019
Antoine Pitrou557934f2009-11-06 22:41:14 +000020from test import lock_tests
Martin Panter19e69c52015-11-14 12:46:42 +000021from test import support
Antoine Pitrou557934f2009-11-06 22:41:14 +000022
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +030023
24# Between fork() and exec(), only async-safe functions are allowed (issues
25# #12316 and #11870), and fork() from a worker thread is known to trigger
26# problems with some operating systems (issue #3863): skip problematic tests
27# on platforms known to behave badly.
28platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
29 'hp-ux11')
30
31
Tim Peters84d54892005-01-08 06:03:17 +000032# A trivial mutable counter.
33class Counter(object):
34 def __init__(self):
35 self.value = 0
36 def inc(self):
37 self.value += 1
38 def dec(self):
39 self.value -= 1
40 def get(self):
41 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000042
43class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000044 def __init__(self, name, testcase, sema, mutex, nrunning):
45 threading.Thread.__init__(self, name=name)
46 self.testcase = testcase
47 self.sema = sema
48 self.mutex = mutex
49 self.nrunning = nrunning
50
Skip Montanaro4533f602001-08-20 20:28:48 +000051 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000052 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000053 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000054 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000055 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000056
Christian Heimes4fbc72b2008-03-22 00:47:35 +000057 with self.sema:
58 with self.mutex:
59 self.nrunning.inc()
60 if verbose:
61 print(self.nrunning.get(), 'tasks are running')
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020062 self.testcase.assertLessEqual(self.nrunning.get(), 3)
Tim Peters84d54892005-01-08 06:03:17 +000063
Christian Heimes4fbc72b2008-03-22 00:47:35 +000064 time.sleep(delay)
65 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000066 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000067
Christian Heimes4fbc72b2008-03-22 00:47:35 +000068 with self.mutex:
69 self.nrunning.dec()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +020070 self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 if verbose:
72 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000073 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000074
Skip Montanaro4533f602001-08-20 20:28:48 +000075
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000076class BaseTestCase(unittest.TestCase):
77 def setUp(self):
78 self._threads = test.support.threading_setup()
79
80 def tearDown(self):
81 test.support.threading_cleanup(*self._threads)
82 test.support.reap_children()
83
84
85class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000086
Tim Peters84d54892005-01-08 06:03:17 +000087 # Create a bunch of threads, let each do some work, wait until all are
88 # done.
89 def test_various_ops(self):
90 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
91 # times about 1 second per clump).
92 NUMTASKS = 10
93
94 # no more than 3 of the 10 can run at once
95 sema = threading.BoundedSemaphore(value=3)
96 mutex = threading.RLock()
97 numrunning = Counter()
98
99 threads = []
100
101 for i in range(NUMTASKS):
102 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
103 threads.append(t)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200104 self.assertIsNone(t.ident)
105 self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000106 t.start()
107
108 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +0000110 for t in threads:
Antoine Pitrou5da7e792013-09-08 13:19:06 +0200111 t.join()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200112 self.assertFalse(t.is_alive())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertNotEqual(t.ident, 0)
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200114 self.assertIsNotNone(t.ident)
115 self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
Tim Peters84d54892005-01-08 06:03:17 +0000116 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000117 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000118 self.assertEqual(numrunning.get(), 0)
119
Benjamin Petersond23f8222009-04-05 19:13:16 +0000120 def test_ident_of_no_threading_threads(self):
121 # The ident still must work for the main thread and dummy threads.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200122 self.assertIsNotNone(threading.currentThread().ident)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000123 def f():
124 ident.append(threading.currentThread().ident)
125 done.set()
126 done = threading.Event()
127 ident = []
128 _thread.start_new_thread(f, ())
129 done.wait()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200130 self.assertIsNotNone(ident[0])
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000131 # Kill the "immortal" _DummyThread
132 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000133
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000134 # run with a small(ish) thread stack size (256kB)
135 def test_various_ops_small_stack(self):
136 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000137 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 try:
139 threading.stack_size(262144)
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
146 # run with a large thread stack size (1MB)
147 def test_various_ops_large_stack(self):
148 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 try:
151 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000152 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000153 raise unittest.SkipTest(
154 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 self.test_various_ops()
156 threading.stack_size(0)
157
Tim Peters711906e2005-01-08 07:30:42 +0000158 def test_foreign_thread(self):
159 # Check that a "foreign" thread can use the threading module.
160 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000161 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000162 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000163 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000164 mutex.release()
165
166 mutex = threading.Lock()
167 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000168 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000169 # Wait for the thread to finish.
170 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000172 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Xiang Zhang4b6c4172017-02-27 11:45:42 +0800173 #Issue 29376
174 self.assertTrue(threading._active[tid].is_alive())
175 self.assertRegex(repr(threading._active[tid]), '_DummyThread')
Tim Peters711906e2005-01-08 07:30:42 +0000176 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000177
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
179 # exposed at the Python level. This test relies on ctypes to get at it.
180 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200181 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182
183 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
184
185 class AsyncExc(Exception):
186 pass
187
188 exception = ctypes.py_object(AsyncExc)
189
Antoine Pitroube4d8092009-10-18 18:27:17 +0000190 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200191 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000192
193 try:
194 result = set_async_exc(ctypes.c_long(tid), exception)
195 # The exception is async, so we might have to keep the VM busy until
196 # it notices.
197 while True:
198 pass
199 except AsyncExc:
200 pass
201 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000202 # This code is unreachable but it reflects the intent. If we wanted
203 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000204 self.fail("AsyncExc not raised")
205 try:
206 self.assertEqual(result, 1) # one thread state modified
207 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000208 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000209 pass
210
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000211 # `worker_started` is set by the thread when it's inside a try/except
212 # block waiting to catch the asynchronously set AsyncExc exception.
213 # `worker_saw_exception` is set by the thread upon catching that
214 # exception.
215 worker_started = threading.Event()
216 worker_saw_exception = threading.Event()
217
218 class Worker(threading.Thread):
219 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200220 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221 self.finished = False
222
223 try:
224 while True:
225 worker_started.set()
226 time.sleep(0.1)
227 except AsyncExc:
228 self.finished = True
229 worker_saw_exception.set()
230
231 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000232 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 t.start()
234 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000235 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236
237 # Try a thread id that doesn't make sense.
238 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000240 result = set_async_exc(ctypes.c_long(-1), exception)
241 self.assertEqual(result, 0) # no thread states modified
242
243 # Now raise an exception in the worker thread.
244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000246 ret = worker_started.wait()
247 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000248 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(" verifying worker hasn't exited")
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200250 self.assertFalse(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000251 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000252 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000253 result = set_async_exc(ctypes.c_long(t.id), exception)
254 self.assertEqual(result, 1) # one thread state modified
255 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000256 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000257 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000258 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000259 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000260 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000261 if t.finished:
262 t.join()
263 # else the thread is still running, and we have no way to kill it
264
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000265 def test_limbo_cleanup(self):
266 # Issue 7481: Failure to start thread should cleanup the limbo map.
267 def fail_new_thread(*args):
268 raise threading.ThreadError()
269 _start_new_thread = threading._start_new_thread
270 threading._start_new_thread = fail_new_thread
271 try:
272 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000273 self.assertRaises(threading.ThreadError, t.start)
274 self.assertFalse(
275 t in threading._limbo,
276 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000277 finally:
278 threading._start_new_thread = _start_new_thread
279
Christian Heimes7d2ff882007-11-30 14:35:04 +0000280 def test_finalize_runnning_thread(self):
281 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
282 # very late on python exit: on deallocation of a running thread for
283 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200284 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000285
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200286 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000287 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000288
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000289 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000290 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000291 ready.acquire()
292
Christian Heimes7d2ff882007-11-30 14:35:04 +0000293 # Module globals are cleared before __del__ is run
294 # So we save the functions in class dict
295 class C:
296 ensure = ctypes.pythonapi.PyGILState_Ensure
297 release = ctypes.pythonapi.PyGILState_Release
298 def __del__(self):
299 state = self.ensure()
300 self.release(state)
301
302 def waitingThread():
303 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000304 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000305 time.sleep(100)
306
Georg Brandl2067bfd2008-05-25 13:05:15 +0000307 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000308 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000309 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200310 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000311 self.assertEqual(rc, 42)
312
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000313 def test_finalize_with_trace(self):
314 # Issue1733757
315 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200316 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000317 import sys, threading
318
319 # A deadlock-killer, to prevent the
320 # testsuite to hang forever
321 def killer():
322 import os, time
323 time.sleep(2)
324 print('program blocked; aborting')
325 os._exit(2)
326 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000327 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000328 t.start()
329
330 # This is the trace function
331 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000332 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000333 return func
334
335 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200336 """)
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 Pitrouc4d78642011-05-05 20:17:32 +0200341 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000342 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
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200353 """)
354 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000355 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200356 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000357
Christian Heimes1af737c2008-01-23 08:24:23 +0000358 def test_enumerate_after_join(self):
359 # Try hard to trigger #1703448: a thread is still returned in
360 # threading.enumerate() after it has been join()ed.
361 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000362 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000363 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000364 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000365 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000366 t = threading.Thread(target=lambda: None)
367 t.start()
368 t.join()
369 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000370 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000371 "#1703448 triggered after %d trials: %s" % (i, l))
372 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000373 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000374
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000375 def test_no_refcycle_through_target(self):
376 class RunSelfFunction(object):
377 def __init__(self, should_raise):
378 # The links in this refcycle from Thread back to self
379 # should be cleaned up when the thread completes.
380 self.should_raise = should_raise
381 self.thread = threading.Thread(target=self._run,
382 args=(self,),
383 kwargs={'yet_another':self})
384 self.thread.start()
385
386 def _run(self, other_ref, yet_another):
387 if self.should_raise:
388 raise SystemExit
389
390 cyclic_object = RunSelfFunction(should_raise=False)
391 weak_cyclic_object = weakref.ref(cyclic_object)
392 cyclic_object.thread.join()
393 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000394 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000395 msg=('%d references still around' %
396 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000397
398 raising_cyclic_object = RunSelfFunction(should_raise=True)
399 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
400 raising_cyclic_object.thread.join()
401 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000402 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000403 msg=('%d references still around' %
404 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000405
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000406 def test_old_threading_api(self):
407 # Just a quick sanity check to make sure the old method names are
408 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000409 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000410 t.isDaemon()
411 t.setDaemon(True)
412 t.getName()
413 t.setName("name")
414 t.isAlive()
415 e = threading.Event()
416 e.isSet()
417 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000418
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000419 def test_repr_daemon(self):
420 t = threading.Thread()
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200421 self.assertNotIn('daemon', repr(t))
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000422 t.daemon = True
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200423 self.assertIn('daemon', repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000424
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000425 def test_deamon_param(self):
426 t = threading.Thread()
427 self.assertFalse(t.daemon)
428 t = threading.Thread(daemon=False)
429 self.assertFalse(t.daemon)
430 t = threading.Thread(daemon=True)
431 self.assertTrue(t.daemon)
432
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200433 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
434 def test_dummy_thread_after_fork(self):
435 # Issue #14308: a dummy thread in the active list doesn't mess up
436 # the after-fork mechanism.
437 code = """if 1:
438 import _thread, threading, os, time
439
440 def background_thread(evt):
441 # Creates and registers the _DummyThread instance
442 threading.current_thread()
443 evt.set()
444 time.sleep(10)
445
446 evt = threading.Event()
447 _thread.start_new_thread(background_thread, (evt,))
448 evt.wait()
449 assert threading.active_count() == 2, threading.active_count()
450 if os.fork() == 0:
451 assert threading.active_count() == 1, threading.active_count()
452 os._exit(0)
453 else:
454 os.wait()
455 """
456 _, out, err = assert_python_ok("-c", code)
457 self.assertEqual(out, b'')
458 self.assertEqual(err, b'')
459
Charles-François Natali9939cc82013-08-30 23:32:53 +0200460 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
461 def test_is_alive_after_fork(self):
462 # Try hard to trigger #18418: is_alive() could sometimes be True on
463 # threads that vanished after a fork.
464 old_interval = sys.getswitchinterval()
465 self.addCleanup(sys.setswitchinterval, old_interval)
466
467 # Make the bug more likely to manifest.
Xavier de Gayecb9ab0f2016-12-08 12:21:00 +0100468 test.support.setswitchinterval(1e-6)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200469
470 for i in range(20):
471 t = threading.Thread(target=lambda: None)
472 t.start()
Charles-François Natali9939cc82013-08-30 23:32:53 +0200473 pid = os.fork()
474 if pid == 0:
Victor Stinner44944b62017-05-17 14:49:38 -0700475 os._exit(11 if t.is_alive() else 10)
Charles-François Natali9939cc82013-08-30 23:32:53 +0200476 else:
Victor Stinner44944b62017-05-17 14:49:38 -0700477 t.join()
478
Charles-François Natali9939cc82013-08-30 23:32:53 +0200479 pid, status = os.waitpid(pid, 0)
Victor Stinner44944b62017-05-17 14:49:38 -0700480 self.assertTrue(os.WIFEXITED(status))
481 self.assertEqual(10, os.WEXITSTATUS(status))
Charles-François Natali9939cc82013-08-30 23:32:53 +0200482
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300483 def test_main_thread(self):
484 main = threading.main_thread()
485 self.assertEqual(main.name, 'MainThread')
486 self.assertEqual(main.ident, threading.current_thread().ident)
487 self.assertEqual(main.ident, threading.get_ident())
488
489 def f():
490 self.assertNotEqual(threading.main_thread().ident,
491 threading.current_thread().ident)
492 th = threading.Thread(target=f)
493 th.start()
494 th.join()
495
496 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
497 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
498 def test_main_thread_after_fork(self):
499 code = """if 1:
500 import os, threading
501
502 pid = os.fork()
503 if pid == 0:
504 main = threading.main_thread()
505 print(main.name)
506 print(main.ident == threading.current_thread().ident)
507 print(main.ident == threading.get_ident())
508 else:
509 os.waitpid(pid, 0)
510 """
511 _, out, err = assert_python_ok("-c", code)
512 data = out.decode().replace('\r', '')
513 self.assertEqual(err, b"")
514 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
515
516 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
517 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
518 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
519 def test_main_thread_after_fork_from_nonmain_thread(self):
520 code = """if 1:
521 import os, threading, sys
522
523 def f():
524 pid = os.fork()
525 if pid == 0:
526 main = threading.main_thread()
527 print(main.name)
528 print(main.ident == threading.current_thread().ident)
529 print(main.ident == threading.get_ident())
530 # stdout is fully buffered because not a tty,
531 # we have to flush before exit.
532 sys.stdout.flush()
533 else:
534 os.waitpid(pid, 0)
535
536 th = threading.Thread(target=f)
537 th.start()
538 th.join()
539 """
540 _, out, err = assert_python_ok("-c", code)
541 data = out.decode().replace('\r', '')
542 self.assertEqual(err, b"")
543 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
544
Antoine Pitrou7b476992013-09-07 23:38:37 +0200545 def test_tstate_lock(self):
546 # Test an implementation detail of Thread objects.
547 started = _thread.allocate_lock()
548 finish = _thread.allocate_lock()
549 started.acquire()
550 finish.acquire()
551 def f():
552 started.release()
553 finish.acquire()
554 time.sleep(0.01)
555 # The tstate lock is None until the thread is started
556 t = threading.Thread(target=f)
557 self.assertIs(t._tstate_lock, None)
558 t.start()
559 started.acquire()
560 self.assertTrue(t.is_alive())
561 # The tstate lock can't be acquired when the thread is running
562 # (or suspended).
563 tstate_lock = t._tstate_lock
564 self.assertFalse(tstate_lock.acquire(timeout=0), False)
565 finish.release()
566 # When the thread ends, the state_lock can be successfully
567 # acquired.
568 self.assertTrue(tstate_lock.acquire(timeout=5), False)
569 # But is_alive() is still True: we hold _tstate_lock now, which
570 # prevents is_alive() from knowing the thread's end-of-life C code
571 # is done.
572 self.assertTrue(t.is_alive())
573 # Let is_alive() find out the C code is done.
574 tstate_lock.release()
575 self.assertFalse(t.is_alive())
576 # And verify the thread disposed of _tstate_lock.
Serhiy Storchaka8c0f0c52016-03-14 10:28:59 +0200577 self.assertIsNone(t._tstate_lock)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200578
Tim Peters72460fa2013-09-09 18:48:24 -0500579 def test_repr_stopped(self):
580 # Verify that "stopped" shows up in repr(Thread) appropriately.
581 started = _thread.allocate_lock()
582 finish = _thread.allocate_lock()
583 started.acquire()
584 finish.acquire()
585 def f():
586 started.release()
587 finish.acquire()
588 t = threading.Thread(target=f)
589 t.start()
590 started.acquire()
591 self.assertIn("started", repr(t))
592 finish.release()
593 # "stopped" should appear in the repr in a reasonable amount of time.
594 # Implementation detail: as of this writing, that's trivially true
595 # if .join() is called, and almost trivially true if .is_alive() is
596 # called. The detail we're testing here is that "stopped" shows up
597 # "all on its own".
598 LOOKING_FOR = "stopped"
599 for i in range(500):
600 if LOOKING_FOR in repr(t):
601 break
602 time.sleep(0.01)
603 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Christian Heimes1af737c2008-01-23 08:24:23 +0000604
Tim Peters7634e1c2013-10-08 20:55:51 -0500605 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500606 # BoundedSemaphore should raise ValueError if released too often.
607 for limit in range(1, 10):
608 bs = threading.BoundedSemaphore(limit)
609 threads = [threading.Thread(target=bs.acquire)
610 for _ in range(limit)]
611 for t in threads:
612 t.start()
613 for t in threads:
614 t.join()
615 threads = [threading.Thread(target=bs.release)
616 for _ in range(limit)]
617 for t in threads:
618 t.start()
619 for t in threads:
620 t.join()
621 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500622
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200623 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100624 def test_frame_tstate_tracing(self):
625 # Issue #14432: Crash when a generator is created in a C thread that is
626 # destroyed while the generator is still used. The issue was that a
627 # generator contains a frame, and the frame kept a reference to the
628 # Python state of the destroyed C thread. The crash occurs when a trace
629 # function is setup.
630
631 def noop_trace(frame, event, arg):
632 # no operation
633 return noop_trace
634
635 def generator():
636 while 1:
Berker Peksag4882cac2015-04-14 09:30:01 +0300637 yield "generator"
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100638
639 def callback():
640 if callback.gen is None:
641 callback.gen = generator()
642 return next(callback.gen)
643 callback.gen = None
644
645 old_trace = sys.gettrace()
646 sys.settrace(noop_trace)
647 try:
648 # Install a trace function
649 threading.settrace(noop_trace)
650
651 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200652 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100653 _testcapi.call_in_temporary_c_thread(callback)
654
655 # Call the generator in a different Python thread, check that the
656 # generator didn't keep a reference to the destroyed thread state
657 for test in range(3):
658 # The trace function is still called here
659 callback()
660 finally:
661 sys.settrace(old_trace)
662
Victor Stinner45956b92013-11-12 16:37:55 +0100663
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000664class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000665
666 def _run_and_join(self, script):
667 script = """if 1:
668 import sys, os, time, threading
669
670 # a thread, which waits for the main program to terminate
671 def joiningfunc(mainthread):
672 mainthread.join()
673 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000674 # stdout is fully buffered because not a tty, we have to flush
675 # before exit.
676 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000677 \n""" + script
678
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200679 rc, out, err = assert_python_ok("-c", script)
680 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000681 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000682
683 def test_1_join_on_shutdown(self):
684 # The usual case: on exit, wait for a non-daemon thread
685 script = """if 1:
686 import os
687 t = threading.Thread(target=joiningfunc,
688 args=(threading.current_thread(),))
689 t.start()
690 time.sleep(0.1)
691 print('end of main')
692 """
693 self._run_and_join(script)
694
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000695 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200696 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000697 def test_2_join_in_forked_process(self):
698 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000699 script = """if 1:
700 childpid = os.fork()
701 if childpid != 0:
702 os.waitpid(childpid, 0)
703 sys.exit(0)
704
705 t = threading.Thread(target=joiningfunc,
706 args=(threading.current_thread(),))
707 t.start()
708 print('end of main')
709 """
710 self._run_and_join(script)
711
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000712 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200713 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000714 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000715 # Like the test above, but fork() was called from a worker thread
716 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000717
Jesse Nollera8513972008-07-17 16:49:17 +0000718 script = """if 1:
719 main_thread = threading.current_thread()
720 def worker():
721 childpid = os.fork()
722 if childpid != 0:
723 os.waitpid(childpid, 0)
724 sys.exit(0)
725
726 t = threading.Thread(target=joiningfunc,
727 args=(main_thread,))
728 print('end of main')
729 t.start()
730 t.join() # Should not block: main_thread is already stopped
731
732 w = threading.Thread(target=worker)
733 w.start()
734 """
735 self._run_and_join(script)
736
Victor Stinner26d31862011-07-01 14:26:24 +0200737 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500738 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200739 # Check that a daemon thread cannot crash the interpreter on shutdown
740 # by manipulating internal structures that are being disposed of in
741 # the main thread.
742 script = """if True:
743 import os
744 import random
745 import sys
746 import time
747 import threading
748
749 thread_has_run = set()
750
751 def random_io():
752 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200753 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200754 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200755 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200756 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200757 null_f.write(stuff)
758 time.sleep(random.random() / 1995)
759 null_f.close()
760 in_f.close()
761 thread_has_run.add(threading.current_thread())
762
763 def main():
764 count = 0
765 for _ in range(40):
766 new_thread = threading.Thread(target=random_io)
767 new_thread.daemon = True
768 new_thread.start()
769 count += 1
770 while len(thread_has_run) < count:
771 time.sleep(0.001)
772 # Trigger process shutdown
773 sys.exit(0)
774
775 main()
776 """
777 rc, out, err = assert_python_ok('-c', script)
778 self.assertFalse(err)
779
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100780 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100781 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100782 def test_reinit_tls_after_fork(self):
783 # Issue #13817: fork() would deadlock in a multithreaded program with
784 # the ad-hoc TLS implementation.
785
786 def do_fork_and_wait():
787 # just fork a child process and wait it
788 pid = os.fork()
789 if pid > 0:
790 os.waitpid(pid, 0)
791 else:
792 os._exit(0)
793
794 # start a bunch of threads that will fork() child processes
795 threads = []
796 for i in range(16):
797 t = threading.Thread(target=do_fork_and_wait)
798 threads.append(t)
799 t.start()
800
801 for t in threads:
802 t.join()
803
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200804 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
805 def test_clear_threads_states_after_fork(self):
806 # Issue #17094: check that threads states are cleared after fork()
807
808 # start a bunch of threads
809 threads = []
810 for i in range(16):
811 t = threading.Thread(target=lambda : time.sleep(0.3))
812 threads.append(t)
813 t.start()
814
815 pid = os.fork()
816 if pid == 0:
817 # check that threads states have been cleared
818 if len(sys._current_frames()) == 1:
819 os._exit(0)
820 else:
821 os._exit(1)
822 else:
823 _, status = os.waitpid(pid, 0)
824 self.assertEqual(0, status)
825
826 for t in threads:
827 t.join()
828
Jesse Nollera8513972008-07-17 16:49:17 +0000829
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200830class SubinterpThreadingTests(BaseTestCase):
831
832 def test_threads_join(self):
833 # Non-daemon threads should be joined at subinterpreter shutdown
834 # (issue #18808)
835 r, w = os.pipe()
836 self.addCleanup(os.close, r)
837 self.addCleanup(os.close, w)
838 code = r"""if 1:
839 import os
840 import threading
841 import time
842
843 def f():
844 # Sleep a bit so that the thread is still running when
845 # Py_EndInterpreter is called.
846 time.sleep(0.05)
847 os.write(%d, b"x")
848 threading.Thread(target=f).start()
849 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100850 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200851 self.assertEqual(ret, 0)
852 # The thread was joined properly.
853 self.assertEqual(os.read(r, 1), b"x")
854
Antoine Pitrou7b476992013-09-07 23:38:37 +0200855 def test_threads_join_2(self):
856 # Same as above, but a delay gets introduced after the thread's
857 # Python code returned but before the thread state is deleted.
858 # To achieve this, we register a thread-local object which sleeps
859 # a bit when deallocated.
860 r, w = os.pipe()
861 self.addCleanup(os.close, r)
862 self.addCleanup(os.close, w)
863 code = r"""if 1:
864 import os
865 import threading
866 import time
867
868 class Sleeper:
869 def __del__(self):
870 time.sleep(0.05)
871
872 tls = threading.local()
873
874 def f():
875 # Sleep a bit so that the thread is still running when
876 # Py_EndInterpreter is called.
877 time.sleep(0.05)
878 tls.x = Sleeper()
879 os.write(%d, b"x")
880 threading.Thread(target=f).start()
881 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100882 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200883 self.assertEqual(ret, 0)
884 # The thread was joined properly.
885 self.assertEqual(os.read(r, 1), b"x")
886
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200887 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200888 def test_daemon_threads_fatal_error(self):
889 subinterp_code = r"""if 1:
890 import os
891 import threading
892 import time
893
894 def f():
895 # Make sure the daemon thread is still running when
896 # Py_EndInterpreter is called.
897 time.sleep(10)
898 threading.Thread(target=f, daemon=True).start()
899 """
900 script = r"""if 1:
901 import _testcapi
902
903 _testcapi.run_in_subinterp(%r)
904 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200905 with test.support.SuppressCrashReport():
906 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200907 self.assertIn("Fatal Python error: Py_EndInterpreter: "
908 "not the last thread", err.decode())
909
910
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000911class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000912 # A RuntimeError should be raised if Thread.start() is called
913 # multiple times.
914 def test_start_thread_again(self):
915 thread = threading.Thread()
916 thread.start()
917 self.assertRaises(RuntimeError, thread.start)
918
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000919 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000920 current_thread = threading.current_thread()
921 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000922
923 def test_joining_inactive_thread(self):
924 thread = threading.Thread()
925 self.assertRaises(RuntimeError, thread.join)
926
927 def test_daemonize_active_thread(self):
928 thread = threading.Thread()
929 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000930 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000931
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000932 def test_releasing_unacquired_lock(self):
933 lock = threading.Lock()
934 self.assertRaises(RuntimeError, lock.release)
935
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400936 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
937 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700938 def test_recursion_limit(self):
939 # Issue 9670
940 # test that excessive recursion within a non-main thread causes
941 # an exception rather than crashing the interpreter on platforms
942 # like Mac OS X or FreeBSD which have small default stack sizes
943 # for threads
944 script = """if True:
945 import threading
946
947 def recurse():
948 return recurse()
949
950 def outer():
951 try:
952 recurse()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400953 except RecursionError:
Ned Deily9a7c5242011-05-28 00:19:56 -0700954 pass
955
956 w = threading.Thread(target=outer)
957 w.start()
958 w.join()
959 print('end of main thread')
960 """
961 expected_output = "end of main thread\n"
962 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200963 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -0700964 stdout, stderr = p.communicate()
965 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +0200966 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -0700967 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000968
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300969 def test_print_exception(self):
970 script = r"""if True:
971 import threading
972 import time
973
974 running = False
975 def run():
976 global running
977 running = True
978 while running:
979 time.sleep(0.01)
980 1/0
981 t = threading.Thread(target=run)
982 t.start()
983 while not running:
984 time.sleep(0.01)
985 running = False
986 t.join()
987 """
988 rc, out, err = assert_python_ok("-c", script)
989 self.assertEqual(out, b'')
990 err = err.decode()
991 self.assertIn("Exception in thread", err)
992 self.assertIn("Traceback (most recent call last):", err)
993 self.assertIn("ZeroDivisionError", err)
994 self.assertNotIn("Unhandled exception", err)
995
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300996 @requires_type_collecting
Serhiy Storchaka52005c22014-09-21 22:08:13 +0300997 def test_print_exception_stderr_is_none_1(self):
998 script = r"""if True:
999 import sys
1000 import threading
1001 import time
1002
1003 running = False
1004 def run():
1005 global running
1006 running = True
1007 while running:
1008 time.sleep(0.01)
1009 1/0
1010 t = threading.Thread(target=run)
1011 t.start()
1012 while not running:
1013 time.sleep(0.01)
1014 sys.stderr = None
1015 running = False
1016 t.join()
1017 """
1018 rc, out, err = assert_python_ok("-c", script)
1019 self.assertEqual(out, b'')
1020 err = err.decode()
1021 self.assertIn("Exception in thread", err)
1022 self.assertIn("Traceback (most recent call last):", err)
1023 self.assertIn("ZeroDivisionError", err)
1024 self.assertNotIn("Unhandled exception", err)
1025
1026 def test_print_exception_stderr_is_none_2(self):
1027 script = r"""if True:
1028 import sys
1029 import threading
1030 import time
1031
1032 running = False
1033 def run():
1034 global running
1035 running = True
1036 while running:
1037 time.sleep(0.01)
1038 1/0
1039 sys.stderr = None
1040 t = threading.Thread(target=run)
1041 t.start()
1042 while not running:
1043 time.sleep(0.01)
1044 running = False
1045 t.join()
1046 """
1047 rc, out, err = assert_python_ok("-c", script)
1048 self.assertEqual(out, b'')
1049 self.assertNotIn("Unhandled exception", err.decode())
1050
Victor Stinnereec93312016-08-18 18:13:10 +02001051 def test_bare_raise_in_brand_new_thread(self):
1052 def bare_raise():
1053 raise
1054
1055 class Issue27558(threading.Thread):
1056 exc = None
1057
1058 def run(self):
1059 try:
1060 bare_raise()
1061 except Exception as exc:
1062 self.exc = exc
1063
1064 thread = Issue27558()
1065 thread.start()
1066 thread.join()
1067 self.assertIsNotNone(thread.exc)
1068 self.assertIsInstance(thread.exc, RuntimeError)
Serhiy Storchaka52005c22014-09-21 22:08:13 +03001069
R David Murray19aeb432013-03-30 17:19:38 -04001070class TimerTests(BaseTestCase):
1071
1072 def setUp(self):
1073 BaseTestCase.setUp(self)
1074 self.callback_args = []
1075 self.callback_event = threading.Event()
1076
1077 def test_init_immutable_default_args(self):
1078 # Issue 17435: constructor defaults were mutable objects, they could be
1079 # mutated via the object attributes and affect other Timer objects.
1080 timer1 = threading.Timer(0.01, self._callback_spy)
1081 timer1.start()
1082 self.callback_event.wait()
1083 timer1.args.append("blah")
1084 timer1.kwargs["foo"] = "bar"
1085 self.callback_event.clear()
1086 timer2 = threading.Timer(0.01, self._callback_spy)
1087 timer2.start()
1088 self.callback_event.wait()
1089 self.assertEqual(len(self.callback_args), 2)
1090 self.assertEqual(self.callback_args, [((), {}), ((), {})])
1091
1092 def _callback_spy(self, *args, **kwargs):
1093 self.callback_args.append((args[:], kwargs.copy()))
1094 self.callback_event.set()
1095
Antoine Pitrou557934f2009-11-06 22:41:14 +00001096class LockTests(lock_tests.LockTests):
1097 locktype = staticmethod(threading.Lock)
1098
Antoine Pitrou434736a2009-11-10 18:46:01 +00001099class PyRLockTests(lock_tests.RLockTests):
1100 locktype = staticmethod(threading._PyRLock)
1101
Charles-François Natali6b671b22012-01-28 11:36:04 +01001102@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001103class CRLockTests(lock_tests.RLockTests):
1104 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001105
1106class EventTests(lock_tests.EventTests):
1107 eventtype = staticmethod(threading.Event)
1108
1109class ConditionAsRLockTests(lock_tests.RLockTests):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001110 # Condition uses an RLock by default and exports its API.
Antoine Pitrou557934f2009-11-06 22:41:14 +00001111 locktype = staticmethod(threading.Condition)
1112
1113class ConditionTests(lock_tests.ConditionTests):
1114 condtype = staticmethod(threading.Condition)
1115
1116class SemaphoreTests(lock_tests.SemaphoreTests):
1117 semtype = staticmethod(threading.Semaphore)
1118
1119class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1120 semtype = staticmethod(threading.BoundedSemaphore)
1121
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001122class BarrierTests(lock_tests.BarrierTests):
1123 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001124
Martin Panter19e69c52015-11-14 12:46:42 +00001125class MiscTestCase(unittest.TestCase):
1126 def test__all__(self):
1127 extra = {"ThreadError"}
1128 blacklist = {'currentThread', 'activeCount'}
1129 support.check__all__(self, threading, ('threading', '_thread'),
1130 extra=extra, blacklist=blacklist)
1131
Tim Peters84d54892005-01-08 06:03:17 +00001132if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001133 unittest.main()