Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 1 | # Very rudimentary test of threading module |
| 2 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 3 | import test.test_support |
Barry Warsaw | 04f357c | 2002-07-23 19:04:11 +0000 | [diff] [blame] | 4 | from test.test_support import verbose |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 5 | import random |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 6 | import sys |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 7 | import threading |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 8 | import thread |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 9 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 10 | import unittest |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 11 | import weakref |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 12 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 13 | # A trivial mutable counter. |
| 14 | class Counter(object): |
| 15 | def __init__(self): |
| 16 | self.value = 0 |
| 17 | def inc(self): |
| 18 | self.value += 1 |
| 19 | def dec(self): |
| 20 | self.value -= 1 |
| 21 | def get(self): |
| 22 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 23 | |
| 24 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 25 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 26 | threading.Thread.__init__(self, name=name) |
| 27 | self.testcase = testcase |
| 28 | self.sema = sema |
| 29 | self.mutex = mutex |
| 30 | self.nrunning = nrunning |
| 31 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 32 | def run(self): |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 33 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 34 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 35 | print('task', self.getName(), 'will run for', delay, 'sec') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 36 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 37 | with self.sema: |
| 38 | with self.mutex: |
| 39 | self.nrunning.inc() |
| 40 | if verbose: |
| 41 | print(self.nrunning.get(), 'tasks are running') |
| 42 | self.testcase.assert_(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 43 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 44 | time.sleep(delay) |
| 45 | if verbose: |
| 46 | print('task', self.getName(), 'done') |
| 47 | with self.mutex: |
| 48 | self.nrunning.dec() |
| 49 | self.testcase.assert_(self.nrunning.get() >= 0) |
| 50 | if verbose: |
| 51 | print('%s is finished. %d tasks are running' % |
| 52 | self.getName(), self.nrunning.get()) |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 53 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 54 | class ThreadTests(unittest.TestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 55 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 56 | # Create a bunch of threads, let each do some work, wait until all are |
| 57 | # done. |
| 58 | def test_various_ops(self): |
| 59 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 60 | # times about 1 second per clump). |
| 61 | NUMTASKS = 10 |
| 62 | |
| 63 | # no more than 3 of the 10 can run at once |
| 64 | sema = threading.BoundedSemaphore(value=3) |
| 65 | mutex = threading.RLock() |
| 66 | numrunning = Counter() |
| 67 | |
| 68 | threads = [] |
| 69 | |
| 70 | for i in range(NUMTASKS): |
| 71 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 72 | threads.append(t) |
| 73 | t.start() |
| 74 | |
| 75 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 76 | print('waiting for all tasks to complete') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 77 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 78 | t.join(NUMTASKS) |
| 79 | self.assert_(not t.isAlive()) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 80 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 81 | print('all tasks done') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 82 | self.assertEqual(numrunning.get(), 0) |
| 83 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 84 | # run with a small(ish) thread stack size (256kB) |
| 85 | def test_various_ops_small_stack(self): |
| 86 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 87 | print('with 256kB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 88 | try: |
| 89 | threading.stack_size(262144) |
| 90 | except thread.error: |
| 91 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 92 | print('platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 93 | return |
| 94 | self.test_various_ops() |
| 95 | threading.stack_size(0) |
| 96 | |
| 97 | # run with a large thread stack size (1MB) |
| 98 | def test_various_ops_large_stack(self): |
| 99 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 100 | print('with 1MB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 101 | try: |
| 102 | threading.stack_size(0x100000) |
| 103 | except thread.error: |
| 104 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 105 | print('platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 106 | return |
| 107 | self.test_various_ops() |
| 108 | threading.stack_size(0) |
| 109 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 110 | def test_foreign_thread(self): |
| 111 | # Check that a "foreign" thread can use the threading module. |
| 112 | def f(mutex): |
| 113 | # Acquiring an RLock forces an entry for the foreign |
| 114 | # thread to get made in the threading._active map. |
| 115 | r = threading.RLock() |
| 116 | r.acquire() |
| 117 | r.release() |
| 118 | mutex.release() |
| 119 | |
| 120 | mutex = threading.Lock() |
| 121 | mutex.acquire() |
| 122 | tid = thread.start_new_thread(f, (mutex,)) |
| 123 | # Wait for the thread to finish. |
| 124 | mutex.acquire() |
| 125 | self.assert_(tid in threading._active) |
| 126 | self.assert_(isinstance(threading._active[tid], |
| 127 | threading._DummyThread)) |
| 128 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 129 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 130 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 131 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 132 | def test_PyThreadState_SetAsyncExc(self): |
| 133 | try: |
| 134 | import ctypes |
| 135 | except ImportError: |
| 136 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 137 | print("test_PyThreadState_SetAsyncExc can't import ctypes") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 138 | return # can't do anything |
| 139 | |
| 140 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 141 | |
| 142 | class AsyncExc(Exception): |
| 143 | pass |
| 144 | |
| 145 | exception = ctypes.py_object(AsyncExc) |
| 146 | |
| 147 | # `worker_started` is set by the thread when it's inside a try/except |
| 148 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 149 | # `worker_saw_exception` is set by the thread upon catching that |
| 150 | # exception. |
| 151 | worker_started = threading.Event() |
| 152 | worker_saw_exception = threading.Event() |
| 153 | |
| 154 | class Worker(threading.Thread): |
| 155 | def run(self): |
| 156 | self.id = thread.get_ident() |
| 157 | self.finished = False |
| 158 | |
| 159 | try: |
| 160 | while True: |
| 161 | worker_started.set() |
| 162 | time.sleep(0.1) |
| 163 | except AsyncExc: |
| 164 | self.finished = True |
| 165 | worker_saw_exception.set() |
| 166 | |
| 167 | t = Worker() |
| 168 | t.setDaemon(True) # so if this fails, we don't hang Python at shutdown |
| 169 | t.start() |
| 170 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 171 | print(" started worker thread") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 172 | |
| 173 | # Try a thread id that doesn't make sense. |
| 174 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 175 | print(" trying nonsensical thread id") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 176 | result = set_async_exc(ctypes.c_long(-1), exception) |
| 177 | self.assertEqual(result, 0) # no thread states modified |
| 178 | |
| 179 | # Now raise an exception in the worker thread. |
| 180 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 181 | print(" waiting for worker thread to get started") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 182 | worker_started.wait() |
| 183 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 184 | print(" verifying worker hasn't exited") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 185 | self.assert_(not t.finished) |
| 186 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 187 | print(" attempting to raise asynch exception in worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 188 | result = set_async_exc(ctypes.c_long(t.id), exception) |
| 189 | self.assertEqual(result, 1) # one thread state modified |
| 190 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 191 | print(" waiting for worker to say it caught the exception") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 192 | worker_saw_exception.wait(timeout=10) |
| 193 | self.assert_(t.finished) |
| 194 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 195 | print(" all OK -- joining worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 196 | if t.finished: |
| 197 | t.join() |
| 198 | # else the thread is still running, and we have no way to kill it |
| 199 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 200 | def test_finalize_runnning_thread(self): |
| 201 | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
| 202 | # very late on python exit: on deallocation of a running thread for |
| 203 | # example. |
| 204 | try: |
| 205 | import ctypes |
| 206 | except ImportError: |
| 207 | if verbose: |
| 208 | print("test_finalize_with_runnning_thread can't import ctypes") |
| 209 | return # can't do anything |
| 210 | |
| 211 | import subprocess |
| 212 | rc = subprocess.call([sys.executable, "-c", """if 1: |
| 213 | import ctypes, sys, time, thread |
| 214 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 215 | # This lock is used as a simple event variable. |
| 216 | ready = thread.allocate_lock() |
| 217 | ready.acquire() |
| 218 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 219 | # Module globals are cleared before __del__ is run |
| 220 | # So we save the functions in class dict |
| 221 | class C: |
| 222 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 223 | release = ctypes.pythonapi.PyGILState_Release |
| 224 | def __del__(self): |
| 225 | state = self.ensure() |
| 226 | self.release(state) |
| 227 | |
| 228 | def waitingThread(): |
| 229 | x = C() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 230 | ready.release() |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 231 | time.sleep(100) |
| 232 | |
| 233 | thread.start_new_thread(waitingThread, ()) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 234 | ready.acquire() # Be sure the other thread is waiting. |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 235 | sys.exit(42) |
| 236 | """]) |
| 237 | self.assertEqual(rc, 42) |
| 238 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 239 | def test_enumerate_after_join(self): |
| 240 | # Try hard to trigger #1703448: a thread is still returned in |
| 241 | # threading.enumerate() after it has been join()ed. |
| 242 | enum = threading.enumerate |
| 243 | old_interval = sys.getcheckinterval() |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 244 | try: |
| 245 | for i in range(1, 1000): |
| 246 | t = threading.Thread(target=lambda: None) |
| 247 | t.start() |
| 248 | t.join() |
| 249 | l = enum() |
| 250 | self.assertFalse(t in l, |
| 251 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 252 | finally: |
| 253 | sys.setcheckinterval(old_interval) |
| 254 | |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 255 | def test_no_refcycle_through_target(self): |
| 256 | class RunSelfFunction(object): |
| 257 | def __init__(self, should_raise): |
| 258 | # The links in this refcycle from Thread back to self |
| 259 | # should be cleaned up when the thread completes. |
| 260 | self.should_raise = should_raise |
| 261 | self.thread = threading.Thread(target=self._run, |
| 262 | args=(self,), |
| 263 | kwargs={'yet_another':self}) |
| 264 | self.thread.start() |
| 265 | |
| 266 | def _run(self, other_ref, yet_another): |
| 267 | if self.should_raise: |
| 268 | raise SystemExit |
| 269 | |
| 270 | cyclic_object = RunSelfFunction(should_raise=False) |
| 271 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 272 | cyclic_object.thread.join() |
| 273 | del cyclic_object |
| 274 | self.assertEquals(None, weak_cyclic_object()) |
| 275 | |
| 276 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 277 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 278 | raising_cyclic_object.thread.join() |
| 279 | del raising_cyclic_object |
| 280 | self.assertEquals(None, weak_raising_cyclic_object()) |
| 281 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 282 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 283 | class ThreadingExceptionTests(unittest.TestCase): |
| 284 | # A RuntimeError should be raised if Thread.start() is called |
| 285 | # multiple times. |
| 286 | def test_start_thread_again(self): |
| 287 | thread = threading.Thread() |
| 288 | thread.start() |
| 289 | self.assertRaises(RuntimeError, thread.start) |
| 290 | |
| 291 | def test_releasing_unacquired_rlock(self): |
| 292 | rlock = threading.RLock() |
| 293 | self.assertRaises(RuntimeError, rlock.release) |
| 294 | |
| 295 | def test_waiting_on_unacquired_condition(self): |
| 296 | cond = threading.Condition() |
| 297 | self.assertRaises(RuntimeError, cond.wait) |
| 298 | |
| 299 | def test_notify_on_unacquired_condition(self): |
| 300 | cond = threading.Condition() |
| 301 | self.assertRaises(RuntimeError, cond.notify) |
| 302 | |
| 303 | def test_semaphore_with_negative_value(self): |
| 304 | self.assertRaises(ValueError, threading.Semaphore, value = -1) |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 305 | self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 306 | |
| 307 | def test_joining_current_thread(self): |
| 308 | currentThread = threading.currentThread() |
| 309 | self.assertRaises(RuntimeError, currentThread.join); |
| 310 | |
| 311 | def test_joining_inactive_thread(self): |
| 312 | thread = threading.Thread() |
| 313 | self.assertRaises(RuntimeError, thread.join) |
| 314 | |
| 315 | def test_daemonize_active_thread(self): |
| 316 | thread = threading.Thread() |
| 317 | thread.start() |
| 318 | self.assertRaises(RuntimeError, thread.setDaemon, True) |
| 319 | |
| 320 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 321 | def test_main(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 322 | test.test_support.run_unittest(ThreadTests, |
| 323 | ThreadingExceptionTests) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 324 | |
| 325 | if __name__ == "__main__": |
| 326 | test_main() |