blob: 2e4f645e43a5ed8dc5dcfa13c740f461ed654003 [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")
324 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000325
Christian Heimes1af737c2008-01-23 08:24:23 +0000326 def test_enumerate_after_join(self):
327 # Try hard to trigger #1703448: a thread is still returned in
328 # threading.enumerate() after it has been join()ed.
329 enum = threading.enumerate
330 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000331 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000332 for i in range(1, 100):
333 # Try a couple times at each thread-switching interval
334 # to get more interleavings.
335 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000336 t = threading.Thread(target=lambda: None)
337 t.start()
338 t.join()
339 l = enum()
340 self.assertFalse(t in l,
341 "#1703448 triggered after %d trials: %s" % (i, l))
342 finally:
343 sys.setcheckinterval(old_interval)
344
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000345 def test_no_refcycle_through_target(self):
346 class RunSelfFunction(object):
347 def __init__(self, should_raise):
348 # The links in this refcycle from Thread back to self
349 # should be cleaned up when the thread completes.
350 self.should_raise = should_raise
351 self.thread = threading.Thread(target=self._run,
352 args=(self,),
353 kwargs={'yet_another':self})
354 self.thread.start()
355
356 def _run(self, other_ref, yet_another):
357 if self.should_raise:
358 raise SystemExit
359
360 cyclic_object = RunSelfFunction(should_raise=False)
361 weak_cyclic_object = weakref.ref(cyclic_object)
362 cyclic_object.thread.join()
363 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000364 self.assertEquals(None, weak_cyclic_object(),
365 msg=('%d references still around' %
366 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000367
368 raising_cyclic_object = RunSelfFunction(should_raise=True)
369 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
370 raising_cyclic_object.thread.join()
371 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000372 self.assertEquals(None, weak_raising_cyclic_object(),
373 msg=('%d references still around' %
374 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000375
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000376 def test_old_threading_api(self):
377 # Just a quick sanity check to make sure the old method names are
378 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000379 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000380 t.isDaemon()
381 t.setDaemon(True)
382 t.getName()
383 t.setName("name")
384 t.isAlive()
385 e = threading.Event()
386 e.isSet()
387 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000388
Christian Heimes1af737c2008-01-23 08:24:23 +0000389
Jesse Nollera8513972008-07-17 16:49:17 +0000390class ThreadJoinOnShutdown(unittest.TestCase):
391
392 def _run_and_join(self, script):
393 script = """if 1:
394 import sys, os, time, threading
395
396 # a thread, which waits for the main program to terminate
397 def joiningfunc(mainthread):
398 mainthread.join()
399 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000400 # stdout is fully buffered because not a tty, we have to flush
401 # before exit.
402 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000403 \n""" + script
404
405 import subprocess
406 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
407 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000408 data = p.stdout.read().decode().replace('\r', '')
409 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000410 self.assertFalse(rc == 2, "interpreter was blocked")
411 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000412
413 def test_1_join_on_shutdown(self):
414 # The usual case: on exit, wait for a non-daemon thread
415 script = """if 1:
416 import os
417 t = threading.Thread(target=joiningfunc,
418 args=(threading.current_thread(),))
419 t.start()
420 time.sleep(0.1)
421 print('end of main')
422 """
423 self._run_and_join(script)
424
425
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000426 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000427 def test_2_join_in_forked_process(self):
428 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000429 script = """if 1:
430 childpid = os.fork()
431 if childpid != 0:
432 os.waitpid(childpid, 0)
433 sys.exit(0)
434
435 t = threading.Thread(target=joiningfunc,
436 args=(threading.current_thread(),))
437 t.start()
438 print('end of main')
439 """
440 self._run_and_join(script)
441
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000442 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000443 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000444 # Like the test above, but fork() was called from a worker thread
445 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000446
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000447 # Skip platforms with known problems forking from a worker thread.
448 # See http://bugs.python.org/issue3863.
449 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000450 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000451 script = """if 1:
452 main_thread = threading.current_thread()
453 def worker():
454 childpid = os.fork()
455 if childpid != 0:
456 os.waitpid(childpid, 0)
457 sys.exit(0)
458
459 t = threading.Thread(target=joiningfunc,
460 args=(main_thread,))
461 print('end of main')
462 t.start()
463 t.join() # Should not block: main_thread is already stopped
464
465 w = threading.Thread(target=worker)
466 w.start()
467 """
468 self._run_and_join(script)
469
470
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000471class ThreadingExceptionTests(unittest.TestCase):
472 # A RuntimeError should be raised if Thread.start() is called
473 # multiple times.
474 def test_start_thread_again(self):
475 thread = threading.Thread()
476 thread.start()
477 self.assertRaises(RuntimeError, thread.start)
478
479 def test_releasing_unacquired_rlock(self):
480 rlock = threading.RLock()
481 self.assertRaises(RuntimeError, rlock.release)
482
483 def test_waiting_on_unacquired_condition(self):
484 cond = threading.Condition()
485 self.assertRaises(RuntimeError, cond.wait)
486
487 def test_notify_on_unacquired_condition(self):
488 cond = threading.Condition()
489 self.assertRaises(RuntimeError, cond.notify)
490
491 def test_semaphore_with_negative_value(self):
492 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000493 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000494
495 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000496 current_thread = threading.current_thread()
497 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000498
499 def test_joining_inactive_thread(self):
500 thread = threading.Thread()
501 self.assertRaises(RuntimeError, thread.join)
502
503 def test_daemonize_active_thread(self):
504 thread = threading.Thread()
505 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000506 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000507
508
Tim Peters84d54892005-01-08 06:03:17 +0000509def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000510 test.support.run_unittest(ThreadTests,
Jesse Nollera8513972008-07-17 16:49:17 +0000511 ThreadJoinOnShutdown,
512 ThreadingExceptionTests,
513 )
Tim Peters84d54892005-01-08 06:03:17 +0000514
515if __name__ == "__main__":
516 test_main()