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