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