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