blob: 7b6d82bb11685bc1059b8f151a788a056ffd2839 [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)
Antoine Pitroudebfafd2009-11-08 00:36:36 +0000104 # Kill the "immortal" _DummyThread
105 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000106
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107 # run with a small(ish) thread stack size (256kB)
108 def test_various_ops_small_stack(self):
109 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111 try:
112 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000113 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000115 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000116 return
117 self.test_various_ops()
118 threading.stack_size(0)
119
120 # run with a large thread stack size (1MB)
121 def test_various_ops_large_stack(self):
122 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124 try:
125 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000126 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000128 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000129 return
130 self.test_various_ops()
131 threading.stack_size(0)
132
Tim Peters711906e2005-01-08 07:30:42 +0000133 def test_foreign_thread(self):
134 # Check that a "foreign" thread can use the threading module.
135 def f(mutex):
136 # Acquiring an RLock forces an entry for the foreign
137 # thread to get made in the threading._active map.
138 r = threading.RLock()
139 r.acquire()
140 r.release()
141 mutex.release()
142
143 mutex = threading.Lock()
144 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000145 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000146 # Wait for the thread to finish.
147 mutex.acquire()
Georg Brandlab91fde2009-08-13 08:51:18 +0000148 self.assertTrue(tid in threading._active)
149 self.assertTrue(isinstance(threading._active[tid],
Tim Peters711906e2005-01-08 07:30:42 +0000150 threading._DummyThread))
151 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000152
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000153 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
154 # exposed at the Python level. This test relies on ctypes to get at it.
155 def test_PyThreadState_SetAsyncExc(self):
156 try:
157 import ctypes
158 except ImportError:
159 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000160 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161 return # can't do anything
162
163 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
164
165 class AsyncExc(Exception):
166 pass
167
168 exception = ctypes.py_object(AsyncExc)
169
170 # `worker_started` is set by the thread when it's inside a try/except
171 # block waiting to catch the asynchronously set AsyncExc exception.
172 # `worker_saw_exception` is set by the thread upon catching that
173 # exception.
174 worker_started = threading.Event()
175 worker_saw_exception = threading.Event()
176
177 class Worker(threading.Thread):
178 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000179 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180 self.finished = False
181
182 try:
183 while True:
184 worker_started.set()
185 time.sleep(0.1)
186 except AsyncExc:
187 self.finished = True
188 worker_saw_exception.set()
189
190 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000191 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000192 t.start()
193 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000194 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000195
196 # Try a thread id that doesn't make sense.
197 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000198 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000199 result = set_async_exc(ctypes.c_long(-1), exception)
200 self.assertEqual(result, 0) # no thread states modified
201
202 # Now raise an exception in the worker thread.
203 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000204 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000205 ret = worker_started.wait()
206 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print(" verifying worker hasn't exited")
Georg Brandlab91fde2009-08-13 08:51:18 +0000209 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000210 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000211 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000212 result = set_async_exc(ctypes.c_long(t.id), exception)
213 self.assertEqual(result, 1) # one thread state modified
214 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000215 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000216 worker_saw_exception.wait(timeout=10)
Georg Brandlab91fde2009-08-13 08:51:18 +0000217 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000220 if t.finished:
221 t.join()
222 # else the thread is still running, and we have no way to kill it
223
Christian Heimes7d2ff882007-11-30 14:35:04 +0000224 def test_finalize_runnning_thread(self):
225 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
226 # very late on python exit: on deallocation of a running thread for
227 # example.
228 try:
229 import ctypes
230 except ImportError:
231 if verbose:
232 print("test_finalize_with_runnning_thread can't import ctypes")
233 return # can't do anything
234
235 import subprocess
236 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000237 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000238
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000239 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000240 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000241 ready.acquire()
242
Christian Heimes7d2ff882007-11-30 14:35:04 +0000243 # Module globals are cleared before __del__ is run
244 # So we save the functions in class dict
245 class C:
246 ensure = ctypes.pythonapi.PyGILState_Ensure
247 release = ctypes.pythonapi.PyGILState_Release
248 def __del__(self):
249 state = self.ensure()
250 self.release(state)
251
252 def waitingThread():
253 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000254 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000255 time.sleep(100)
256
Georg Brandl2067bfd2008-05-25 13:05:15 +0000257 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000258 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000259 sys.exit(42)
260 """])
261 self.assertEqual(rc, 42)
262
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000263 def test_finalize_with_trace(self):
264 # Issue1733757
265 # Avoid a deadlock when sys.settrace steps into threading._shutdown
266 import subprocess
267 rc = subprocess.call([sys.executable, "-c", """if 1:
268 import sys, threading
269
270 # A deadlock-killer, to prevent the
271 # testsuite to hang forever
272 def killer():
273 import os, time
274 time.sleep(2)
275 print('program blocked; aborting')
276 os._exit(2)
277 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000278 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000279 t.start()
280
281 # This is the trace function
282 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000283 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000284 return func
285
286 sys.settrace(func)
287 """])
Georg Brandlab91fde2009-08-13 08:51:18 +0000288 self.assertFalse(rc == 2, "interpreted was blocked")
289 self.assertTrue(rc == 0, "Unexpected error")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000290
Antoine Pitroucefb3162009-10-20 22:08:36 +0000291 def test_join_nondaemon_on_shutdown(self):
292 # Issue 1722344
293 # Raising SystemExit skipped threading._shutdown
294 import subprocess
295 p = subprocess.Popen([sys.executable, "-c", """if 1:
296 import threading
297 from time import sleep
298
299 def child():
300 sleep(1)
301 # As a non-daemon thread we SHOULD wake up and nothing
302 # should be torn down yet
303 print("Woke up, sleep function is:", sleep)
304
305 threading.Thread(target=child).start()
306 raise SystemExit
307 """],
308 stdout=subprocess.PIPE,
309 stderr=subprocess.PIPE)
310 stdout, stderr = p.communicate()
Antoine Pitrouf6779fb2009-10-23 22:06:37 +0000311 self.assertEqual(stdout.strip(),
312 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitroucefb3162009-10-20 22:08:36 +0000313 stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
314 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000315
Christian Heimes1af737c2008-01-23 08:24:23 +0000316 def test_enumerate_after_join(self):
317 # Try hard to trigger #1703448: a thread is still returned in
318 # threading.enumerate() after it has been join()ed.
319 enum = threading.enumerate
320 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000321 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000322 for i in range(1, 100):
323 # Try a couple times at each thread-switching interval
324 # to get more interleavings.
325 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000326 t = threading.Thread(target=lambda: None)
327 t.start()
328 t.join()
329 l = enum()
330 self.assertFalse(t in l,
331 "#1703448 triggered after %d trials: %s" % (i, l))
332 finally:
333 sys.setcheckinterval(old_interval)
334
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000335 def test_no_refcycle_through_target(self):
336 class RunSelfFunction(object):
337 def __init__(self, should_raise):
338 # The links in this refcycle from Thread back to self
339 # should be cleaned up when the thread completes.
340 self.should_raise = should_raise
341 self.thread = threading.Thread(target=self._run,
342 args=(self,),
343 kwargs={'yet_another':self})
344 self.thread.start()
345
346 def _run(self, other_ref, yet_another):
347 if self.should_raise:
348 raise SystemExit
349
350 cyclic_object = RunSelfFunction(should_raise=False)
351 weak_cyclic_object = weakref.ref(cyclic_object)
352 cyclic_object.thread.join()
353 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000354 self.assertEquals(None, weak_cyclic_object(),
355 msg=('%d references still around' %
356 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000357
358 raising_cyclic_object = RunSelfFunction(should_raise=True)
359 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
360 raising_cyclic_object.thread.join()
361 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000362 self.assertEquals(None, weak_raising_cyclic_object(),
363 msg=('%d references still around' %
364 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000365
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000366 def test_old_threading_api(self):
367 # Just a quick sanity check to make sure the old method names are
368 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000369 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000370 t.isDaemon()
371 t.setDaemon(True)
372 t.getName()
373 t.setName("name")
374 t.isAlive()
375 e = threading.Event()
376 e.isSet()
377 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000378
Christian Heimes1af737c2008-01-23 08:24:23 +0000379
Jesse Nollera8513972008-07-17 16:49:17 +0000380class ThreadJoinOnShutdown(unittest.TestCase):
381
382 def _run_and_join(self, script):
383 script = """if 1:
384 import sys, os, time, threading
385
386 # a thread, which waits for the main program to terminate
387 def joiningfunc(mainthread):
388 mainthread.join()
389 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000390 # stdout is fully buffered because not a tty, we have to flush
391 # before exit.
392 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000393 \n""" + script
394
395 import subprocess
396 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
397 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000398 data = p.stdout.read().decode().replace('\r', '')
399 self.assertEqual(data, "end of main\nend of thread\n")
Georg Brandlab91fde2009-08-13 08:51:18 +0000400 self.assertFalse(rc == 2, "interpreter was blocked")
401 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000402
403 def test_1_join_on_shutdown(self):
404 # The usual case: on exit, wait for a non-daemon thread
405 script = """if 1:
406 import os
407 t = threading.Thread(target=joiningfunc,
408 args=(threading.current_thread(),))
409 t.start()
410 time.sleep(0.1)
411 print('end of main')
412 """
413 self._run_and_join(script)
414
415
416 def test_2_join_in_forked_process(self):
417 # Like the test above, but from a forked interpreter
418 import os
419 if not hasattr(os, 'fork'):
420 return
421 script = """if 1:
422 childpid = os.fork()
423 if childpid != 0:
424 os.waitpid(childpid, 0)
425 sys.exit(0)
426
427 t = threading.Thread(target=joiningfunc,
428 args=(threading.current_thread(),))
429 t.start()
430 print('end of main')
431 """
432 self._run_and_join(script)
433
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000434 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000435 # Like the test above, but fork() was called from a worker thread
436 # In the forked process, the main Thread object must be marked as stopped.
437 import os
438 if not hasattr(os, 'fork'):
439 return
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000440 # Skip platforms with known problems forking from a worker thread.
441 # See http://bugs.python.org/issue3863.
442 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
R. David Murray9948da02009-10-26 03:27:32 +0000443 print('Skipping test_3_join_in_forked_from_thread'
444 ' due to known OS bugs on', sys.platform, file=sys.stderr)
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000445 return
Jesse Nollera8513972008-07-17 16:49:17 +0000446 script = """if 1:
447 main_thread = threading.current_thread()
448 def worker():
449 childpid = os.fork()
450 if childpid != 0:
451 os.waitpid(childpid, 0)
452 sys.exit(0)
453
454 t = threading.Thread(target=joiningfunc,
455 args=(main_thread,))
456 print('end of main')
457 t.start()
458 t.join() # Should not block: main_thread is already stopped
459
460 w = threading.Thread(target=worker)
461 w.start()
462 """
463 self._run_and_join(script)
464
465
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000466class ThreadingExceptionTests(unittest.TestCase):
467 # A RuntimeError should be raised if Thread.start() is called
468 # multiple times.
469 def test_start_thread_again(self):
470 thread = threading.Thread()
471 thread.start()
472 self.assertRaises(RuntimeError, thread.start)
473
474 def test_releasing_unacquired_rlock(self):
475 rlock = threading.RLock()
476 self.assertRaises(RuntimeError, rlock.release)
477
478 def test_waiting_on_unacquired_condition(self):
479 cond = threading.Condition()
480 self.assertRaises(RuntimeError, cond.wait)
481
482 def test_notify_on_unacquired_condition(self):
483 cond = threading.Condition()
484 self.assertRaises(RuntimeError, cond.notify)
485
486 def test_semaphore_with_negative_value(self):
487 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000488 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000489
490 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000491 current_thread = threading.current_thread()
492 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000493
494 def test_joining_inactive_thread(self):
495 thread = threading.Thread()
496 self.assertRaises(RuntimeError, thread.join)
497
498 def test_daemonize_active_thread(self):
499 thread = threading.Thread()
500 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000501 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000502
503
Tim Peters84d54892005-01-08 06:03:17 +0000504def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000505 test.support.run_unittest(ThreadTests,
Jesse Nollera8513972008-07-17 16:49:17 +0000506 ThreadJoinOnShutdown,
507 ThreadingExceptionTests,
508 )
Tim Peters84d54892005-01-08 06:03:17 +0000509
510if __name__ == "__main__":
511 test_main()