blob: ad363582317f6b16bdc00fa1497a4a9b49013591 [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 Storchaka5cfc79d2014-02-07 10:06:39 +02006from test.support import verbose, strip_python_stderr, import_module, cpython_only
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')
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
Antoine Pitrouc4d78642011-05-05 20:17:32 +020018from test.script_helper import assert_python_ok, assert_python_failure
Gregory P. Smith4b129d22011-01-04 00:51:50 +000019import subprocess
Skip Montanaro4533f602001-08-20 20:28:48 +000020
Antoine Pitrou557934f2009-11-06 22:41:14 +000021from test import lock_tests
22
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')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000062 self.testcase.assertTrue(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()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000070 self.testcase.assertTrue(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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000104 self.assertEqual(t.ident, None)
105 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
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()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000112 self.assertTrue(not t.is_alive())
113 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000114 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000115 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
116 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000117 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000118 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000119 self.assertEqual(numrunning.get(), 0)
120
Benjamin Petersond23f8222009-04-05 19:13:16 +0000121 def test_ident_of_no_threading_threads(self):
122 # The ident still must work for the main thread and dummy threads.
123 self.assertFalse(threading.currentThread().ident is None)
124 def f():
125 ident.append(threading.currentThread().ident)
126 done.set()
127 done = threading.Event()
128 ident = []
129 _thread.start_new_thread(f, ())
130 done.wait()
131 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000132 # Kill the "immortal" _DummyThread
133 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000134
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 # run with a small(ish) thread stack size (256kB)
136 def test_various_ops_small_stack(self):
137 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000138 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 try:
140 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000141 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000142 raise unittest.SkipTest(
143 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 self.test_various_ops()
145 threading.stack_size(0)
146
147 # run with a large thread stack size (1MB)
148 def test_various_ops_large_stack(self):
149 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000150 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151 try:
152 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000153 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000154 raise unittest.SkipTest(
155 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156 self.test_various_ops()
157 threading.stack_size(0)
158
Tim Peters711906e2005-01-08 07:30:42 +0000159 def test_foreign_thread(self):
160 # Check that a "foreign" thread can use the threading module.
161 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000162 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000163 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000164 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000165 mutex.release()
166
167 mutex = threading.Lock()
168 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000169 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000170 # Wait for the thread to finish.
171 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000172 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000173 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000174 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000175
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000176 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
177 # exposed at the Python level. This test relies on ctypes to get at it.
178 def test_PyThreadState_SetAsyncExc(self):
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200179 ctypes = import_module("ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180
181 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
182
183 class AsyncExc(Exception):
184 pass
185
186 exception = ctypes.py_object(AsyncExc)
187
Antoine Pitroube4d8092009-10-18 18:27:17 +0000188 # First check it works when setting the exception from the same thread.
Victor Stinner2a129742011-05-30 23:02:52 +0200189 tid = threading.get_ident()
Antoine Pitroube4d8092009-10-18 18:27:17 +0000190
191 try:
192 result = set_async_exc(ctypes.c_long(tid), exception)
193 # The exception is async, so we might have to keep the VM busy until
194 # it notices.
195 while True:
196 pass
197 except AsyncExc:
198 pass
199 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000200 # This code is unreachable but it reflects the intent. If we wanted
201 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000202 self.fail("AsyncExc not raised")
203 try:
204 self.assertEqual(result, 1) # one thread state modified
205 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000206 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000207 pass
208
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000209 # `worker_started` is set by the thread when it's inside a try/except
210 # block waiting to catch the asynchronously set AsyncExc exception.
211 # `worker_saw_exception` is set by the thread upon catching that
212 # exception.
213 worker_started = threading.Event()
214 worker_saw_exception = threading.Event()
215
216 class Worker(threading.Thread):
217 def run(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200218 self.id = threading.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000219 self.finished = False
220
221 try:
222 while True:
223 worker_started.set()
224 time.sleep(0.1)
225 except AsyncExc:
226 self.finished = True
227 worker_saw_exception.set()
228
229 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000230 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000231 t.start()
232 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000233 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000234
235 # Try a thread id that doesn't make sense.
236 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000237 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000238 result = set_async_exc(ctypes.c_long(-1), exception)
239 self.assertEqual(result, 0) # no thread states modified
240
241 # Now raise an exception in the worker thread.
242 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000244 ret = worker_started.wait()
245 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000249 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000251 result = set_async_exc(ctypes.c_long(t.id), exception)
252 self.assertEqual(result, 1) # one thread state modified
253 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000254 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000255 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000256 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000257 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000258 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000259 if t.finished:
260 t.join()
261 # else the thread is still running, and we have no way to kill it
262
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000263 def test_limbo_cleanup(self):
264 # Issue 7481: Failure to start thread should cleanup the limbo map.
265 def fail_new_thread(*args):
266 raise threading.ThreadError()
267 _start_new_thread = threading._start_new_thread
268 threading._start_new_thread = fail_new_thread
269 try:
270 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000271 self.assertRaises(threading.ThreadError, t.start)
272 self.assertFalse(
273 t in threading._limbo,
274 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000275 finally:
276 threading._start_new_thread = _start_new_thread
277
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278 def test_finalize_runnning_thread(self):
279 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
280 # very late on python exit: on deallocation of a running thread for
281 # example.
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200282 import_module("ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000283
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200284 rc, out, err = assert_python_failure("-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000285 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000286
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000287 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000288 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000289 ready.acquire()
290
Christian Heimes7d2ff882007-11-30 14:35:04 +0000291 # Module globals are cleared before __del__ is run
292 # So we save the functions in class dict
293 class C:
294 ensure = ctypes.pythonapi.PyGILState_Ensure
295 release = ctypes.pythonapi.PyGILState_Release
296 def __del__(self):
297 state = self.ensure()
298 self.release(state)
299
300 def waitingThread():
301 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000302 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000303 time.sleep(100)
304
Georg Brandl2067bfd2008-05-25 13:05:15 +0000305 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000306 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000307 sys.exit(42)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200308 """)
Christian Heimes7d2ff882007-11-30 14:35:04 +0000309 self.assertEqual(rc, 42)
310
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000311 def test_finalize_with_trace(self):
312 # Issue1733757
313 # Avoid a deadlock when sys.settrace steps into threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200314 assert_python_ok("-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000315 import sys, threading
316
317 # A deadlock-killer, to prevent the
318 # testsuite to hang forever
319 def killer():
320 import os, time
321 time.sleep(2)
322 print('program blocked; aborting')
323 os._exit(2)
324 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000325 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000326 t.start()
327
328 # This is the trace function
329 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000330 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000331 return func
332
333 sys.settrace(func)
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200334 """)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000335
Antoine Pitrou011bd622009-10-20 21:52:47 +0000336 def test_join_nondaemon_on_shutdown(self):
337 # Issue 1722344
338 # Raising SystemExit skipped threading._shutdown
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200339 rc, out, err = assert_python_ok("-c", """if 1:
Antoine Pitrou011bd622009-10-20 21:52:47 +0000340 import threading
341 from time import sleep
342
343 def child():
344 sleep(1)
345 # As a non-daemon thread we SHOULD wake up and nothing
346 # should be torn down yet
347 print("Woke up, sleep function is:", sleep)
348
349 threading.Thread(target=child).start()
350 raise SystemExit
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200351 """)
352 self.assertEqual(out.strip(),
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000353 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200354 self.assertEqual(err, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000355
Christian Heimes1af737c2008-01-23 08:24:23 +0000356 def test_enumerate_after_join(self):
357 # Try hard to trigger #1703448: a thread is still returned in
358 # threading.enumerate() after it has been join()ed.
359 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000360 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000361 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000362 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000363 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000364 t = threading.Thread(target=lambda: None)
365 t.start()
366 t.join()
367 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000368 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000369 "#1703448 triggered after %d trials: %s" % (i, l))
370 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000371 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000372
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000373 def test_no_refcycle_through_target(self):
374 class RunSelfFunction(object):
375 def __init__(self, should_raise):
376 # The links in this refcycle from Thread back to self
377 # should be cleaned up when the thread completes.
378 self.should_raise = should_raise
379 self.thread = threading.Thread(target=self._run,
380 args=(self,),
381 kwargs={'yet_another':self})
382 self.thread.start()
383
384 def _run(self, other_ref, yet_another):
385 if self.should_raise:
386 raise SystemExit
387
388 cyclic_object = RunSelfFunction(should_raise=False)
389 weak_cyclic_object = weakref.ref(cyclic_object)
390 cyclic_object.thread.join()
391 del cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000392 self.assertIsNone(weak_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000393 msg=('%d references still around' %
394 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000395
396 raising_cyclic_object = RunSelfFunction(should_raise=True)
397 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
398 raising_cyclic_object.thread.join()
399 del raising_cyclic_object
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000400 self.assertIsNone(weak_raising_cyclic_object(),
Ezio Melottib3aedd42010-11-20 19:04:17 +0000401 msg=('%d references still around' %
402 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000403
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000404 def test_old_threading_api(self):
405 # Just a quick sanity check to make sure the old method names are
406 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000407 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000408 t.isDaemon()
409 t.setDaemon(True)
410 t.getName()
411 t.setName("name")
412 t.isAlive()
413 e = threading.Event()
414 e.isSet()
415 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000416
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000417 def test_repr_daemon(self):
418 t = threading.Thread()
419 self.assertFalse('daemon' in repr(t))
420 t.daemon = True
421 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000422
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000423 def test_deamon_param(self):
424 t = threading.Thread()
425 self.assertFalse(t.daemon)
426 t = threading.Thread(daemon=False)
427 self.assertFalse(t.daemon)
428 t = threading.Thread(daemon=True)
429 self.assertTrue(t.daemon)
430
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200431 @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
432 def test_dummy_thread_after_fork(self):
433 # Issue #14308: a dummy thread in the active list doesn't mess up
434 # the after-fork mechanism.
435 code = """if 1:
436 import _thread, threading, os, time
437
438 def background_thread(evt):
439 # Creates and registers the _DummyThread instance
440 threading.current_thread()
441 evt.set()
442 time.sleep(10)
443
444 evt = threading.Event()
445 _thread.start_new_thread(background_thread, (evt,))
446 evt.wait()
447 assert threading.active_count() == 2, threading.active_count()
448 if os.fork() == 0:
449 assert threading.active_count() == 1, threading.active_count()
450 os._exit(0)
451 else:
452 os.wait()
453 """
454 _, out, err = assert_python_ok("-c", code)
455 self.assertEqual(out, b'')
456 self.assertEqual(err, b'')
457
Charles-François Natali9939cc82013-08-30 23:32:53 +0200458 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
459 def test_is_alive_after_fork(self):
460 # Try hard to trigger #18418: is_alive() could sometimes be True on
461 # threads that vanished after a fork.
462 old_interval = sys.getswitchinterval()
463 self.addCleanup(sys.setswitchinterval, old_interval)
464
465 # Make the bug more likely to manifest.
466 sys.setswitchinterval(1e-6)
467
468 for i in range(20):
469 t = threading.Thread(target=lambda: None)
470 t.start()
471 self.addCleanup(t.join)
472 pid = os.fork()
473 if pid == 0:
474 os._exit(1 if t.is_alive() else 0)
475 else:
476 pid, status = os.waitpid(pid, 0)
477 self.assertEqual(0, status)
478
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300479 def test_main_thread(self):
480 main = threading.main_thread()
481 self.assertEqual(main.name, 'MainThread')
482 self.assertEqual(main.ident, threading.current_thread().ident)
483 self.assertEqual(main.ident, threading.get_ident())
484
485 def f():
486 self.assertNotEqual(threading.main_thread().ident,
487 threading.current_thread().ident)
488 th = threading.Thread(target=f)
489 th.start()
490 th.join()
491
492 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
493 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
494 def test_main_thread_after_fork(self):
495 code = """if 1:
496 import os, threading
497
498 pid = os.fork()
499 if pid == 0:
500 main = threading.main_thread()
501 print(main.name)
502 print(main.ident == threading.current_thread().ident)
503 print(main.ident == threading.get_ident())
504 else:
505 os.waitpid(pid, 0)
506 """
507 _, out, err = assert_python_ok("-c", code)
508 data = out.decode().replace('\r', '')
509 self.assertEqual(err, b"")
510 self.assertEqual(data, "MainThread\nTrue\nTrue\n")
511
512 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
513 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
514 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
515 def test_main_thread_after_fork_from_nonmain_thread(self):
516 code = """if 1:
517 import os, threading, sys
518
519 def f():
520 pid = os.fork()
521 if pid == 0:
522 main = threading.main_thread()
523 print(main.name)
524 print(main.ident == threading.current_thread().ident)
525 print(main.ident == threading.get_ident())
526 # stdout is fully buffered because not a tty,
527 # we have to flush before exit.
528 sys.stdout.flush()
529 else:
530 os.waitpid(pid, 0)
531
532 th = threading.Thread(target=f)
533 th.start()
534 th.join()
535 """
536 _, out, err = assert_python_ok("-c", code)
537 data = out.decode().replace('\r', '')
538 self.assertEqual(err, b"")
539 self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
540
Antoine Pitrou7b476992013-09-07 23:38:37 +0200541 def test_tstate_lock(self):
542 # Test an implementation detail of Thread objects.
543 started = _thread.allocate_lock()
544 finish = _thread.allocate_lock()
545 started.acquire()
546 finish.acquire()
547 def f():
548 started.release()
549 finish.acquire()
550 time.sleep(0.01)
551 # The tstate lock is None until the thread is started
552 t = threading.Thread(target=f)
553 self.assertIs(t._tstate_lock, None)
554 t.start()
555 started.acquire()
556 self.assertTrue(t.is_alive())
557 # The tstate lock can't be acquired when the thread is running
558 # (or suspended).
559 tstate_lock = t._tstate_lock
560 self.assertFalse(tstate_lock.acquire(timeout=0), False)
561 finish.release()
562 # When the thread ends, the state_lock can be successfully
563 # acquired.
564 self.assertTrue(tstate_lock.acquire(timeout=5), False)
565 # But is_alive() is still True: we hold _tstate_lock now, which
566 # prevents is_alive() from knowing the thread's end-of-life C code
567 # is done.
568 self.assertTrue(t.is_alive())
569 # Let is_alive() find out the C code is done.
570 tstate_lock.release()
571 self.assertFalse(t.is_alive())
572 # And verify the thread disposed of _tstate_lock.
573 self.assertTrue(t._tstate_lock is None)
574
Tim Peters72460fa2013-09-09 18:48:24 -0500575 def test_repr_stopped(self):
576 # Verify that "stopped" shows up in repr(Thread) appropriately.
577 started = _thread.allocate_lock()
578 finish = _thread.allocate_lock()
579 started.acquire()
580 finish.acquire()
581 def f():
582 started.release()
583 finish.acquire()
584 t = threading.Thread(target=f)
585 t.start()
586 started.acquire()
587 self.assertIn("started", repr(t))
588 finish.release()
589 # "stopped" should appear in the repr in a reasonable amount of time.
590 # Implementation detail: as of this writing, that's trivially true
591 # if .join() is called, and almost trivially true if .is_alive() is
592 # called. The detail we're testing here is that "stopped" shows up
593 # "all on its own".
594 LOOKING_FOR = "stopped"
595 for i in range(500):
596 if LOOKING_FOR in repr(t):
597 break
598 time.sleep(0.01)
599 self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
Christian Heimes1af737c2008-01-23 08:24:23 +0000600
Tim Peters7634e1c2013-10-08 20:55:51 -0500601 def test_BoundedSemaphore_limit(self):
Tim Peters3d1b7a02013-10-08 21:29:27 -0500602 # BoundedSemaphore should raise ValueError if released too often.
603 for limit in range(1, 10):
604 bs = threading.BoundedSemaphore(limit)
605 threads = [threading.Thread(target=bs.acquire)
606 for _ in range(limit)]
607 for t in threads:
608 t.start()
609 for t in threads:
610 t.join()
611 threads = [threading.Thread(target=bs.release)
612 for _ in range(limit)]
613 for t in threads:
614 t.start()
615 for t in threads:
616 t.join()
617 self.assertRaises(ValueError, bs.release)
Tim Peters7634e1c2013-10-08 20:55:51 -0500618
Victor Stinner45956b92013-11-12 16:37:55 +0100619 def test_locals_at_exit(self):
620 # Issue #19466: thread locals must not be deleted before destructors
621 # are called
622 rc, out, err = assert_python_ok("-c", """if 1:
623 import threading
624
625 class Atexit:
626 def __del__(self):
627 print("thread_dict.atexit = %r" % thread_dict.atexit)
628
629 thread_dict = threading.local()
630 thread_dict.atexit = "atexit"
631
632 atexit = Atexit()
633 """)
634 self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'atexit'")
635
636 def test_warnings_at_exit(self):
637 # Issue #19466: try to call most destructors at Python shutdown before
638 # destroying Python thread states
639 filename = __file__
640 rc, out, err = assert_python_ok("-Wd", "-c", """if 1:
641 import time
642 import threading
643
644 def open_sleep():
645 # a warning will be emitted when the open file will be
646 # destroyed (without being explicitly closed) while the daemon
647 # thread is destroyed
648 fileobj = open(%a, 'rb')
649 start_event.set()
650 time.sleep(60.0)
651
652 start_event = threading.Event()
653
654 thread = threading.Thread(target=open_sleep)
655 thread.daemon = True
656 thread.start()
657
658 # wait until the thread started
659 start_event.wait()
660 """ % filename)
661 self.assertRegex(err.rstrip(),
662 b"^sys:1: ResourceWarning: unclosed file ")
663
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200664 @cpython_only
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100665 def test_frame_tstate_tracing(self):
666 # Issue #14432: Crash when a generator is created in a C thread that is
667 # destroyed while the generator is still used. The issue was that a
668 # generator contains a frame, and the frame kept a reference to the
669 # Python state of the destroyed C thread. The crash occurs when a trace
670 # function is setup.
671
672 def noop_trace(frame, event, arg):
673 # no operation
674 return noop_trace
675
676 def generator():
677 while 1:
678 yield "genereator"
679
680 def callback():
681 if callback.gen is None:
682 callback.gen = generator()
683 return next(callback.gen)
684 callback.gen = None
685
686 old_trace = sys.gettrace()
687 sys.settrace(noop_trace)
688 try:
689 # Install a trace function
690 threading.settrace(noop_trace)
691
692 # Create a generator in a C thread which exits after the call
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200693 import _testcapi
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100694 _testcapi.call_in_temporary_c_thread(callback)
695
696 # Call the generator in a different Python thread, check that the
697 # generator didn't keep a reference to the destroyed thread state
698 for test in range(3):
699 # The trace function is still called here
700 callback()
701 finally:
702 sys.settrace(old_trace)
703
Victor Stinner45956b92013-11-12 16:37:55 +0100704
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000705class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000706
707 def _run_and_join(self, script):
708 script = """if 1:
709 import sys, os, time, threading
710
711 # a thread, which waits for the main program to terminate
712 def joiningfunc(mainthread):
713 mainthread.join()
714 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000715 # stdout is fully buffered because not a tty, we have to flush
716 # before exit.
717 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000718 \n""" + script
719
Antoine Pitrouc4d78642011-05-05 20:17:32 +0200720 rc, out, err = assert_python_ok("-c", script)
721 data = out.decode().replace('\r', '')
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000722 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000723
724 def test_1_join_on_shutdown(self):
725 # The usual case: on exit, wait for a non-daemon thread
726 script = """if 1:
727 import os
728 t = threading.Thread(target=joiningfunc,
729 args=(threading.current_thread(),))
730 t.start()
731 time.sleep(0.1)
732 print('end of main')
733 """
734 self._run_and_join(script)
735
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000736 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200737 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Jesse Nollera8513972008-07-17 16:49:17 +0000738 def test_2_join_in_forked_process(self):
739 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000740 script = """if 1:
741 childpid = os.fork()
742 if childpid != 0:
743 os.waitpid(childpid, 0)
744 sys.exit(0)
745
746 t = threading.Thread(target=joiningfunc,
747 args=(threading.current_thread(),))
748 t.start()
749 print('end of main')
750 """
751 self._run_and_join(script)
752
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000753 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Victor Stinner26d31862011-07-01 14:26:24 +0200754 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000755 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000756 # Like the test above, but fork() was called from a worker thread
757 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000758
Jesse Nollera8513972008-07-17 16:49:17 +0000759 script = """if 1:
760 main_thread = threading.current_thread()
761 def worker():
762 childpid = os.fork()
763 if childpid != 0:
764 os.waitpid(childpid, 0)
765 sys.exit(0)
766
767 t = threading.Thread(target=joiningfunc,
768 args=(main_thread,))
769 print('end of main')
770 t.start()
771 t.join() # Should not block: main_thread is already stopped
772
773 w = threading.Thread(target=worker)
774 w.start()
775 """
776 self._run_and_join(script)
777
Victor Stinner26d31862011-07-01 14:26:24 +0200778 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Tim Petersc363a232013-09-08 18:44:40 -0500779 def test_4_daemon_threads(self):
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200780 # Check that a daemon thread cannot crash the interpreter on shutdown
781 # by manipulating internal structures that are being disposed of in
782 # the main thread.
783 script = """if True:
784 import os
785 import random
786 import sys
787 import time
788 import threading
Victor Stinner45956b92013-11-12 16:37:55 +0100789 import warnings
790
791 # ignore "unclosed file ..." warnings
792 warnings.filterwarnings('ignore', '', ResourceWarning)
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200793
794 thread_has_run = set()
795
796 def random_io():
797 '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200798 while True:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200799 in_f = open(os.__file__, 'rb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200800 stuff = in_f.read(200)
Victor Stinnera6d2c762011-06-30 18:20:11 +0200801 null_f = open(os.devnull, 'wb')
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200802 null_f.write(stuff)
803 time.sleep(random.random() / 1995)
804 null_f.close()
805 in_f.close()
806 thread_has_run.add(threading.current_thread())
807
808 def main():
809 count = 0
810 for _ in range(40):
811 new_thread = threading.Thread(target=random_io)
812 new_thread.daemon = True
813 new_thread.start()
814 count += 1
815 while len(thread_has_run) < count:
816 time.sleep(0.001)
817 # Trigger process shutdown
818 sys.exit(0)
819
820 main()
821 """
822 rc, out, err = assert_python_ok('-c', script)
823 self.assertFalse(err)
824
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100825 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Charles-François Natalib2c9e9a2012-02-08 21:29:11 +0100826 @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
Charles-François Natali6d0d24e2012-02-02 20:31:42 +0100827 def test_reinit_tls_after_fork(self):
828 # Issue #13817: fork() would deadlock in a multithreaded program with
829 # the ad-hoc TLS implementation.
830
831 def do_fork_and_wait():
832 # just fork a child process and wait it
833 pid = os.fork()
834 if pid > 0:
835 os.waitpid(pid, 0)
836 else:
837 os._exit(0)
838
839 # start a bunch of threads that will fork() child processes
840 threads = []
841 for i in range(16):
842 t = threading.Thread(target=do_fork_and_wait)
843 threads.append(t)
844 t.start()
845
846 for t in threads:
847 t.join()
848
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200849 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
850 def test_clear_threads_states_after_fork(self):
851 # Issue #17094: check that threads states are cleared after fork()
852
853 # start a bunch of threads
854 threads = []
855 for i in range(16):
856 t = threading.Thread(target=lambda : time.sleep(0.3))
857 threads.append(t)
858 t.start()
859
860 pid = os.fork()
861 if pid == 0:
862 # check that threads states have been cleared
863 if len(sys._current_frames()) == 1:
864 os._exit(0)
865 else:
866 os._exit(1)
867 else:
868 _, status = os.waitpid(pid, 0)
869 self.assertEqual(0, status)
870
871 for t in threads:
872 t.join()
873
Jesse Nollera8513972008-07-17 16:49:17 +0000874
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200875class SubinterpThreadingTests(BaseTestCase):
876
877 def test_threads_join(self):
878 # Non-daemon threads should be joined at subinterpreter shutdown
879 # (issue #18808)
880 r, w = os.pipe()
881 self.addCleanup(os.close, r)
882 self.addCleanup(os.close, w)
883 code = r"""if 1:
884 import os
885 import threading
886 import time
887
888 def f():
889 # Sleep a bit so that the thread is still running when
890 # Py_EndInterpreter is called.
891 time.sleep(0.05)
892 os.write(%d, b"x")
893 threading.Thread(target=f).start()
894 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100895 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200896 self.assertEqual(ret, 0)
897 # The thread was joined properly.
898 self.assertEqual(os.read(r, 1), b"x")
899
Antoine Pitrou7b476992013-09-07 23:38:37 +0200900 def test_threads_join_2(self):
901 # Same as above, but a delay gets introduced after the thread's
902 # Python code returned but before the thread state is deleted.
903 # To achieve this, we register a thread-local object which sleeps
904 # a bit when deallocated.
905 r, w = os.pipe()
906 self.addCleanup(os.close, r)
907 self.addCleanup(os.close, w)
908 code = r"""if 1:
909 import os
910 import threading
911 import time
912
913 class Sleeper:
914 def __del__(self):
915 time.sleep(0.05)
916
917 tls = threading.local()
918
919 def f():
920 # Sleep a bit so that the thread is still running when
921 # Py_EndInterpreter is called.
922 time.sleep(0.05)
923 tls.x = Sleeper()
924 os.write(%d, b"x")
925 threading.Thread(target=f).start()
926 """ % (w,)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100927 ret = test.support.run_in_subinterp(code)
Antoine Pitrou7b476992013-09-07 23:38:37 +0200928 self.assertEqual(ret, 0)
929 # The thread was joined properly.
930 self.assertEqual(os.read(r, 1), b"x")
931
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200932 @cpython_only
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200933 def test_daemon_threads_fatal_error(self):
934 subinterp_code = r"""if 1:
935 import os
936 import threading
937 import time
938
939 def f():
940 # Make sure the daemon thread is still running when
941 # Py_EndInterpreter is called.
942 time.sleep(10)
943 threading.Thread(target=f, daemon=True).start()
944 """
945 script = r"""if 1:
946 import _testcapi
947
948 _testcapi.run_in_subinterp(%r)
949 """ % (subinterp_code,)
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200950 with test.support.SuppressCrashReport():
951 rc, out, err = assert_python_failure("-c", script)
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200952 self.assertIn("Fatal Python error: Py_EndInterpreter: "
953 "not the last thread", err.decode())
954
955
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000956class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000957 # A RuntimeError should be raised if Thread.start() is called
958 # multiple times.
959 def test_start_thread_again(self):
960 thread = threading.Thread()
961 thread.start()
962 self.assertRaises(RuntimeError, thread.start)
963
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000964 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000965 current_thread = threading.current_thread()
966 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000967
968 def test_joining_inactive_thread(self):
969 thread = threading.Thread()
970 self.assertRaises(RuntimeError, thread.join)
971
972 def test_daemonize_active_thread(self):
973 thread = threading.Thread()
974 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000975 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000976
Antoine Pitroufcf81fd2011-02-28 22:03:34 +0000977 def test_releasing_unacquired_lock(self):
978 lock = threading.Lock()
979 self.assertRaises(RuntimeError, lock.release)
980
Benjamin Petersond541d3f2012-10-13 11:46:44 -0400981 @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(),
982 'test macosx problem')
Ned Deily9a7c5242011-05-28 00:19:56 -0700983 def test_recursion_limit(self):
984 # Issue 9670
985 # test that excessive recursion within a non-main thread causes
986 # an exception rather than crashing the interpreter on platforms
987 # like Mac OS X or FreeBSD which have small default stack sizes
988 # for threads
989 script = """if True:
990 import threading
991
992 def recurse():
993 return recurse()
994
995 def outer():
996 try:
997 recurse()
998 except RuntimeError:
999 pass
1000
1001 w = threading.Thread(target=outer)
1002 w.start()
1003 w.join()
1004 print('end of main thread')
1005 """
1006 expected_output = "end of main thread\n"
1007 p = subprocess.Popen([sys.executable, "-c", script],
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001008 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Ned Deily9a7c5242011-05-28 00:19:56 -07001009 stdout, stderr = p.communicate()
1010 data = stdout.decode().replace('\r', '')
Antoine Pitroub8b6a682012-06-29 19:40:35 +02001011 self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
Ned Deily9a7c5242011-05-28 00:19:56 -07001012 self.assertEqual(data, expected_output)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001013
R David Murray19aeb432013-03-30 17:19:38 -04001014class TimerTests(BaseTestCase):
1015
1016 def setUp(self):
1017 BaseTestCase.setUp(self)
1018 self.callback_args = []
1019 self.callback_event = threading.Event()
1020
1021 def test_init_immutable_default_args(self):
1022 # Issue 17435: constructor defaults were mutable objects, they could be
1023 # mutated via the object attributes and affect other Timer objects.
1024 timer1 = threading.Timer(0.01, self._callback_spy)
1025 timer1.start()
1026 self.callback_event.wait()
1027 timer1.args.append("blah")
1028 timer1.kwargs["foo"] = "bar"
1029 self.callback_event.clear()
1030 timer2 = threading.Timer(0.01, self._callback_spy)
1031 timer2.start()
1032 self.callback_event.wait()
1033 self.assertEqual(len(self.callback_args), 2)
1034 self.assertEqual(self.callback_args, [((), {}), ((), {})])
1035
1036 def _callback_spy(self, *args, **kwargs):
1037 self.callback_args.append((args[:], kwargs.copy()))
1038 self.callback_event.set()
1039
Antoine Pitrou557934f2009-11-06 22:41:14 +00001040class LockTests(lock_tests.LockTests):
1041 locktype = staticmethod(threading.Lock)
1042
Antoine Pitrou434736a2009-11-10 18:46:01 +00001043class PyRLockTests(lock_tests.RLockTests):
1044 locktype = staticmethod(threading._PyRLock)
1045
Charles-François Natali6b671b22012-01-28 11:36:04 +01001046@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
Antoine Pitrou434736a2009-11-10 18:46:01 +00001047class CRLockTests(lock_tests.RLockTests):
1048 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001049
1050class EventTests(lock_tests.EventTests):
1051 eventtype = staticmethod(threading.Event)
1052
1053class ConditionAsRLockTests(lock_tests.RLockTests):
1054 # An Condition uses an RLock by default and exports its API.
1055 locktype = staticmethod(threading.Condition)
1056
1057class ConditionTests(lock_tests.ConditionTests):
1058 condtype = staticmethod(threading.Condition)
1059
1060class SemaphoreTests(lock_tests.SemaphoreTests):
1061 semtype = staticmethod(threading.Semaphore)
1062
1063class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
1064 semtype = staticmethod(threading.BoundedSemaphore)
1065
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +00001066class BarrierTests(lock_tests.BarrierTests):
1067 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +00001068
Tim Peters84d54892005-01-08 06:03:17 +00001069if __name__ == "__main__":
R David Murray19aeb432013-03-30 17:19:38 -04001070 unittest.main()