blob: 5af74794c29b92cbaaeeed214fb4ed740b1806b7 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Tim Peters84d54892005-01-08 06:03:17 +00003import test.test_support
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test.test_support import verbose
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Gregory P. Smith8856dda2008-06-01 23:48:47 +00006import re
Collin Winter50b79ce2007-06-06 00:17:35 +00007import sys
Victor Stinner6a102812010-04-27 23:55:59 +00008thread = test.test_support.import_module('thread')
9threading = test.test_support.import_module('threading')
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +000012import weakref
Skip Montanaro4533f602001-08-20 20:28:48 +000013
Antoine Pitrouc98efe02009-11-06 22:34:35 +000014from test import lock_tests
15
Tim Peters84d54892005-01-08 06:03:17 +000016# A trivial mutable counter.
17class Counter(object):
18 def __init__(self):
19 self.value = 0
20 def inc(self):
21 self.value += 1
22 def dec(self):
23 self.value -= 1
24 def get(self):
25 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000026
27class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000028 def __init__(self, name, testcase, sema, mutex, nrunning):
29 threading.Thread.__init__(self, name=name)
30 self.testcase = testcase
31 self.sema = sema
32 self.mutex = mutex
33 self.nrunning = nrunning
34
Skip Montanaro4533f602001-08-20 20:28:48 +000035 def run(self):
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000036 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000037 if verbose:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000038 print 'task %s will run for %.1f usec' % (
Benjamin Petersoncbae8692008-08-18 17:45:09 +000039 self.name, delay * 1e6)
Tim Peters84d54892005-01-08 06:03:17 +000040
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000041 with self.sema:
42 with self.mutex:
43 self.nrunning.inc()
44 if verbose:
45 print self.nrunning.get(), 'tasks are running'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000046 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000047
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000048 time.sleep(delay)
49 if verbose:
Benjamin Petersoncbae8692008-08-18 17:45:09 +000050 print 'task', self.name, 'done'
Tim Peters84d54892005-01-08 06:03:17 +000051
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000052 with self.mutex:
53 self.nrunning.dec()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000054 self.testcase.assertTrue(self.nrunning.get() >= 0)
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000055 if verbose:
56 print '%s is finished. %d tasks are running' % (
Benjamin Petersoncbae8692008-08-18 17:45:09 +000057 self.name, self.nrunning.get())
Skip Montanaro4533f602001-08-20 20:28:48 +000058
Antoine Pitroubb0bb302009-10-27 20:02:23 +000059class BaseTestCase(unittest.TestCase):
60 def setUp(self):
61 self._threads = test.test_support.threading_setup()
62
63 def tearDown(self):
64 test.test_support.threading_cleanup(*self._threads)
65 test.test_support.reap_children()
66
67
68class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000069
Tim Peters84d54892005-01-08 06:03:17 +000070 # Create a bunch of threads, let each do some work, wait until all are
71 # done.
72 def test_various_ops(self):
73 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
74 # times about 1 second per clump).
75 NUMTASKS = 10
76
77 # no more than 3 of the 10 can run at once
78 sema = threading.BoundedSemaphore(value=3)
79 mutex = threading.RLock()
80 numrunning = Counter()
81
82 threads = []
83
84 for i in range(NUMTASKS):
85 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
86 threads.append(t)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000087 self.assertEqual(t.ident, None)
88 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000089 t.start()
90
91 if verbose:
92 print 'waiting for all tasks to complete'
93 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000094 t.join(NUMTASKS)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000095 self.assertTrue(not t.is_alive())
96 self.assertNotEqual(t.ident, 0)
Benjamin Petersond906ea62009-03-31 21:34:42 +000097 self.assertFalse(t.ident is None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000098 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000099 if verbose:
100 print 'all tasks done'
101 self.assertEqual(numrunning.get(), 0)
102
Benjamin Petersond906ea62009-03-31 21:34:42 +0000103 def test_ident_of_no_threading_threads(self):
104 # The ident still must work for the main thread and dummy threads.
105 self.assertFalse(threading.currentThread().ident is None)
106 def f():
107 ident.append(threading.currentThread().ident)
108 done.set()
109 done = threading.Event()
110 ident = []
111 thread.start_new_thread(f, ())
112 done.wait()
113 self.assertFalse(ident[0] is None)
Antoine Pitrou00253302009-11-08 00:24:12 +0000114 # Kill the "immortal" _DummyThread
115 del threading._active[ident[0]]
Benjamin Petersond906ea62009-03-31 21:34:42 +0000116
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +0000117 # run with a small(ish) thread stack size (256kB)
Andrew MacIntyre92913322006-06-13 15:04:24 +0000118 def test_various_ops_small_stack(self):
119 if verbose:
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +0000120 print 'with 256kB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000121 try:
122 threading.stack_size(262144)
123 except thread.error:
124 if verbose:
125 print 'platform does not support changing thread stack size'
126 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000127 self.test_various_ops()
128 threading.stack_size(0)
129
130 # run with a large thread stack size (1MB)
131 def test_various_ops_large_stack(self):
132 if verbose:
133 print 'with 1MB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000134 try:
135 threading.stack_size(0x100000)
136 except thread.error:
137 if verbose:
138 print 'platform does not support changing thread stack size'
139 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000140 self.test_various_ops()
141 threading.stack_size(0)
142
Tim Peters711906e2005-01-08 07:30:42 +0000143 def test_foreign_thread(self):
144 # Check that a "foreign" thread can use the threading module.
145 def f(mutex):
Antoine Pitroud7158d42009-11-09 16:00:11 +0000146 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000147 # thread to get made in the threading._active map.
Antoine Pitroud7158d42009-11-09 16:00:11 +0000148 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000149 mutex.release()
150
151 mutex = threading.Lock()
152 mutex.acquire()
153 tid = thread.start_new_thread(f, (mutex,))
154 # Wait for the thread to finish.
155 mutex.acquire()
Ezio Melottiaa980582010-01-23 23:04:36 +0000156 self.assertIn(tid, threading._active)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000157 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000158 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000159
Tim Peters4643c2f2006-08-10 22:45:34 +0000160 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
161 # exposed at the Python level. This test relies on ctypes to get at it.
162 def test_PyThreadState_SetAsyncExc(self):
163 try:
164 import ctypes
165 except ImportError:
166 if verbose:
167 print "test_PyThreadState_SetAsyncExc can't import ctypes"
168 return # can't do anything
169
170 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
171
172 class AsyncExc(Exception):
173 pass
174
175 exception = ctypes.py_object(AsyncExc)
176
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000177 # First check it works when setting the exception from the same thread.
178 tid = thread.get_ident()
179
180 try:
181 result = set_async_exc(ctypes.c_long(tid), exception)
182 # The exception is async, so we might have to keep the VM busy until
183 # it notices.
184 while True:
185 pass
186 except AsyncExc:
187 pass
188 else:
Antoine Pitrou603acf92009-10-18 18:37:11 +0000189 # This code is unreachable but it reflects the intent. If we wanted
190 # to be smarter the above loop wouldn't be infinite.
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000191 self.fail("AsyncExc not raised")
192 try:
193 self.assertEqual(result, 1) # one thread state modified
194 except UnboundLocalError:
Antoine Pitrou603acf92009-10-18 18:37:11 +0000195 # The exception was raised too quickly for us to get the result.
Antoine Pitrou8a172b12009-10-18 18:22:04 +0000196 pass
197
Tim Peters4643c2f2006-08-10 22:45:34 +0000198 # `worker_started` is set by the thread when it's inside a try/except
199 # block waiting to catch the asynchronously set AsyncExc exception.
200 # `worker_saw_exception` is set by the thread upon catching that
201 # exception.
202 worker_started = threading.Event()
203 worker_saw_exception = threading.Event()
204
205 class Worker(threading.Thread):
206 def run(self):
207 self.id = thread.get_ident()
208 self.finished = False
209
210 try:
211 while True:
212 worker_started.set()
213 time.sleep(0.1)
214 except AsyncExc:
215 self.finished = True
216 worker_saw_exception.set()
217
218 t = Worker()
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000219 t.daemon = True # so if this fails, we don't hang Python at shutdown
Tim Peters08574772006-08-11 00:49:01 +0000220 t.start()
Tim Peters4643c2f2006-08-10 22:45:34 +0000221 if verbose:
222 print " started worker thread"
Tim Peters4643c2f2006-08-10 22:45:34 +0000223
224 # Try a thread id that doesn't make sense.
225 if verbose:
226 print " trying nonsensical thread id"
Tim Peters08574772006-08-11 00:49:01 +0000227 result = set_async_exc(ctypes.c_long(-1), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000228 self.assertEqual(result, 0) # no thread states modified
229
230 # Now raise an exception in the worker thread.
231 if verbose:
232 print " waiting for worker thread to get started"
Georg Brandlef660e82009-03-31 20:41:08 +0000233 ret = worker_started.wait()
234 self.assertTrue(ret)
Tim Peters4643c2f2006-08-10 22:45:34 +0000235 if verbose:
236 print " verifying worker hasn't exited"
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000237 self.assertTrue(not t.finished)
Tim Peters4643c2f2006-08-10 22:45:34 +0000238 if verbose:
239 print " attempting to raise asynch exception in worker"
Tim Peters08574772006-08-11 00:49:01 +0000240 result = set_async_exc(ctypes.c_long(t.id), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000241 self.assertEqual(result, 1) # one thread state modified
242 if verbose:
243 print " waiting for worker to say it caught the exception"
244 worker_saw_exception.wait(timeout=10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000245 self.assertTrue(t.finished)
Tim Peters4643c2f2006-08-10 22:45:34 +0000246 if verbose:
247 print " all OK -- joining worker"
248 if t.finished:
249 t.join()
250 # else the thread is still running, and we have no way to kill it
251
Gregory P. Smith613c7a52010-02-28 18:36:09 +0000252 def test_limbo_cleanup(self):
253 # Issue 7481: Failure to start thread should cleanup the limbo map.
254 def fail_new_thread(*args):
255 raise thread.error()
256 _start_new_thread = threading._start_new_thread
257 threading._start_new_thread = fail_new_thread
258 try:
259 t = threading.Thread(target=lambda: None)
Gregory P. Smith3c1586a2010-03-01 03:09:19 +0000260 self.assertRaises(thread.error, t.start)
261 self.assertFalse(
262 t in threading._limbo,
263 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith613c7a52010-02-28 18:36:09 +0000264 finally:
265 threading._start_new_thread = _start_new_thread
266
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000267 def test_finalize_runnning_thread(self):
268 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
269 # very late on python exit: on deallocation of a running thread for
270 # example.
271 try:
272 import ctypes
273 except ImportError:
274 if verbose:
275 print("test_finalize_with_runnning_thread can't import ctypes")
276 return # can't do anything
277
278 import subprocess
279 rc = subprocess.call([sys.executable, "-c", """if 1:
280 import ctypes, sys, time, thread
281
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000282 # This lock is used as a simple event variable.
283 ready = thread.allocate_lock()
284 ready.acquire()
285
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000286 # Module globals are cleared before __del__ is run
287 # So we save the functions in class dict
288 class C:
289 ensure = ctypes.pythonapi.PyGILState_Ensure
290 release = ctypes.pythonapi.PyGILState_Release
291 def __del__(self):
292 state = self.ensure()
293 self.release(state)
294
295 def waitingThread():
296 x = C()
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000297 ready.release()
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000298 time.sleep(100)
299
300 thread.start_new_thread(waitingThread, ())
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000301 ready.acquire() # Be sure the other thread is waiting.
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000302 sys.exit(42)
303 """])
304 self.assertEqual(rc, 42)
305
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000306 def test_finalize_with_trace(self):
307 # Issue1733757
308 # Avoid a deadlock when sys.settrace steps into threading._shutdown
309 import subprocess
Antoine Pitroua6166da2010-09-20 11:20:44 +0000310 p = subprocess.Popen([sys.executable, "-c", """if 1:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000311 import sys, threading
312
313 # A deadlock-killer, to prevent the
314 # testsuite to hang forever
315 def killer():
316 import os, time
317 time.sleep(2)
318 print 'program blocked; aborting'
319 os._exit(2)
320 t = threading.Thread(target=killer)
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000321 t.daemon = True
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000322 t.start()
323
324 # This is the trace function
325 def func(frame, event, arg):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000326 threading.current_thread()
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000327 return func
328
329 sys.settrace(func)
Antoine Pitroua6166da2010-09-20 11:20:44 +0000330 """],
331 stdout=subprocess.PIPE,
332 stderr=subprocess.PIPE)
333 stdout, stderr = p.communicate()
334 rc = p.returncode
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000335 self.assertFalse(rc == 2, "interpreted was blocked")
Antoine Pitroua6166da2010-09-20 11:20:44 +0000336 self.assertTrue(rc == 0,
337 "Unexpected error: " + repr(stderr))
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000338
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000339 def test_join_nondaemon_on_shutdown(self):
340 # Issue 1722344
341 # Raising SystemExit skipped threading._shutdown
342 import subprocess
343 p = subprocess.Popen([sys.executable, "-c", """if 1:
344 import threading
345 from time import sleep
346
347 def child():
348 sleep(1)
349 # As a non-daemon thread we SHOULD wake up and nothing
350 # should be torn down yet
351 print "Woke up, sleep function is:", sleep
352
353 threading.Thread(target=child).start()
354 raise SystemExit
355 """],
356 stdout=subprocess.PIPE,
357 stderr=subprocess.PIPE)
358 stdout, stderr = p.communicate()
Antoine Pitroub119ca92009-10-23 12:01:13 +0000359 self.assertEqual(stdout.strip(),
360 "Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou9bd246b2009-10-20 21:59:25 +0000361 stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip()
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000362 self.assertEqual(stderr, "")
363
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000364 def test_enumerate_after_join(self):
365 # Try hard to trigger #1703448: a thread is still returned in
366 # threading.enumerate() after it has been join()ed.
367 enum = threading.enumerate
368 old_interval = sys.getcheckinterval()
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000369 try:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000370 for i in xrange(1, 100):
371 # Try a couple times at each thread-switching interval
372 # to get more interleavings.
373 sys.setcheckinterval(i // 5)
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000374 t = threading.Thread(target=lambda: None)
375 t.start()
376 t.join()
377 l = enum()
Ezio Melottiaa980582010-01-23 23:04:36 +0000378 self.assertNotIn(t, l,
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000379 "#1703448 triggered after %d trials: %s" % (i, l))
380 finally:
381 sys.setcheckinterval(old_interval)
382
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000383 def test_no_refcycle_through_target(self):
384 class RunSelfFunction(object):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000385 def __init__(self, should_raise):
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000386 # The links in this refcycle from Thread back to self
387 # should be cleaned up when the thread completes.
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000388 self.should_raise = should_raise
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000389 self.thread = threading.Thread(target=self._run,
390 args=(self,),
391 kwargs={'yet_another':self})
392 self.thread.start()
393
394 def _run(self, other_ref, yet_another):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000395 if self.should_raise:
396 raise SystemExit
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000397
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000398 cyclic_object = RunSelfFunction(should_raise=False)
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000399 weak_cyclic_object = weakref.ref(cyclic_object)
400 cyclic_object.thread.join()
401 del cyclic_object
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000402 self.assertEquals(None, weak_cyclic_object(),
403 msg=('%d references still around' %
404 sys.getrefcount(weak_cyclic_object())))
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000405
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000406 raising_cyclic_object = RunSelfFunction(should_raise=True)
407 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
408 raising_cyclic_object.thread.join()
409 del raising_cyclic_object
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000410 self.assertEquals(None, weak_raising_cyclic_object(),
411 msg=('%d references still around' %
412 sys.getrefcount(weak_raising_cyclic_object())))
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000413
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000414
Antoine Pitroubb0bb302009-10-27 20:02:23 +0000415class ThreadJoinOnShutdown(BaseTestCase):
Jesse Noller5e62ca42008-07-16 20:03:47 +0000416
417 def _run_and_join(self, script):
418 script = """if 1:
419 import sys, os, time, threading
420
421 # a thread, which waits for the main program to terminate
422 def joiningfunc(mainthread):
423 mainthread.join()
424 print 'end of thread'
425 \n""" + script
426
427 import subprocess
428 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
429 rc = p.wait()
Benjamin Petersonf5668f12008-07-17 12:57:22 +0000430 data = p.stdout.read().replace('\r', '')
431 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000432 self.assertFalse(rc == 2, "interpreter was blocked")
433 self.assertTrue(rc == 0, "Unexpected error")
Jesse Noller5e62ca42008-07-16 20:03:47 +0000434
435 def test_1_join_on_shutdown(self):
436 # The usual case: on exit, wait for a non-daemon thread
437 script = """if 1:
438 import os
439 t = threading.Thread(target=joiningfunc,
440 args=(threading.current_thread(),))
441 t.start()
442 time.sleep(0.1)
443 print 'end of main'
444 """
445 self._run_and_join(script)
446
447
448 def test_2_join_in_forked_process(self):
449 # Like the test above, but from a forked interpreter
450 import os
451 if not hasattr(os, 'fork'):
452 return
453 script = """if 1:
454 childpid = os.fork()
455 if childpid != 0:
456 os.waitpid(childpid, 0)
457 sys.exit(0)
458
459 t = threading.Thread(target=joiningfunc,
460 args=(threading.current_thread(),))
461 t.start()
462 print 'end of main'
463 """
464 self._run_and_join(script)
465
466 def test_3_join_in_forked_from_thread(self):
467 # Like the test above, but fork() was called from a worker thread
468 # In the forked process, the main Thread object must be marked as stopped.
469 import os
470 if not hasattr(os, 'fork'):
471 return
Gregory P. Smith08067492008-09-30 20:41:13 +0000472 # Skip platforms with known problems forking from a worker thread.
473 # See http://bugs.python.org/issue3863.
Gregory P. Smith886a1cd2010-10-17 04:28:14 +0000474 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
475 'os2emx'):
Gregory P. Smith08067492008-09-30 20:41:13 +0000476 print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread'
477 ' due to known OS bugs on'), sys.platform
478 return
Jesse Noller5e62ca42008-07-16 20:03:47 +0000479 script = """if 1:
480 main_thread = threading.current_thread()
481 def worker():
482 childpid = os.fork()
483 if childpid != 0:
484 os.waitpid(childpid, 0)
485 sys.exit(0)
486
487 t = threading.Thread(target=joiningfunc,
488 args=(main_thread,))
489 print 'end of main'
490 t.start()
491 t.join() # Should not block: main_thread is already stopped
492
493 w = threading.Thread(target=worker)
494 w.start()
495 """
496 self._run_and_join(script)
497
498
Antoine Pitroubb0bb302009-10-27 20:02:23 +0000499class ThreadingExceptionTests(BaseTestCase):
Collin Winter50b79ce2007-06-06 00:17:35 +0000500 # A RuntimeError should be raised if Thread.start() is called
501 # multiple times.
502 def test_start_thread_again(self):
503 thread = threading.Thread()
504 thread.start()
505 self.assertRaises(RuntimeError, thread.start)
506
Collin Winter50b79ce2007-06-06 00:17:35 +0000507 def test_joining_current_thread(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000508 current_thread = threading.current_thread()
509 self.assertRaises(RuntimeError, current_thread.join);
Collin Winter50b79ce2007-06-06 00:17:35 +0000510
511 def test_joining_inactive_thread(self):
512 thread = threading.Thread()
513 self.assertRaises(RuntimeError, thread.join)
514
515 def test_daemonize_active_thread(self):
516 thread = threading.Thread()
517 thread.start()
Benjamin Petersoncbae8692008-08-18 17:45:09 +0000518 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Collin Winter50b79ce2007-06-06 00:17:35 +0000519
520
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000521class LockTests(lock_tests.LockTests):
522 locktype = staticmethod(threading.Lock)
523
524class RLockTests(lock_tests.RLockTests):
525 locktype = staticmethod(threading.RLock)
526
527class EventTests(lock_tests.EventTests):
528 eventtype = staticmethod(threading.Event)
529
530class ConditionAsRLockTests(lock_tests.RLockTests):
531 # An Condition uses an RLock by default and exports its API.
532 locktype = staticmethod(threading.Condition)
533
534class ConditionTests(lock_tests.ConditionTests):
535 condtype = staticmethod(threading.Condition)
536
537class SemaphoreTests(lock_tests.SemaphoreTests):
538 semtype = staticmethod(threading.Semaphore)
539
540class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
541 semtype = staticmethod(threading.BoundedSemaphore)
542
543
Tim Peters84d54892005-01-08 06:03:17 +0000544def test_main():
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000545 test.test_support.run_unittest(LockTests, RLockTests, EventTests,
546 ConditionAsRLockTests, ConditionTests,
547 SemaphoreTests, BoundedSemaphoreTests,
548 ThreadTests,
Jesse Noller5e62ca42008-07-16 20:03:47 +0000549 ThreadJoinOnShutdown,
550 ThreadingExceptionTests,
551 )
Tim Peters84d54892005-01-08 06:03:17 +0000552
553if __name__ == "__main__":
554 test_main()