blob: b8265aa9238d91f37036f2dde059e5786c807ba6 [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)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000116 # Kill the "immortal" _DummyThread
117 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000118
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000119 # run with a small(ish) thread stack size (256kB)
120 def test_various_ops_small_stack(self):
121 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 try:
124 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000125 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000126 raise unittest.SkipTest(
127 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000128 self.test_various_ops()
129 threading.stack_size(0)
130
131 # run with a large thread stack size (1MB)
132 def test_various_ops_large_stack(self):
133 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000134 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 try:
136 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000137 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000138 raise unittest.SkipTest(
139 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 Pitroub0872682009-11-09 16:08:16 +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 Pitroub0872682009-11-09 16:08:16 +0000148 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000149 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 Peterson577473f2010-01-19 00:09:57 +0000156 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +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
Thomas Wouters00ee7ba2006-08-21 19:07:27 +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:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000166 raise unittest.SkipTest("cannot import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000167
168 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
169
170 class AsyncExc(Exception):
171 pass
172
173 exception = ctypes.py_object(AsyncExc)
174
Antoine Pitroube4d8092009-10-18 18:27:17 +0000175 # First check it works when setting the exception from the same thread.
176 tid = _thread.get_ident()
177
178 try:
179 result = set_async_exc(ctypes.c_long(tid), exception)
180 # The exception is async, so we might have to keep the VM busy until
181 # it notices.
182 while True:
183 pass
184 except AsyncExc:
185 pass
186 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000187 # This code is unreachable but it reflects the intent. If we wanted
188 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000189 self.fail("AsyncExc not raised")
190 try:
191 self.assertEqual(result, 1) # one thread state modified
192 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000193 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000194 pass
195
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000196 # `worker_started` is set by the thread when it's inside a try/except
197 # block waiting to catch the asynchronously set AsyncExc exception.
198 # `worker_saw_exception` is set by the thread upon catching that
199 # exception.
200 worker_started = threading.Event()
201 worker_saw_exception = threading.Event()
202
203 class Worker(threading.Thread):
204 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000205 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000206 self.finished = False
207
208 try:
209 while True:
210 worker_started.set()
211 time.sleep(0.1)
212 except AsyncExc:
213 self.finished = True
214 worker_saw_exception.set()
215
216 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000217 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 t.start()
219 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000220 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221
222 # Try a thread id that doesn't make sense.
223 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000224 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000225 result = set_async_exc(ctypes.c_long(-1), exception)
226 self.assertEqual(result, 0) # no thread states modified
227
228 # Now raise an exception in the worker thread.
229 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000230 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000231 ret = worker_started.wait()
232 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000234 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000237 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000238 result = set_async_exc(ctypes.c_long(t.id), exception)
239 self.assertEqual(result, 1) # one thread state modified
240 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000241 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000242 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000243 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000246 if t.finished:
247 t.join()
248 # else the thread is still running, and we have no way to kill it
249
Christian Heimes7d2ff882007-11-30 14:35:04 +0000250 def test_finalize_runnning_thread(self):
251 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
252 # very late on python exit: on deallocation of a running thread for
253 # example.
254 try:
255 import ctypes
256 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000257 raise unittest.SkipTest("cannot import ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000258
259 import subprocess
260 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000261 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000262
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000263 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000264 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000265 ready.acquire()
266
Christian Heimes7d2ff882007-11-30 14:35:04 +0000267 # Module globals are cleared before __del__ is run
268 # So we save the functions in class dict
269 class C:
270 ensure = ctypes.pythonapi.PyGILState_Ensure
271 release = ctypes.pythonapi.PyGILState_Release
272 def __del__(self):
273 state = self.ensure()
274 self.release(state)
275
276 def waitingThread():
277 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000278 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000279 time.sleep(100)
280
Georg Brandl2067bfd2008-05-25 13:05:15 +0000281 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000282 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000283 sys.exit(42)
284 """])
285 self.assertEqual(rc, 42)
286
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000287 def test_finalize_with_trace(self):
288 # Issue1733757
289 # Avoid a deadlock when sys.settrace steps into threading._shutdown
290 import subprocess
291 rc = subprocess.call([sys.executable, "-c", """if 1:
292 import sys, threading
293
294 # A deadlock-killer, to prevent the
295 # testsuite to hang forever
296 def killer():
297 import os, time
298 time.sleep(2)
299 print('program blocked; aborting')
300 os._exit(2)
301 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000302 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000303 t.start()
304
305 # This is the trace function
306 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000307 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000308 return func
309
310 sys.settrace(func)
311 """])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000312 self.assertFalse(rc == 2, "interpreted was blocked")
313 self.assertTrue(rc == 0, "Unexpected error")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000314
Antoine Pitrou011bd622009-10-20 21:52:47 +0000315 def test_join_nondaemon_on_shutdown(self):
316 # Issue 1722344
317 # Raising SystemExit skipped threading._shutdown
318 import subprocess
319 p = subprocess.Popen([sys.executable, "-c", """if 1:
320 import threading
321 from time import sleep
322
323 def child():
324 sleep(1)
325 # As a non-daemon thread we SHOULD wake up and nothing
326 # should be torn down yet
327 print("Woke up, sleep function is:", sleep)
328
329 threading.Thread(target=child).start()
330 raise SystemExit
331 """],
332 stdout=subprocess.PIPE,
333 stderr=subprocess.PIPE)
334 stdout, stderr = p.communicate()
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000335 self.assertEqual(stdout.strip(),
336 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou6a354d72009-10-20 22:05:38 +0000337 stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
Antoine Pitrou011bd622009-10-20 21:52:47 +0000338 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000339
Christian Heimes1af737c2008-01-23 08:24:23 +0000340 def test_enumerate_after_join(self):
341 # Try hard to trigger #1703448: a thread is still returned in
342 # threading.enumerate() after it has been join()ed.
343 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000344 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000345 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000346 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000347 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000348 t = threading.Thread(target=lambda: None)
349 t.start()
350 t.join()
351 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000352 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000353 "#1703448 triggered after %d trials: %s" % (i, l))
354 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000355 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000356
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000357 def test_no_refcycle_through_target(self):
358 class RunSelfFunction(object):
359 def __init__(self, should_raise):
360 # The links in this refcycle from Thread back to self
361 # should be cleaned up when the thread completes.
362 self.should_raise = should_raise
363 self.thread = threading.Thread(target=self._run,
364 args=(self,),
365 kwargs={'yet_another':self})
366 self.thread.start()
367
368 def _run(self, other_ref, yet_another):
369 if self.should_raise:
370 raise SystemExit
371
372 cyclic_object = RunSelfFunction(should_raise=False)
373 weak_cyclic_object = weakref.ref(cyclic_object)
374 cyclic_object.thread.join()
375 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000376 self.assertEquals(None, weak_cyclic_object(),
377 msg=('%d references still around' %
378 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000379
380 raising_cyclic_object = RunSelfFunction(should_raise=True)
381 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
382 raising_cyclic_object.thread.join()
383 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000384 self.assertEquals(None, weak_raising_cyclic_object(),
385 msg=('%d references still around' %
386 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000387
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000388 def test_old_threading_api(self):
389 # Just a quick sanity check to make sure the old method names are
390 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000391 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000392 t.isDaemon()
393 t.setDaemon(True)
394 t.getName()
395 t.setName("name")
396 t.isAlive()
397 e = threading.Event()
398 e.isSet()
399 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000400
Christian Heimes1af737c2008-01-23 08:24:23 +0000401
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000402class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000403
404 def _run_and_join(self, script):
405 script = """if 1:
406 import sys, os, time, threading
407
408 # a thread, which waits for the main program to terminate
409 def joiningfunc(mainthread):
410 mainthread.join()
411 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000412 # stdout is fully buffered because not a tty, we have to flush
413 # before exit.
414 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000415 \n""" + script
416
417 import subprocess
418 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
419 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000420 data = p.stdout.read().decode().replace('\r', '')
421 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000422 self.assertFalse(rc == 2, "interpreter was blocked")
423 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000424
425 def test_1_join_on_shutdown(self):
426 # The usual case: on exit, wait for a non-daemon thread
427 script = """if 1:
428 import os
429 t = threading.Thread(target=joiningfunc,
430 args=(threading.current_thread(),))
431 t.start()
432 time.sleep(0.1)
433 print('end of main')
434 """
435 self._run_and_join(script)
436
437
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000438 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000439 def test_2_join_in_forked_process(self):
440 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000441 script = """if 1:
442 childpid = os.fork()
443 if childpid != 0:
444 os.waitpid(childpid, 0)
445 sys.exit(0)
446
447 t = threading.Thread(target=joiningfunc,
448 args=(threading.current_thread(),))
449 t.start()
450 print('end of main')
451 """
452 self._run_and_join(script)
453
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000454 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000455 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000456 # Like the test above, but fork() was called from a worker thread
457 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000458
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000459 # Skip platforms with known problems forking from a worker thread.
460 # See http://bugs.python.org/issue3863.
461 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000462 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000463 script = """if 1:
464 main_thread = threading.current_thread()
465 def worker():
466 childpid = os.fork()
467 if childpid != 0:
468 os.waitpid(childpid, 0)
469 sys.exit(0)
470
471 t = threading.Thread(target=joiningfunc,
472 args=(main_thread,))
473 print('end of main')
474 t.start()
475 t.join() # Should not block: main_thread is already stopped
476
477 w = threading.Thread(target=worker)
478 w.start()
479 """
480 self._run_and_join(script)
481
482
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000483class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000484 # A RuntimeError should be raised if Thread.start() is called
485 # multiple times.
486 def test_start_thread_again(self):
487 thread = threading.Thread()
488 thread.start()
489 self.assertRaises(RuntimeError, thread.start)
490
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000491 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000492 current_thread = threading.current_thread()
493 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000494
495 def test_joining_inactive_thread(self):
496 thread = threading.Thread()
497 self.assertRaises(RuntimeError, thread.join)
498
499 def test_daemonize_active_thread(self):
500 thread = threading.Thread()
501 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000502 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000503
504
Antoine Pitrou557934f2009-11-06 22:41:14 +0000505class LockTests(lock_tests.LockTests):
506 locktype = staticmethod(threading.Lock)
507
Antoine Pitrou434736a2009-11-10 18:46:01 +0000508class PyRLockTests(lock_tests.RLockTests):
509 locktype = staticmethod(threading._PyRLock)
510
511class CRLockTests(lock_tests.RLockTests):
512 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000513
514class EventTests(lock_tests.EventTests):
515 eventtype = staticmethod(threading.Event)
516
517class ConditionAsRLockTests(lock_tests.RLockTests):
518 # An Condition uses an RLock by default and exports its API.
519 locktype = staticmethod(threading.Condition)
520
521class ConditionTests(lock_tests.ConditionTests):
522 condtype = staticmethod(threading.Condition)
523
524class SemaphoreTests(lock_tests.SemaphoreTests):
525 semtype = staticmethod(threading.Semaphore)
526
527class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
528 semtype = staticmethod(threading.BoundedSemaphore)
529
530
Tim Peters84d54892005-01-08 06:03:17 +0000531def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000532 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000533 ConditionAsRLockTests, ConditionTests,
534 SemaphoreTests, BoundedSemaphoreTests,
535 ThreadTests,
536 ThreadJoinOnShutdown,
537 ThreadingExceptionTests,
538 )
Tim Peters84d54892005-01-08 06:03:17 +0000539
540if __name__ == "__main__":
541 test_main()