blob: 71135cc2e040fa029d36638b3a4b99eff85f8fa6 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003import test.support
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00004from test.support import verbose
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Georg Brandl0c77a822008-06-10 16:37:50 +00006import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007import sys
Skip Montanaro4533f602001-08-20 20:28:48 +00008import threading
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000012import weakref
Skip Montanaro4533f602001-08-20 20:28:48 +000013
Antoine Pitrou959f3e52009-11-09 16:52:46 +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):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000036 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000037 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000038 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000039 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000040
Christian Heimes4fbc72b2008-03-22 00:47:35 +000041 with self.sema:
42 with self.mutex:
43 self.nrunning.inc()
44 if verbose:
45 print(self.nrunning.get(), 'tasks are running')
Georg Brandlab91fde2009-08-13 08:51:18 +000046 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000047
Christian Heimes4fbc72b2008-03-22 00:47:35 +000048 time.sleep(delay)
49 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000050 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000051
Christian Heimes4fbc72b2008-03-22 00:47:35 +000052 with self.mutex:
53 self.nrunning.dec()
Georg Brandlab91fde2009-08-13 08:51:18 +000054 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000055 if verbose:
56 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000057 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000058
Skip Montanaro4533f602001-08-20 20:28:48 +000059
Tim Peters84d54892005-01-08 06:03:17 +000060class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000061
Tim Peters84d54892005-01-08 06:03:17 +000062 # Create a bunch of threads, let each do some work, wait until all are
63 # done.
64 def test_various_ops(self):
65 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
66 # times about 1 second per clump).
67 NUMTASKS = 10
68
69 # no more than 3 of the 10 can run at once
70 sema = threading.BoundedSemaphore(value=3)
71 mutex = threading.RLock()
72 numrunning = Counter()
73
74 threads = []
75
76 for i in range(NUMTASKS):
77 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
78 threads.append(t)
Georg Brandlab91fde2009-08-13 08:51:18 +000079 self.assertEqual(t.ident, None)
80 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000081 t.start()
82
83 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000084 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000085 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000086 t.join(NUMTASKS)
Georg Brandlab91fde2009-08-13 08:51:18 +000087 self.assertTrue(not t.is_alive())
88 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +000089 self.assertFalse(t.ident is None)
Georg Brandlab91fde2009-08-13 08:51:18 +000090 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000091 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000092 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000093 self.assertEqual(numrunning.get(), 0)
94
Benjamin Petersond23f8222009-04-05 19:13:16 +000095 def test_ident_of_no_threading_threads(self):
96 # The ident still must work for the main thread and dummy threads.
97 self.assertFalse(threading.currentThread().ident is None)
98 def f():
99 ident.append(threading.currentThread().ident)
100 done.set()
101 done = threading.Event()
102 ident = []
103 _thread.start_new_thread(f, ())
104 done.wait()
105 self.assertFalse(ident[0] is None)
Antoine Pitroudebfafd2009-11-08 00:36:36 +0000106 # Kill the "immortal" _DummyThread
107 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000108
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109 # run with a small(ish) thread stack size (256kB)
110 def test_various_ops_small_stack(self):
111 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000113 try:
114 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000115 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000116 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000117 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000118 return
119 self.test_various_ops()
120 threading.stack_size(0)
121
122 # run with a large thread stack size (1MB)
123 def test_various_ops_large_stack(self):
124 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000125 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 try:
127 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000128 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000129 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000130 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000131 return
132 self.test_various_ops()
133 threading.stack_size(0)
134
Tim Peters711906e2005-01-08 07:30:42 +0000135 def test_foreign_thread(self):
136 # Check that a "foreign" thread can use the threading module.
137 def f(mutex):
Antoine Pitrou959f3e52009-11-09 16:52:46 +0000138 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000139 # thread to get made in the threading._active map.
Antoine Pitrou959f3e52009-11-09 16:52:46 +0000140 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000141 mutex.release()
142
143 mutex = threading.Lock()
144 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000145 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000146 # Wait for the thread to finish.
147 mutex.acquire()
Georg Brandlab91fde2009-08-13 08:51:18 +0000148 self.assertTrue(tid in threading._active)
149 self.assertTrue(isinstance(threading._active[tid],
Tim Peters711906e2005-01-08 07:30:42 +0000150 threading._DummyThread))
151 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000152
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000153 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
154 # exposed at the Python level. This test relies on ctypes to get at it.
155 def test_PyThreadState_SetAsyncExc(self):
156 try:
157 import ctypes
158 except ImportError:
159 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000160 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161 return # can't do anything
162
163 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
164
165 class AsyncExc(Exception):
166 pass
167
168 exception = ctypes.py_object(AsyncExc)
169
170 # `worker_started` is set by the thread when it's inside a try/except
171 # block waiting to catch the asynchronously set AsyncExc exception.
172 # `worker_saw_exception` is set by the thread upon catching that
173 # exception.
174 worker_started = threading.Event()
175 worker_saw_exception = threading.Event()
176
177 class Worker(threading.Thread):
178 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000179 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180 self.finished = False
181
182 try:
183 while True:
184 worker_started.set()
185 time.sleep(0.1)
186 except AsyncExc:
187 self.finished = True
188 worker_saw_exception.set()
189
190 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000191 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000192 t.start()
193 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000194 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000195
196 # Try a thread id that doesn't make sense.
197 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000198 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000199 result = set_async_exc(ctypes.c_long(-1), exception)
200 self.assertEqual(result, 0) # no thread states modified
201
202 # Now raise an exception in the worker thread.
203 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000204 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000205 ret = worker_started.wait()
206 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print(" verifying worker hasn't exited")
Georg Brandlab91fde2009-08-13 08:51:18 +0000209 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000210 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000211 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000212 result = set_async_exc(ctypes.c_long(t.id), exception)
213 self.assertEqual(result, 1) # one thread state modified
214 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000215 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000216 worker_saw_exception.wait(timeout=10)
Georg Brandlab91fde2009-08-13 08:51:18 +0000217 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220 if t.finished:
221 t.join()
222 # else the thread is still running, and we have no way to kill it
223
Gregory P. Smith31d12ca2010-02-28 19:21:42 +0000224 def test_limbo_cleanup(self):
225 # Issue 7481: Failure to start thread should cleanup the limbo map.
226 def fail_new_thread(*args):
227 raise threading.ThreadError()
228 _start_new_thread = threading._start_new_thread
229 threading._start_new_thread = fail_new_thread
230 try:
231 t = threading.Thread(target=lambda: None)
Gregory P. Smithff318642010-03-01 03:19:29 +0000232 self.assertRaises(threading.ThreadError, t.start)
233 self.assertFalse(
234 t in threading._limbo,
235 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith31d12ca2010-02-28 19:21:42 +0000236 finally:
237 threading._start_new_thread = _start_new_thread
238
Christian Heimes7d2ff882007-11-30 14:35:04 +0000239 def test_finalize_runnning_thread(self):
240 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
241 # very late on python exit: on deallocation of a running thread for
242 # example.
243 try:
244 import ctypes
245 except ImportError:
246 if verbose:
247 print("test_finalize_with_runnning_thread can't import ctypes")
248 return # can't do anything
249
250 import subprocess
251 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000252 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000253
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000254 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000255 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000256 ready.acquire()
257
Christian Heimes7d2ff882007-11-30 14:35:04 +0000258 # Module globals are cleared before __del__ is run
259 # So we save the functions in class dict
260 class C:
261 ensure = ctypes.pythonapi.PyGILState_Ensure
262 release = ctypes.pythonapi.PyGILState_Release
263 def __del__(self):
264 state = self.ensure()
265 self.release(state)
266
267 def waitingThread():
268 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000269 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000270 time.sleep(100)
271
Georg Brandl2067bfd2008-05-25 13:05:15 +0000272 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000273 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000274 sys.exit(42)
275 """])
276 self.assertEqual(rc, 42)
277
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000278 def test_finalize_with_trace(self):
279 # Issue1733757
280 # Avoid a deadlock when sys.settrace steps into threading._shutdown
281 import subprocess
282 rc = subprocess.call([sys.executable, "-c", """if 1:
283 import sys, threading
284
285 # A deadlock-killer, to prevent the
286 # testsuite to hang forever
287 def killer():
288 import os, time
289 time.sleep(2)
290 print('program blocked; aborting')
291 os._exit(2)
292 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000293 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000294 t.start()
295
296 # This is the trace function
297 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000298 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000299 return func
300
301 sys.settrace(func)
302 """])
Georg Brandlab91fde2009-08-13 08:51:18 +0000303 self.assertFalse(rc == 2, "interpreted was blocked")
304 self.assertTrue(rc == 0, "Unexpected error")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000305
Antoine Pitroucefb3162009-10-20 22:08:36 +0000306 def test_join_nondaemon_on_shutdown(self):
307 # Issue 1722344
308 # Raising SystemExit skipped threading._shutdown
309 import subprocess
310 p = subprocess.Popen([sys.executable, "-c", """if 1:
311 import threading
312 from time import sleep
313
314 def child():
315 sleep(1)
316 # As a non-daemon thread we SHOULD wake up and nothing
317 # should be torn down yet
318 print("Woke up, sleep function is:", sleep)
319
320 threading.Thread(target=child).start()
321 raise SystemExit
322 """],
323 stdout=subprocess.PIPE,
324 stderr=subprocess.PIPE)
325 stdout, stderr = p.communicate()
Antoine Pitrouf6779fb2009-10-23 22:06:37 +0000326 self.assertEqual(stdout.strip(),
327 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitroucefb3162009-10-20 22:08:36 +0000328 stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
329 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000330
Christian Heimes1af737c2008-01-23 08:24:23 +0000331 def test_enumerate_after_join(self):
332 # Try hard to trigger #1703448: a thread is still returned in
333 # threading.enumerate() after it has been join()ed.
334 enum = threading.enumerate
335 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000336 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000337 for i in range(1, 100):
338 # Try a couple times at each thread-switching interval
339 # to get more interleavings.
340 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000341 t = threading.Thread(target=lambda: None)
342 t.start()
343 t.join()
344 l = enum()
345 self.assertFalse(t in l,
346 "#1703448 triggered after %d trials: %s" % (i, l))
347 finally:
348 sys.setcheckinterval(old_interval)
349
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000350 def test_no_refcycle_through_target(self):
351 class RunSelfFunction(object):
352 def __init__(self, should_raise):
353 # The links in this refcycle from Thread back to self
354 # should be cleaned up when the thread completes.
355 self.should_raise = should_raise
356 self.thread = threading.Thread(target=self._run,
357 args=(self,),
358 kwargs={'yet_another':self})
359 self.thread.start()
360
361 def _run(self, other_ref, yet_another):
362 if self.should_raise:
363 raise SystemExit
364
365 cyclic_object = RunSelfFunction(should_raise=False)
366 weak_cyclic_object = weakref.ref(cyclic_object)
367 cyclic_object.thread.join()
368 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000369 self.assertEquals(None, weak_cyclic_object(),
370 msg=('%d references still around' %
371 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000372
373 raising_cyclic_object = RunSelfFunction(should_raise=True)
374 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
375 raising_cyclic_object.thread.join()
376 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000377 self.assertEquals(None, weak_raising_cyclic_object(),
378 msg=('%d references still around' %
379 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000380
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000381 def test_old_threading_api(self):
382 # Just a quick sanity check to make sure the old method names are
383 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000384 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000385 t.isDaemon()
386 t.setDaemon(True)
387 t.getName()
388 t.setName("name")
389 t.isAlive()
390 e = threading.Event()
391 e.isSet()
392 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000393
Christian Heimes1af737c2008-01-23 08:24:23 +0000394
Jesse Nollera8513972008-07-17 16:49:17 +0000395class ThreadJoinOnShutdown(unittest.TestCase):
396
397 def _run_and_join(self, script):
398 script = """if 1:
399 import sys, os, time, threading
400
401 # a thread, which waits for the main program to terminate
402 def joiningfunc(mainthread):
403 mainthread.join()
404 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000405 # stdout is fully buffered because not a tty, we have to flush
406 # before exit.
407 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000408 \n""" + script
409
410 import subprocess
411 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
412 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000413 data = p.stdout.read().decode().replace('\r', '')
414 self.assertEqual(data, "end of main\nend of thread\n")
Georg Brandlab91fde2009-08-13 08:51:18 +0000415 self.assertFalse(rc == 2, "interpreter was blocked")
416 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000417
418 def test_1_join_on_shutdown(self):
419 # The usual case: on exit, wait for a non-daemon thread
420 script = """if 1:
421 import os
422 t = threading.Thread(target=joiningfunc,
423 args=(threading.current_thread(),))
424 t.start()
425 time.sleep(0.1)
426 print('end of main')
427 """
428 self._run_and_join(script)
429
430
431 def test_2_join_in_forked_process(self):
432 # Like the test above, but from a forked interpreter
433 import os
434 if not hasattr(os, 'fork'):
435 return
436 script = """if 1:
437 childpid = os.fork()
438 if childpid != 0:
439 os.waitpid(childpid, 0)
440 sys.exit(0)
441
442 t = threading.Thread(target=joiningfunc,
443 args=(threading.current_thread(),))
444 t.start()
445 print('end of main')
446 """
447 self._run_and_join(script)
448
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000449 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000450 # Like the test above, but fork() was called from a worker thread
451 # In the forked process, the main Thread object must be marked as stopped.
452 import os
453 if not hasattr(os, 'fork'):
454 return
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000455 # Skip platforms with known problems forking from a worker thread.
456 # See http://bugs.python.org/issue3863.
457 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
R. David Murray9948da02009-10-26 03:27:32 +0000458 print('Skipping test_3_join_in_forked_from_thread'
459 ' due to known OS bugs on', sys.platform, file=sys.stderr)
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000460 return
Jesse Nollera8513972008-07-17 16:49:17 +0000461 script = """if 1:
462 main_thread = threading.current_thread()
463 def worker():
464 childpid = os.fork()
465 if childpid != 0:
466 os.waitpid(childpid, 0)
467 sys.exit(0)
468
469 t = threading.Thread(target=joiningfunc,
470 args=(main_thread,))
471 print('end of main')
472 t.start()
473 t.join() # Should not block: main_thread is already stopped
474
475 w = threading.Thread(target=worker)
476 w.start()
477 """
478 self._run_and_join(script)
479
480
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000481class ThreadingExceptionTests(unittest.TestCase):
482 # A RuntimeError should be raised if Thread.start() is called
483 # multiple times.
484 def test_start_thread_again(self):
485 thread = threading.Thread()
486 thread.start()
487 self.assertRaises(RuntimeError, thread.start)
488
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000489 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000490 current_thread = threading.current_thread()
491 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000492
493 def test_joining_inactive_thread(self):
494 thread = threading.Thread()
495 self.assertRaises(RuntimeError, thread.join)
496
497 def test_daemonize_active_thread(self):
498 thread = threading.Thread()
499 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000500 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000501
502
Antoine Pitrou959f3e52009-11-09 16:52:46 +0000503class LockTests(lock_tests.LockTests):
504 locktype = staticmethod(threading.Lock)
505
506class RLockTests(lock_tests.RLockTests):
507 locktype = staticmethod(threading.RLock)
508
509class EventTests(lock_tests.EventTests):
510 eventtype = staticmethod(threading.Event)
511
512class ConditionAsRLockTests(lock_tests.RLockTests):
513 # An Condition uses an RLock by default and exports its API.
514 locktype = staticmethod(threading.Condition)
515
516class ConditionTests(lock_tests.ConditionTests):
517 condtype = staticmethod(threading.Condition)
518
519class SemaphoreTests(lock_tests.SemaphoreTests):
520 semtype = staticmethod(threading.Semaphore)
521
522class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
523 semtype = staticmethod(threading.BoundedSemaphore)
524
525
Tim Peters84d54892005-01-08 06:03:17 +0000526def test_main():
Antoine Pitrou959f3e52009-11-09 16:52:46 +0000527 test.support.run_unittest(LockTests, RLockTests, EventTests,
528 ConditionAsRLockTests, ConditionTests,
529 SemaphoreTests, BoundedSemaphoreTests,
530 ThreadTests,
531 ThreadJoinOnShutdown,
532 ThreadingExceptionTests,
533 )
Tim Peters84d54892005-01-08 06:03:17 +0000534
535if __name__ == "__main__":
536 test_main()