blob: 8f7c676ee411749e339fb51417e02731cff3ed81 [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
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000013import os
Skip Montanaro4533f602001-08-20 20:28:48 +000014
Antoine Pitrou557934f2009-11-06 22:41:14 +000015from test import lock_tests
16
Tim Peters84d54892005-01-08 06:03:17 +000017# A trivial mutable counter.
18class Counter(object):
19 def __init__(self):
20 self.value = 0
21 def inc(self):
22 self.value += 1
23 def dec(self):
24 self.value -= 1
25 def get(self):
26 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000027
28class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000029 def __init__(self, name, testcase, sema, mutex, nrunning):
30 threading.Thread.__init__(self, name=name)
31 self.testcase = testcase
32 self.sema = sema
33 self.mutex = mutex
34 self.nrunning = nrunning
35
Skip Montanaro4533f602001-08-20 20:28:48 +000036 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000037 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000038 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000039 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000040 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000041
Christian Heimes4fbc72b2008-03-22 00:47:35 +000042 with self.sema:
43 with self.mutex:
44 self.nrunning.inc()
45 if verbose:
46 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000047 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000048
Christian Heimes4fbc72b2008-03-22 00:47:35 +000049 time.sleep(delay)
50 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000051 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000052
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 with self.mutex:
54 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000055 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000056 if verbose:
57 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000058 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000059
Skip Montanaro4533f602001-08-20 20:28:48 +000060
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000061class BaseTestCase(unittest.TestCase):
62 def setUp(self):
63 self._threads = test.support.threading_setup()
64
65 def tearDown(self):
66 test.support.threading_cleanup(*self._threads)
67 test.support.reap_children()
68
69
70class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000071
Tim Peters84d54892005-01-08 06:03:17 +000072 # Create a bunch of threads, let each do some work, wait until all are
73 # done.
74 def test_various_ops(self):
75 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
76 # times about 1 second per clump).
77 NUMTASKS = 10
78
79 # no more than 3 of the 10 can run at once
80 sema = threading.BoundedSemaphore(value=3)
81 mutex = threading.RLock()
82 numrunning = Counter()
83
84 threads = []
85
86 for i in range(NUMTASKS):
87 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
88 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000089 self.assertEqual(t.ident, None)
90 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000091 t.start()
92
93 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000094 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000095 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000096 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000097 self.assertTrue(not t.is_alive())
98 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +000099 self.assertFalse(t.ident is None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000100 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000101 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000102 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000103 self.assertEqual(numrunning.get(), 0)
104
Benjamin Petersond23f8222009-04-05 19:13:16 +0000105 def test_ident_of_no_threading_threads(self):
106 # The ident still must work for the main thread and dummy threads.
107 self.assertFalse(threading.currentThread().ident is None)
108 def f():
109 ident.append(threading.currentThread().ident)
110 done.set()
111 done = threading.Event()
112 ident = []
113 _thread.start_new_thread(f, ())
114 done.wait()
115 self.assertFalse(ident[0] is None)
116
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000117 # run with a small(ish) thread stack size (256kB)
118 def test_various_ops_small_stack(self):
119 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000120 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000121 try:
122 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000123 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000124 raise unittest.SkipTest(
125 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 self.test_various_ops()
127 threading.stack_size(0)
128
129 # run with a large thread stack size (1MB)
130 def test_various_ops_large_stack(self):
131 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000132 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000133 try:
134 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000135 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000136 raise unittest.SkipTest(
137 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 self.test_various_ops()
139 threading.stack_size(0)
140
Tim Peters711906e2005-01-08 07:30:42 +0000141 def test_foreign_thread(self):
142 # Check that a "foreign" thread can use the threading module.
143 def f(mutex):
144 # Acquiring an RLock forces an entry for the foreign
145 # thread to get made in the threading._active map.
146 r = threading.RLock()
147 r.acquire()
148 r.release()
149 mutex.release()
150
151 mutex = threading.Lock()
152 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000153 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000154 # Wait for the thread to finish.
155 mutex.acquire()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000156 self.assertTrue(tid in threading._active)
157 self.assertTrue(isinstance(threading._active[tid],
Tim Peters711906e2005-01-08 07:30:42 +0000158 threading._DummyThread))
159 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000160
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
162 # exposed at the Python level. This test relies on ctypes to get at it.
163 def test_PyThreadState_SetAsyncExc(self):
164 try:
165 import ctypes
166 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000167 raise unittest.SkipTest("cannot import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000168
169 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
170
171 class AsyncExc(Exception):
172 pass
173
174 exception = ctypes.py_object(AsyncExc)
175
Antoine Pitroube4d8092009-10-18 18:27:17 +0000176 # First check it works when setting the exception from the same thread.
177 tid = _thread.get_ident()
178
179 try:
180 result = set_async_exc(ctypes.c_long(tid), exception)
181 # The exception is async, so we might have to keep the VM busy until
182 # it notices.
183 while True:
184 pass
185 except AsyncExc:
186 pass
187 else:
188 self.fail("AsyncExc not raised")
189 try:
190 self.assertEqual(result, 1) # one thread state modified
191 except UnboundLocalError:
192 # The exception was raised to quickly for us to get the result.
193 pass
194
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000195 # `worker_started` is set by the thread when it's inside a try/except
196 # block waiting to catch the asynchronously set AsyncExc exception.
197 # `worker_saw_exception` is set by the thread upon catching that
198 # exception.
199 worker_started = threading.Event()
200 worker_saw_exception = threading.Event()
201
202 class Worker(threading.Thread):
203 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000204 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000205 self.finished = False
206
207 try:
208 while True:
209 worker_started.set()
210 time.sleep(0.1)
211 except AsyncExc:
212 self.finished = True
213 worker_saw_exception.set()
214
215 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000216 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000217 t.start()
218 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220
221 # Try a thread id that doesn't make sense.
222 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000223 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000224 result = set_async_exc(ctypes.c_long(-1), exception)
225 self.assertEqual(result, 0) # no thread states modified
226
227 # Now raise an exception in the worker thread.
228 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000230 ret = worker_started.wait()
231 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000233 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000234 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000235 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000236 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000237 result = set_async_exc(ctypes.c_long(t.id), exception)
238 self.assertEqual(result, 1) # one thread state modified
239 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000242 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000243 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 if t.finished:
246 t.join()
247 # else the thread is still running, and we have no way to kill it
248
Christian Heimes7d2ff882007-11-30 14:35:04 +0000249 def test_finalize_runnning_thread(self):
250 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
251 # very late on python exit: on deallocation of a running thread for
252 # example.
253 try:
254 import ctypes
255 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000256 raise unittest.SkipTest("cannot import ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000257
258 import subprocess
259 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000260 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000261
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000262 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000263 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000264 ready.acquire()
265
Christian Heimes7d2ff882007-11-30 14:35:04 +0000266 # Module globals are cleared before __del__ is run
267 # So we save the functions in class dict
268 class C:
269 ensure = ctypes.pythonapi.PyGILState_Ensure
270 release = ctypes.pythonapi.PyGILState_Release
271 def __del__(self):
272 state = self.ensure()
273 self.release(state)
274
275 def waitingThread():
276 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000277 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278 time.sleep(100)
279
Georg Brandl2067bfd2008-05-25 13:05:15 +0000280 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000281 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000282 sys.exit(42)
283 """])
284 self.assertEqual(rc, 42)
285
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000286 def test_finalize_with_trace(self):
287 # Issue1733757
288 # Avoid a deadlock when sys.settrace steps into threading._shutdown
289 import subprocess
290 rc = subprocess.call([sys.executable, "-c", """if 1:
291 import sys, threading
292
293 # A deadlock-killer, to prevent the
294 # testsuite to hang forever
295 def killer():
296 import os, time
297 time.sleep(2)
298 print('program blocked; aborting')
299 os._exit(2)
300 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000301 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000302 t.start()
303
304 # This is the trace function
305 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000306 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000307 return func
308
309 sys.settrace(func)
310 """])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertFalse(rc == 2, "interpreted was blocked")
312 self.assertTrue(rc == 0, "Unexpected error")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000313
Antoine Pitrou011bd622009-10-20 21:52:47 +0000314 def test_join_nondaemon_on_shutdown(self):
315 # Issue 1722344
316 # Raising SystemExit skipped threading._shutdown
317 import subprocess
318 p = subprocess.Popen([sys.executable, "-c", """if 1:
319 import threading
320 from time import sleep
321
322 def child():
323 sleep(1)
324 # As a non-daemon thread we SHOULD wake up and nothing
325 # should be torn down yet
326 print("Woke up, sleep function is:", sleep)
327
328 threading.Thread(target=child).start()
329 raise SystemExit
330 """],
331 stdout=subprocess.PIPE,
332 stderr=subprocess.PIPE)
333 stdout, stderr = p.communicate()
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000334 self.assertEqual(stdout.strip(),
335 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou6a354d72009-10-20 22:05:38 +0000336 stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
Antoine Pitrou011bd622009-10-20 21:52:47 +0000337 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000338
Christian Heimes1af737c2008-01-23 08:24:23 +0000339 def test_enumerate_after_join(self):
340 # Try hard to trigger #1703448: a thread is still returned in
341 # threading.enumerate() after it has been join()ed.
342 enum = threading.enumerate
343 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000344 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000345 for i in range(1, 100):
346 # Try a couple times at each thread-switching interval
347 # to get more interleavings.
348 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000349 t = threading.Thread(target=lambda: None)
350 t.start()
351 t.join()
352 l = enum()
353 self.assertFalse(t in l,
354 "#1703448 triggered after %d trials: %s" % (i, l))
355 finally:
356 sys.setcheckinterval(old_interval)
357
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000358 def test_no_refcycle_through_target(self):
359 class RunSelfFunction(object):
360 def __init__(self, should_raise):
361 # The links in this refcycle from Thread back to self
362 # should be cleaned up when the thread completes.
363 self.should_raise = should_raise
364 self.thread = threading.Thread(target=self._run,
365 args=(self,),
366 kwargs={'yet_another':self})
367 self.thread.start()
368
369 def _run(self, other_ref, yet_another):
370 if self.should_raise:
371 raise SystemExit
372
373 cyclic_object = RunSelfFunction(should_raise=False)
374 weak_cyclic_object = weakref.ref(cyclic_object)
375 cyclic_object.thread.join()
376 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000377 self.assertEquals(None, weak_cyclic_object(),
378 msg=('%d references still around' %
379 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000380
381 raising_cyclic_object = RunSelfFunction(should_raise=True)
382 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
383 raising_cyclic_object.thread.join()
384 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000385 self.assertEquals(None, weak_raising_cyclic_object(),
386 msg=('%d references still around' %
387 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000388
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000389 def test_old_threading_api(self):
390 # Just a quick sanity check to make sure the old method names are
391 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000392 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000393 t.isDaemon()
394 t.setDaemon(True)
395 t.getName()
396 t.setName("name")
397 t.isAlive()
398 e = threading.Event()
399 e.isSet()
400 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000401
Christian Heimes1af737c2008-01-23 08:24:23 +0000402
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000403class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000404
405 def _run_and_join(self, script):
406 script = """if 1:
407 import sys, os, time, threading
408
409 # a thread, which waits for the main program to terminate
410 def joiningfunc(mainthread):
411 mainthread.join()
412 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000413 # stdout is fully buffered because not a tty, we have to flush
414 # before exit.
415 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000416 \n""" + script
417
418 import subprocess
419 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
420 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000421 data = p.stdout.read().decode().replace('\r', '')
422 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000423 self.assertFalse(rc == 2, "interpreter was blocked")
424 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000425
426 def test_1_join_on_shutdown(self):
427 # The usual case: on exit, wait for a non-daemon thread
428 script = """if 1:
429 import os
430 t = threading.Thread(target=joiningfunc,
431 args=(threading.current_thread(),))
432 t.start()
433 time.sleep(0.1)
434 print('end of main')
435 """
436 self._run_and_join(script)
437
438
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000439 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000440 def test_2_join_in_forked_process(self):
441 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000442 script = """if 1:
443 childpid = os.fork()
444 if childpid != 0:
445 os.waitpid(childpid, 0)
446 sys.exit(0)
447
448 t = threading.Thread(target=joiningfunc,
449 args=(threading.current_thread(),))
450 t.start()
451 print('end of main')
452 """
453 self._run_and_join(script)
454
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000455 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000456 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000457 # Like the test above, but fork() was called from a worker thread
458 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000459
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000460 # Skip platforms with known problems forking from a worker thread.
461 # See http://bugs.python.org/issue3863.
462 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000463 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000464 script = """if 1:
465 main_thread = threading.current_thread()
466 def worker():
467 childpid = os.fork()
468 if childpid != 0:
469 os.waitpid(childpid, 0)
470 sys.exit(0)
471
472 t = threading.Thread(target=joiningfunc,
473 args=(main_thread,))
474 print('end of main')
475 t.start()
476 t.join() # Should not block: main_thread is already stopped
477
478 w = threading.Thread(target=worker)
479 w.start()
480 """
481 self._run_and_join(script)
482
483
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000484class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000485 # A RuntimeError should be raised if Thread.start() is called
486 # multiple times.
487 def test_start_thread_again(self):
488 thread = threading.Thread()
489 thread.start()
490 self.assertRaises(RuntimeError, thread.start)
491
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000492 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000493 current_thread = threading.current_thread()
494 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000495
496 def test_joining_inactive_thread(self):
497 thread = threading.Thread()
498 self.assertRaises(RuntimeError, thread.join)
499
500 def test_daemonize_active_thread(self):
501 thread = threading.Thread()
502 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000503 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000504
505
Antoine Pitrou557934f2009-11-06 22:41:14 +0000506class LockTests(lock_tests.LockTests):
507 locktype = staticmethod(threading.Lock)
508
509class RLockTests(lock_tests.RLockTests):
510 locktype = staticmethod(threading.RLock)
511
512class EventTests(lock_tests.EventTests):
513 eventtype = staticmethod(threading.Event)
514
515class ConditionAsRLockTests(lock_tests.RLockTests):
516 # An Condition uses an RLock by default and exports its API.
517 locktype = staticmethod(threading.Condition)
518
519class ConditionTests(lock_tests.ConditionTests):
520 condtype = staticmethod(threading.Condition)
521
522class SemaphoreTests(lock_tests.SemaphoreTests):
523 semtype = staticmethod(threading.Semaphore)
524
525class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
526 semtype = staticmethod(threading.BoundedSemaphore)
527
528
Tim Peters84d54892005-01-08 06:03:17 +0000529def test_main():
Antoine Pitrou557934f2009-11-06 22:41:14 +0000530 test.support.run_unittest(LockTests, RLockTests, EventTests,
531 ConditionAsRLockTests, ConditionTests,
532 SemaphoreTests, BoundedSemaphoreTests,
533 ThreadTests,
534 ThreadJoinOnShutdown,
535 ThreadingExceptionTests,
536 )
Tim Peters84d54892005-01-08 06:03:17 +0000537
538if __name__ == "__main__":
539 test_main()