blob: cc83476d0ce3a296fba075559a4320f51716e186 [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
Tim Peters84d54892005-01-08 06:03:17 +000015# A trivial mutable counter.
16class Counter(object):
17 def __init__(self):
18 self.value = 0
19 def inc(self):
20 self.value += 1
21 def dec(self):
22 self.value -= 1
23 def get(self):
24 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000025
26class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000027 def __init__(self, name, testcase, sema, mutex, nrunning):
28 threading.Thread.__init__(self, name=name)
29 self.testcase = testcase
30 self.sema = sema
31 self.mutex = mutex
32 self.nrunning = nrunning
33
Skip Montanaro4533f602001-08-20 20:28:48 +000034 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000035 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000036 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000037 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000038 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000039
Christian Heimes4fbc72b2008-03-22 00:47:35 +000040 with self.sema:
41 with self.mutex:
42 self.nrunning.inc()
43 if verbose:
44 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000045 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000046
Christian Heimes4fbc72b2008-03-22 00:47:35 +000047 time.sleep(delay)
48 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000049 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000050
Christian Heimes4fbc72b2008-03-22 00:47:35 +000051 with self.mutex:
52 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000053 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000054 if verbose:
55 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000056 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000057
Skip Montanaro4533f602001-08-20 20:28:48 +000058
Tim Peters84d54892005-01-08 06:03:17 +000059class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000060
Tim Peters84d54892005-01-08 06:03:17 +000061 # Create a bunch of threads, let each do some work, wait until all are
62 # done.
63 def test_various_ops(self):
64 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
65 # times about 1 second per clump).
66 NUMTASKS = 10
67
68 # no more than 3 of the 10 can run at once
69 sema = threading.BoundedSemaphore(value=3)
70 mutex = threading.RLock()
71 numrunning = Counter()
72
73 threads = []
74
75 for i in range(NUMTASKS):
76 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
77 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000078 self.assertEqual(t.ident, None)
79 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000080 t.start()
81
82 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000083 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000084 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000085 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000086 self.assertTrue(not t.is_alive())
87 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +000088 self.assertFalse(t.ident is None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000089 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000090 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000091 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000092 self.assertEqual(numrunning.get(), 0)
93
Benjamin Petersond23f8222009-04-05 19:13:16 +000094 def test_ident_of_no_threading_threads(self):
95 # The ident still must work for the main thread and dummy threads.
96 self.assertFalse(threading.currentThread().ident is None)
97 def f():
98 ident.append(threading.currentThread().ident)
99 done.set()
100 done = threading.Event()
101 ident = []
102 _thread.start_new_thread(f, ())
103 done.wait()
104 self.assertFalse(ident[0] is None)
105
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106 # run with a small(ish) thread stack size (256kB)
107 def test_various_ops_small_stack(self):
108 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000110 try:
111 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000112 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000113 raise unittest.SkipTest(
114 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000115 self.test_various_ops()
116 threading.stack_size(0)
117
118 # run with a large thread stack size (1MB)
119 def test_various_ops_large_stack(self):
120 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000121 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 try:
123 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000124 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000125 raise unittest.SkipTest(
126 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 self.test_various_ops()
128 threading.stack_size(0)
129
Tim Peters711906e2005-01-08 07:30:42 +0000130 def test_foreign_thread(self):
131 # Check that a "foreign" thread can use the threading module.
132 def f(mutex):
133 # Acquiring an RLock forces an entry for the foreign
134 # thread to get made in the threading._active map.
135 r = threading.RLock()
136 r.acquire()
137 r.release()
138 mutex.release()
139
140 mutex = threading.Lock()
141 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000142 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000143 # Wait for the thread to finish.
144 mutex.acquire()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000145 self.assertTrue(tid in threading._active)
146 self.assertTrue(isinstance(threading._active[tid],
Tim Peters711906e2005-01-08 07:30:42 +0000147 threading._DummyThread))
148 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000149
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000150 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
151 # exposed at the Python level. This test relies on ctypes to get at it.
152 def test_PyThreadState_SetAsyncExc(self):
153 try:
154 import ctypes
155 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000156 raise unittest.SkipTest("cannot import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000157
158 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
159
160 class AsyncExc(Exception):
161 pass
162
163 exception = ctypes.py_object(AsyncExc)
164
Antoine Pitroube4d8092009-10-18 18:27:17 +0000165 # First check it works when setting the exception from the same thread.
166 tid = _thread.get_ident()
167
168 try:
169 result = set_async_exc(ctypes.c_long(tid), exception)
170 # The exception is async, so we might have to keep the VM busy until
171 # it notices.
172 while True:
173 pass
174 except AsyncExc:
175 pass
176 else:
177 self.fail("AsyncExc not raised")
178 try:
179 self.assertEqual(result, 1) # one thread state modified
180 except UnboundLocalError:
181 # The exception was raised to quickly for us to get the result.
182 pass
183
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000184 # `worker_started` is set by the thread when it's inside a try/except
185 # block waiting to catch the asynchronously set AsyncExc exception.
186 # `worker_saw_exception` is set by the thread upon catching that
187 # exception.
188 worker_started = threading.Event()
189 worker_saw_exception = threading.Event()
190
191 class Worker(threading.Thread):
192 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000193 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000194 self.finished = False
195
196 try:
197 while True:
198 worker_started.set()
199 time.sleep(0.1)
200 except AsyncExc:
201 self.finished = True
202 worker_saw_exception.set()
203
204 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000205 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000206 t.start()
207 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000209
210 # Try a thread id that doesn't make sense.
211 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000212 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000213 result = set_async_exc(ctypes.c_long(-1), exception)
214 self.assertEqual(result, 0) # no thread states modified
215
216 # Now raise an exception in the worker thread.
217 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000218 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000219 ret = worker_started.wait()
220 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000222 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000223 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000224 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000225 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000226 result = set_async_exc(ctypes.c_long(t.id), exception)
227 self.assertEqual(result, 1) # one thread state modified
228 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000230 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000231 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000233 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000234 if t.finished:
235 t.join()
236 # else the thread is still running, and we have no way to kill it
237
Christian Heimes7d2ff882007-11-30 14:35:04 +0000238 def test_finalize_runnning_thread(self):
239 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
240 # very late on python exit: on deallocation of a running thread for
241 # example.
242 try:
243 import ctypes
244 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000245 raise unittest.SkipTest("cannot import ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000246
247 import subprocess
248 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000249 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000250
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000251 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000252 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000253 ready.acquire()
254
Christian Heimes7d2ff882007-11-30 14:35:04 +0000255 # Module globals are cleared before __del__ is run
256 # So we save the functions in class dict
257 class C:
258 ensure = ctypes.pythonapi.PyGILState_Ensure
259 release = ctypes.pythonapi.PyGILState_Release
260 def __del__(self):
261 state = self.ensure()
262 self.release(state)
263
264 def waitingThread():
265 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000266 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000267 time.sleep(100)
268
Georg Brandl2067bfd2008-05-25 13:05:15 +0000269 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000270 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000271 sys.exit(42)
272 """])
273 self.assertEqual(rc, 42)
274
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000275 def test_finalize_with_trace(self):
276 # Issue1733757
277 # Avoid a deadlock when sys.settrace steps into threading._shutdown
278 import subprocess
279 rc = subprocess.call([sys.executable, "-c", """if 1:
280 import sys, threading
281
282 # A deadlock-killer, to prevent the
283 # testsuite to hang forever
284 def killer():
285 import os, time
286 time.sleep(2)
287 print('program blocked; aborting')
288 os._exit(2)
289 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000290 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000291 t.start()
292
293 # This is the trace function
294 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000295 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000296 return func
297
298 sys.settrace(func)
299 """])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000300 self.assertFalse(rc == 2, "interpreted was blocked")
301 self.assertTrue(rc == 0, "Unexpected error")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000302
Antoine Pitrou011bd622009-10-20 21:52:47 +0000303 def test_join_nondaemon_on_shutdown(self):
304 # Issue 1722344
305 # Raising SystemExit skipped threading._shutdown
306 import subprocess
307 p = subprocess.Popen([sys.executable, "-c", """if 1:
308 import threading
309 from time import sleep
310
311 def child():
312 sleep(1)
313 # As a non-daemon thread we SHOULD wake up and nothing
314 # should be torn down yet
315 print("Woke up, sleep function is:", sleep)
316
317 threading.Thread(target=child).start()
318 raise SystemExit
319 """],
320 stdout=subprocess.PIPE,
321 stderr=subprocess.PIPE)
322 stdout, stderr = p.communicate()
323 self.assertEqual(stdout, b"Woke up, sleep function is: <built-in function sleep>\n")
Antoine Pitrou6a354d72009-10-20 22:05:38 +0000324 stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
Antoine Pitrou011bd622009-10-20 21:52:47 +0000325 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000326
Christian Heimes1af737c2008-01-23 08:24:23 +0000327 def test_enumerate_after_join(self):
328 # Try hard to trigger #1703448: a thread is still returned in
329 # threading.enumerate() after it has been join()ed.
330 enum = threading.enumerate
331 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000332 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000333 for i in range(1, 100):
334 # Try a couple times at each thread-switching interval
335 # to get more interleavings.
336 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000337 t = threading.Thread(target=lambda: None)
338 t.start()
339 t.join()
340 l = enum()
341 self.assertFalse(t in l,
342 "#1703448 triggered after %d trials: %s" % (i, l))
343 finally:
344 sys.setcheckinterval(old_interval)
345
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000346 def test_no_refcycle_through_target(self):
347 class RunSelfFunction(object):
348 def __init__(self, should_raise):
349 # The links in this refcycle from Thread back to self
350 # should be cleaned up when the thread completes.
351 self.should_raise = should_raise
352 self.thread = threading.Thread(target=self._run,
353 args=(self,),
354 kwargs={'yet_another':self})
355 self.thread.start()
356
357 def _run(self, other_ref, yet_another):
358 if self.should_raise:
359 raise SystemExit
360
361 cyclic_object = RunSelfFunction(should_raise=False)
362 weak_cyclic_object = weakref.ref(cyclic_object)
363 cyclic_object.thread.join()
364 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000365 self.assertEquals(None, weak_cyclic_object(),
366 msg=('%d references still around' %
367 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000368
369 raising_cyclic_object = RunSelfFunction(should_raise=True)
370 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
371 raising_cyclic_object.thread.join()
372 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000373 self.assertEquals(None, weak_raising_cyclic_object(),
374 msg=('%d references still around' %
375 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000376
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000377 def test_old_threading_api(self):
378 # Just a quick sanity check to make sure the old method names are
379 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000380 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000381 t.isDaemon()
382 t.setDaemon(True)
383 t.getName()
384 t.setName("name")
385 t.isAlive()
386 e = threading.Event()
387 e.isSet()
388 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000389
Christian Heimes1af737c2008-01-23 08:24:23 +0000390
Jesse Nollera8513972008-07-17 16:49:17 +0000391class ThreadJoinOnShutdown(unittest.TestCase):
392
393 def _run_and_join(self, script):
394 script = """if 1:
395 import sys, os, time, threading
396
397 # a thread, which waits for the main program to terminate
398 def joiningfunc(mainthread):
399 mainthread.join()
400 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000401 # stdout is fully buffered because not a tty, we have to flush
402 # before exit.
403 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000404 \n""" + script
405
406 import subprocess
407 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
408 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000409 data = p.stdout.read().decode().replace('\r', '')
410 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000411 self.assertFalse(rc == 2, "interpreter was blocked")
412 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000413
414 def test_1_join_on_shutdown(self):
415 # The usual case: on exit, wait for a non-daemon thread
416 script = """if 1:
417 import os
418 t = threading.Thread(target=joiningfunc,
419 args=(threading.current_thread(),))
420 t.start()
421 time.sleep(0.1)
422 print('end of main')
423 """
424 self._run_and_join(script)
425
426
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000427 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000428 def test_2_join_in_forked_process(self):
429 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000430 script = """if 1:
431 childpid = os.fork()
432 if childpid != 0:
433 os.waitpid(childpid, 0)
434 sys.exit(0)
435
436 t = threading.Thread(target=joiningfunc,
437 args=(threading.current_thread(),))
438 t.start()
439 print('end of main')
440 """
441 self._run_and_join(script)
442
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000443 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000444 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000445 # Like the test above, but fork() was called from a worker thread
446 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000447
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000448 # Skip platforms with known problems forking from a worker thread.
449 # See http://bugs.python.org/issue3863.
450 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000451 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000452 script = """if 1:
453 main_thread = threading.current_thread()
454 def worker():
455 childpid = os.fork()
456 if childpid != 0:
457 os.waitpid(childpid, 0)
458 sys.exit(0)
459
460 t = threading.Thread(target=joiningfunc,
461 args=(main_thread,))
462 print('end of main')
463 t.start()
464 t.join() # Should not block: main_thread is already stopped
465
466 w = threading.Thread(target=worker)
467 w.start()
468 """
469 self._run_and_join(script)
470
471
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000472class ThreadingExceptionTests(unittest.TestCase):
473 # A RuntimeError should be raised if Thread.start() is called
474 # multiple times.
475 def test_start_thread_again(self):
476 thread = threading.Thread()
477 thread.start()
478 self.assertRaises(RuntimeError, thread.start)
479
480 def test_releasing_unacquired_rlock(self):
481 rlock = threading.RLock()
482 self.assertRaises(RuntimeError, rlock.release)
483
484 def test_waiting_on_unacquired_condition(self):
485 cond = threading.Condition()
486 self.assertRaises(RuntimeError, cond.wait)
487
488 def test_notify_on_unacquired_condition(self):
489 cond = threading.Condition()
490 self.assertRaises(RuntimeError, cond.notify)
491
492 def test_semaphore_with_negative_value(self):
493 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000494 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000495
496 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000497 current_thread = threading.current_thread()
498 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000499
500 def test_joining_inactive_thread(self):
501 thread = threading.Thread()
502 self.assertRaises(RuntimeError, thread.join)
503
504 def test_daemonize_active_thread(self):
505 thread = threading.Thread()
506 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000507 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000508
509
Tim Peters84d54892005-01-08 06:03:17 +0000510def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000511 test.support.run_unittest(ThreadTests,
Jesse Nollera8513972008-07-17 16:49:17 +0000512 ThreadJoinOnShutdown,
513 ThreadingExceptionTests,
514 )
Tim Peters84d54892005-01-08 06:03:17 +0000515
516if __name__ == "__main__":
517 test_main()