blob: f6f6b260d02be93ef3ba063d58b4aa02b830e759 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003import test.support
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00004from test.support import verbose
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Georg Brandl0c77a822008-06-10 16:37:50 +00006import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007import sys
Skip Montanaro4533f602001-08-20 20:28:48 +00008import threading
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +000012import weakref
Skip Montanaro4533f602001-08-20 20:28:48 +000013
Tim Peters84d54892005-01-08 06:03:17 +000014# A trivial mutable counter.
15class Counter(object):
16 def __init__(self):
17 self.value = 0
18 def inc(self):
19 self.value += 1
20 def dec(self):
21 self.value -= 1
22 def get(self):
23 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000024
25class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000026 def __init__(self, name, testcase, sema, mutex, nrunning):
27 threading.Thread.__init__(self, name=name)
28 self.testcase = testcase
29 self.sema = sema
30 self.mutex = mutex
31 self.nrunning = nrunning
32
Skip Montanaro4533f602001-08-20 20:28:48 +000033 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000034 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000035 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000036 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000037 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000038
Christian Heimes4fbc72b2008-03-22 00:47:35 +000039 with self.sema:
40 with self.mutex:
41 self.nrunning.inc()
42 if verbose:
43 print(self.nrunning.get(), 'tasks are running')
Georg Brandlab91fde2009-08-13 08:51:18 +000044 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000045
Christian Heimes4fbc72b2008-03-22 00:47:35 +000046 time.sleep(delay)
47 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000048 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000049
Christian Heimes4fbc72b2008-03-22 00:47:35 +000050 with self.mutex:
51 self.nrunning.dec()
Georg Brandlab91fde2009-08-13 08:51:18 +000052 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 if verbose:
54 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000055 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000056
Skip Montanaro4533f602001-08-20 20:28:48 +000057
Tim Peters84d54892005-01-08 06:03:17 +000058class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000059
Tim Peters84d54892005-01-08 06:03:17 +000060 # Create a bunch of threads, let each do some work, wait until all are
61 # done.
62 def test_various_ops(self):
63 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
64 # times about 1 second per clump).
65 NUMTASKS = 10
66
67 # no more than 3 of the 10 can run at once
68 sema = threading.BoundedSemaphore(value=3)
69 mutex = threading.RLock()
70 numrunning = Counter()
71
72 threads = []
73
74 for i in range(NUMTASKS):
75 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
76 threads.append(t)
Georg Brandlab91fde2009-08-13 08:51:18 +000077 self.assertEqual(t.ident, None)
78 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000079 t.start()
80
81 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000082 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000083 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000084 t.join(NUMTASKS)
Georg Brandlab91fde2009-08-13 08:51:18 +000085 self.assertTrue(not t.is_alive())
86 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +000087 self.assertFalse(t.ident is None)
Georg Brandlab91fde2009-08-13 08:51:18 +000088 self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000089 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000090 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000091 self.assertEqual(numrunning.get(), 0)
92
Benjamin Petersond23f8222009-04-05 19:13:16 +000093 def test_ident_of_no_threading_threads(self):
94 # The ident still must work for the main thread and dummy threads.
95 self.assertFalse(threading.currentThread().ident is None)
96 def f():
97 ident.append(threading.currentThread().ident)
98 done.set()
99 done = threading.Event()
100 ident = []
101 _thread.start_new_thread(f, ())
102 done.wait()
103 self.assertFalse(ident[0] is None)
104
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105 # run with a small(ish) thread stack size (256kB)
106 def test_various_ops_small_stack(self):
107 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109 try:
110 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000111 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000113 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114 return
115 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:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000126 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 return
128 self.test_various_ops()
129 threading.stack_size(0)
130
Tim Peters711906e2005-01-08 07:30:42 +0000131 def test_foreign_thread(self):
132 # Check that a "foreign" thread can use the threading module.
133 def f(mutex):
134 # Acquiring an RLock forces an entry for the foreign
135 # thread to get made in the threading._active map.
136 r = threading.RLock()
137 r.acquire()
138 r.release()
139 mutex.release()
140
141 mutex = threading.Lock()
142 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000143 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000144 # Wait for the thread to finish.
145 mutex.acquire()
Georg Brandlab91fde2009-08-13 08:51:18 +0000146 self.assertTrue(tid in threading._active)
147 self.assertTrue(isinstance(threading._active[tid],
Tim Peters711906e2005-01-08 07:30:42 +0000148 threading._DummyThread))
149 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000150
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000151 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
152 # exposed at the Python level. This test relies on ctypes to get at it.
153 def test_PyThreadState_SetAsyncExc(self):
154 try:
155 import ctypes
156 except ImportError:
157 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000158 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000159 return # can't do anything
160
161 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
162
163 class AsyncExc(Exception):
164 pass
165
166 exception = ctypes.py_object(AsyncExc)
167
168 # `worker_started` is set by the thread when it's inside a try/except
169 # block waiting to catch the asynchronously set AsyncExc exception.
170 # `worker_saw_exception` is set by the thread upon catching that
171 # exception.
172 worker_started = threading.Event()
173 worker_saw_exception = threading.Event()
174
175 class Worker(threading.Thread):
176 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000177 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178 self.finished = False
179
180 try:
181 while True:
182 worker_started.set()
183 time.sleep(0.1)
184 except AsyncExc:
185 self.finished = True
186 worker_saw_exception.set()
187
188 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000189 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190 t.start()
191 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000192 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193
194 # Try a thread id that doesn't make sense.
195 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000196 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 result = set_async_exc(ctypes.c_long(-1), exception)
198 self.assertEqual(result, 0) # no thread states modified
199
200 # Now raise an exception in the worker thread.
201 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000202 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000203 ret = worker_started.wait()
204 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000205 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000206 print(" verifying worker hasn't exited")
Georg Brandlab91fde2009-08-13 08:51:18 +0000207 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000208 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000209 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000210 result = set_async_exc(ctypes.c_long(t.id), exception)
211 self.assertEqual(result, 1) # one thread state modified
212 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000213 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000214 worker_saw_exception.wait(timeout=10)
Georg Brandlab91fde2009-08-13 08:51:18 +0000215 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000216 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000217 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 if t.finished:
219 t.join()
220 # else the thread is still running, and we have no way to kill it
221
Christian Heimes7d2ff882007-11-30 14:35:04 +0000222 def test_finalize_runnning_thread(self):
223 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
224 # very late on python exit: on deallocation of a running thread for
225 # example.
226 try:
227 import ctypes
228 except ImportError:
229 if verbose:
230 print("test_finalize_with_runnning_thread can't import ctypes")
231 return # can't do anything
232
233 import subprocess
234 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000235 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000236
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000237 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000238 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000239 ready.acquire()
240
Christian Heimes7d2ff882007-11-30 14:35:04 +0000241 # Module globals are cleared before __del__ is run
242 # So we save the functions in class dict
243 class C:
244 ensure = ctypes.pythonapi.PyGILState_Ensure
245 release = ctypes.pythonapi.PyGILState_Release
246 def __del__(self):
247 state = self.ensure()
248 self.release(state)
249
250 def waitingThread():
251 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000252 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000253 time.sleep(100)
254
Georg Brandl2067bfd2008-05-25 13:05:15 +0000255 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000256 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000257 sys.exit(42)
258 """])
259 self.assertEqual(rc, 42)
260
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000261 def test_finalize_with_trace(self):
262 # Issue1733757
263 # Avoid a deadlock when sys.settrace steps into threading._shutdown
264 import subprocess
265 rc = subprocess.call([sys.executable, "-c", """if 1:
266 import sys, threading
267
268 # A deadlock-killer, to prevent the
269 # testsuite to hang forever
270 def killer():
271 import os, time
272 time.sleep(2)
273 print('program blocked; aborting')
274 os._exit(2)
275 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000276 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000277 t.start()
278
279 # This is the trace function
280 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000281 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000282 return func
283
284 sys.settrace(func)
285 """])
Georg Brandlab91fde2009-08-13 08:51:18 +0000286 self.assertFalse(rc == 2, "interpreted was blocked")
287 self.assertTrue(rc == 0, "Unexpected error")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000288
Antoine Pitroucefb3162009-10-20 22:08:36 +0000289 def test_join_nondaemon_on_shutdown(self):
290 # Issue 1722344
291 # Raising SystemExit skipped threading._shutdown
292 import subprocess
293 p = subprocess.Popen([sys.executable, "-c", """if 1:
294 import threading
295 from time import sleep
296
297 def child():
298 sleep(1)
299 # As a non-daemon thread we SHOULD wake up and nothing
300 # should be torn down yet
301 print("Woke up, sleep function is:", sleep)
302
303 threading.Thread(target=child).start()
304 raise SystemExit
305 """],
306 stdout=subprocess.PIPE,
307 stderr=subprocess.PIPE)
308 stdout, stderr = p.communicate()
Antoine Pitrouf6779fb2009-10-23 22:06:37 +0000309 self.assertEqual(stdout.strip(),
310 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitroucefb3162009-10-20 22:08:36 +0000311 stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
312 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000313
Christian Heimes1af737c2008-01-23 08:24:23 +0000314 def test_enumerate_after_join(self):
315 # Try hard to trigger #1703448: a thread is still returned in
316 # threading.enumerate() after it has been join()ed.
317 enum = threading.enumerate
318 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000319 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000320 for i in range(1, 100):
321 # Try a couple times at each thread-switching interval
322 # to get more interleavings.
323 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000324 t = threading.Thread(target=lambda: None)
325 t.start()
326 t.join()
327 l = enum()
328 self.assertFalse(t in l,
329 "#1703448 triggered after %d trials: %s" % (i, l))
330 finally:
331 sys.setcheckinterval(old_interval)
332
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000333 def test_no_refcycle_through_target(self):
334 class RunSelfFunction(object):
335 def __init__(self, should_raise):
336 # The links in this refcycle from Thread back to self
337 # should be cleaned up when the thread completes.
338 self.should_raise = should_raise
339 self.thread = threading.Thread(target=self._run,
340 args=(self,),
341 kwargs={'yet_another':self})
342 self.thread.start()
343
344 def _run(self, other_ref, yet_another):
345 if self.should_raise:
346 raise SystemExit
347
348 cyclic_object = RunSelfFunction(should_raise=False)
349 weak_cyclic_object = weakref.ref(cyclic_object)
350 cyclic_object.thread.join()
351 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000352 self.assertEquals(None, weak_cyclic_object(),
353 msg=('%d references still around' %
354 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000355
356 raising_cyclic_object = RunSelfFunction(should_raise=True)
357 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
358 raising_cyclic_object.thread.join()
359 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000360 self.assertEquals(None, weak_raising_cyclic_object(),
361 msg=('%d references still around' %
362 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000363
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000364 def test_old_threading_api(self):
365 # Just a quick sanity check to make sure the old method names are
366 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000367 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000368 t.isDaemon()
369 t.setDaemon(True)
370 t.getName()
371 t.setName("name")
372 t.isAlive()
373 e = threading.Event()
374 e.isSet()
375 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000376
Christian Heimes1af737c2008-01-23 08:24:23 +0000377
Jesse Nollera8513972008-07-17 16:49:17 +0000378class ThreadJoinOnShutdown(unittest.TestCase):
379
380 def _run_and_join(self, script):
381 script = """if 1:
382 import sys, os, time, threading
383
384 # a thread, which waits for the main program to terminate
385 def joiningfunc(mainthread):
386 mainthread.join()
387 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000388 # stdout is fully buffered because not a tty, we have to flush
389 # before exit.
390 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000391 \n""" + script
392
393 import subprocess
394 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
395 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000396 data = p.stdout.read().decode().replace('\r', '')
397 self.assertEqual(data, "end of main\nend of thread\n")
Georg Brandlab91fde2009-08-13 08:51:18 +0000398 self.assertFalse(rc == 2, "interpreter was blocked")
399 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000400
401 def test_1_join_on_shutdown(self):
402 # The usual case: on exit, wait for a non-daemon thread
403 script = """if 1:
404 import os
405 t = threading.Thread(target=joiningfunc,
406 args=(threading.current_thread(),))
407 t.start()
408 time.sleep(0.1)
409 print('end of main')
410 """
411 self._run_and_join(script)
412
413
414 def test_2_join_in_forked_process(self):
415 # Like the test above, but from a forked interpreter
416 import os
417 if not hasattr(os, 'fork'):
418 return
419 script = """if 1:
420 childpid = os.fork()
421 if childpid != 0:
422 os.waitpid(childpid, 0)
423 sys.exit(0)
424
425 t = threading.Thread(target=joiningfunc,
426 args=(threading.current_thread(),))
427 t.start()
428 print('end of main')
429 """
430 self._run_and_join(script)
431
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000432 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000433 # Like the test above, but fork() was called from a worker thread
434 # In the forked process, the main Thread object must be marked as stopped.
435 import os
436 if not hasattr(os, 'fork'):
437 return
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000438 # Skip platforms with known problems forking from a worker thread.
439 # See http://bugs.python.org/issue3863.
440 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
R. David Murray9948da02009-10-26 03:27:32 +0000441 print('Skipping test_3_join_in_forked_from_thread'
442 ' due to known OS bugs on', sys.platform, file=sys.stderr)
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000443 return
Jesse Nollera8513972008-07-17 16:49:17 +0000444 script = """if 1:
445 main_thread = threading.current_thread()
446 def worker():
447 childpid = os.fork()
448 if childpid != 0:
449 os.waitpid(childpid, 0)
450 sys.exit(0)
451
452 t = threading.Thread(target=joiningfunc,
453 args=(main_thread,))
454 print('end of main')
455 t.start()
456 t.join() # Should not block: main_thread is already stopped
457
458 w = threading.Thread(target=worker)
459 w.start()
460 """
461 self._run_and_join(script)
462
463
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000464class ThreadingExceptionTests(unittest.TestCase):
465 # A RuntimeError should be raised if Thread.start() is called
466 # multiple times.
467 def test_start_thread_again(self):
468 thread = threading.Thread()
469 thread.start()
470 self.assertRaises(RuntimeError, thread.start)
471
472 def test_releasing_unacquired_rlock(self):
473 rlock = threading.RLock()
474 self.assertRaises(RuntimeError, rlock.release)
475
476 def test_waiting_on_unacquired_condition(self):
477 cond = threading.Condition()
478 self.assertRaises(RuntimeError, cond.wait)
479
480 def test_notify_on_unacquired_condition(self):
481 cond = threading.Condition()
482 self.assertRaises(RuntimeError, cond.notify)
483
484 def test_semaphore_with_negative_value(self):
485 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000486 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000487
488 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000489 current_thread = threading.current_thread()
490 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000491
492 def test_joining_inactive_thread(self):
493 thread = threading.Thread()
494 self.assertRaises(RuntimeError, thread.join)
495
496 def test_daemonize_active_thread(self):
497 thread = threading.Thread()
498 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000499 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000500
501
Tim Peters84d54892005-01-08 06:03:17 +0000502def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000503 test.support.run_unittest(ThreadTests,
Jesse Nollera8513972008-07-17 16:49:17 +0000504 ThreadJoinOnShutdown,
505 ThreadingExceptionTests,
506 )
Tim Peters84d54892005-01-08 06:03:17 +0000507
508if __name__ == "__main__":
509 test_main()