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 |
Gregory P. Smith | 8f034d9 | 2008-01-22 01:29:11 +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 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 11 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 12 | # A trivial mutable counter. |
| 13 | class Counter(object): |
| 14 | def __init__(self): |
| 15 | self.value = 0 |
| 16 | def inc(self): |
| 17 | self.value += 1 |
| 18 | def dec(self): |
| 19 | self.value -= 1 |
| 20 | def get(self): |
| 21 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 22 | |
| 23 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 24 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 25 | threading.Thread.__init__(self, name=name) |
| 26 | self.testcase = testcase |
| 27 | self.sema = sema |
| 28 | self.mutex = mutex |
| 29 | self.nrunning = nrunning |
| 30 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 31 | def run(self): |
Tim Peters | 02035bc | 2001-08-20 21:45:19 +0000 | [diff] [blame] | 32 | delay = random.random() * 2 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 33 | if verbose: |
Tim Peters | 02035bc | 2001-08-20 21:45:19 +0000 | [diff] [blame] | 34 | print 'task', self.getName(), 'will run for', delay, 'sec' |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 35 | |
| 36 | self.sema.acquire() |
| 37 | |
| 38 | self.mutex.acquire() |
| 39 | self.nrunning.inc() |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 40 | if verbose: |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 41 | print self.nrunning.get(), 'tasks are running' |
| 42 | self.testcase.assert_(self.nrunning.get() <= 3) |
| 43 | self.mutex.release() |
| 44 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +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 | |
| 49 | self.mutex.acquire() |
| 50 | self.nrunning.dec() |
| 51 | self.testcase.assert_(self.nrunning.get() >= 0) |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 52 | if verbose: |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 53 | print self.getName(), 'is finished.', self.nrunning.get(), \ |
| 54 | 'tasks are running' |
| 55 | self.mutex.release() |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 56 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 57 | self.sema.release() |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 58 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 59 | class ThreadTests(unittest.TestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 60 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 61 | # Create a bunch of threads, let each do some work, wait until all are |
| 62 | # done. |
| 63 | def test_various_ops(self): |
| 64 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 65 | # times about 1 second per clump). |
| 66 | NUMTASKS = 10 |
| 67 | |
| 68 | # no more than 3 of the 10 can run at once |
| 69 | sema = threading.BoundedSemaphore(value=3) |
| 70 | mutex = threading.RLock() |
| 71 | numrunning = Counter() |
| 72 | |
| 73 | threads = [] |
| 74 | |
| 75 | for i in range(NUMTASKS): |
| 76 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 77 | threads.append(t) |
| 78 | t.start() |
| 79 | |
| 80 | if verbose: |
| 81 | print 'waiting for all tasks to complete' |
| 82 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 83 | t.join(NUMTASKS) |
| 84 | self.assert_(not t.isAlive()) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 85 | if verbose: |
| 86 | print 'all tasks done' |
| 87 | self.assertEqual(numrunning.get(), 0) |
| 88 | |
Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 89 | # run with a small(ish) thread stack size (256kB) |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 90 | def test_various_ops_small_stack(self): |
| 91 | if verbose: |
Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 92 | print 'with 256kB thread stack size...' |
Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 93 | try: |
| 94 | threading.stack_size(262144) |
| 95 | except thread.error: |
| 96 | if verbose: |
| 97 | print 'platform does not support changing thread stack size' |
| 98 | return |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 99 | self.test_various_ops() |
| 100 | threading.stack_size(0) |
| 101 | |
| 102 | # run with a large thread stack size (1MB) |
| 103 | def test_various_ops_large_stack(self): |
| 104 | if verbose: |
| 105 | print 'with 1MB thread stack size...' |
Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 106 | try: |
| 107 | threading.stack_size(0x100000) |
| 108 | except thread.error: |
| 109 | if verbose: |
| 110 | print 'platform does not support changing thread stack size' |
| 111 | return |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 112 | self.test_various_ops() |
| 113 | threading.stack_size(0) |
| 114 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 115 | def test_foreign_thread(self): |
| 116 | # Check that a "foreign" thread can use the threading module. |
| 117 | def f(mutex): |
| 118 | # Acquiring an RLock forces an entry for the foreign |
| 119 | # thread to get made in the threading._active map. |
| 120 | r = threading.RLock() |
| 121 | r.acquire() |
| 122 | r.release() |
| 123 | mutex.release() |
| 124 | |
| 125 | mutex = threading.Lock() |
| 126 | mutex.acquire() |
| 127 | tid = thread.start_new_thread(f, (mutex,)) |
| 128 | # Wait for the thread to finish. |
| 129 | mutex.acquire() |
| 130 | self.assert_(tid in threading._active) |
| 131 | self.assert_(isinstance(threading._active[tid], |
| 132 | threading._DummyThread)) |
| 133 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 134 | |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 135 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 136 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 137 | def test_PyThreadState_SetAsyncExc(self): |
| 138 | try: |
| 139 | import ctypes |
| 140 | except ImportError: |
| 141 | if verbose: |
| 142 | print "test_PyThreadState_SetAsyncExc can't import ctypes" |
| 143 | return # can't do anything |
| 144 | |
| 145 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 146 | |
| 147 | class AsyncExc(Exception): |
| 148 | pass |
| 149 | |
| 150 | exception = ctypes.py_object(AsyncExc) |
| 151 | |
| 152 | # `worker_started` is set by the thread when it's inside a try/except |
| 153 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 154 | # `worker_saw_exception` is set by the thread upon catching that |
| 155 | # exception. |
| 156 | worker_started = threading.Event() |
| 157 | worker_saw_exception = threading.Event() |
| 158 | |
| 159 | class Worker(threading.Thread): |
| 160 | def run(self): |
| 161 | self.id = thread.get_ident() |
| 162 | self.finished = False |
| 163 | |
| 164 | try: |
| 165 | while True: |
| 166 | worker_started.set() |
| 167 | time.sleep(0.1) |
| 168 | except AsyncExc: |
| 169 | self.finished = True |
| 170 | worker_saw_exception.set() |
| 171 | |
| 172 | t = Worker() |
Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 173 | t.setDaemon(True) # so if this fails, we don't hang Python at shutdown |
| 174 | t.start() |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 175 | if verbose: |
| 176 | print " started worker thread" |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 177 | |
| 178 | # Try a thread id that doesn't make sense. |
| 179 | if verbose: |
| 180 | print " trying nonsensical thread id" |
Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 181 | result = set_async_exc(ctypes.c_long(-1), exception) |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 182 | self.assertEqual(result, 0) # no thread states modified |
| 183 | |
| 184 | # Now raise an exception in the worker thread. |
| 185 | if verbose: |
| 186 | print " waiting for worker thread to get started" |
| 187 | worker_started.wait() |
| 188 | if verbose: |
| 189 | print " verifying worker hasn't exited" |
| 190 | self.assert_(not t.finished) |
| 191 | if verbose: |
| 192 | print " attempting to raise asynch exception in worker" |
Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 193 | result = set_async_exc(ctypes.c_long(t.id), exception) |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 194 | self.assertEqual(result, 1) # one thread state modified |
| 195 | if verbose: |
| 196 | print " waiting for worker to say it caught the exception" |
| 197 | worker_saw_exception.wait(timeout=10) |
| 198 | self.assert_(t.finished) |
| 199 | if verbose: |
| 200 | print " all OK -- joining worker" |
| 201 | if t.finished: |
| 202 | t.join() |
| 203 | # else the thread is still running, and we have no way to kill it |
| 204 | |
Gregory P. Smith | 8f034d9 | 2008-01-22 01:29:11 +0000 | [diff] [blame] | 205 | def test_enumerate_after_join(self): |
| 206 | # Try hard to trigger #1703448: a thread is still returned in |
| 207 | # threading.enumerate() after it has been join()ed. |
| 208 | enum = threading.enumerate |
| 209 | old_interval = sys.getcheckinterval() |
| 210 | sys.setcheckinterval(1) |
| 211 | try: |
| 212 | for i in xrange(1, 1000): |
| 213 | t = threading.Thread(target=lambda: None) |
| 214 | t.start() |
| 215 | t.join() |
| 216 | l = enum() |
| 217 | self.assertFalse(t in l, |
| 218 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 219 | finally: |
| 220 | sys.setcheckinterval(old_interval) |
| 221 | |
| 222 | |
Gregory P. Smith | 5e8dc97 | 2008-08-17 23:01:11 +0000 | [diff] [blame] | 223 | class ThreadJoinOnShutdown(unittest.TestCase): |
| 224 | |
| 225 | def _run_and_join(self, script): |
| 226 | script = """if 1: |
| 227 | import sys, os, time, threading |
| 228 | |
| 229 | # a thread, which waits for the main program to terminate |
| 230 | def joiningfunc(mainthread): |
| 231 | mainthread.join() |
| 232 | print 'end of thread' |
| 233 | \n""" + script |
| 234 | |
| 235 | import subprocess |
| 236 | p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) |
| 237 | rc = p.wait() |
Benjamin Peterson | efbf6fc | 2008-08-23 21:25:16 +0000 | [diff] [blame] | 238 | data = p.stdout.read().replace('\r', '') |
| 239 | self.assertEqual(data, "end of main\nend of thread\n") |
Gregory P. Smith | 5e8dc97 | 2008-08-17 23:01:11 +0000 | [diff] [blame] | 240 | self.failIf(rc == 2, "interpreter was blocked") |
| 241 | self.failUnless(rc == 0, "Unexpected error") |
| 242 | |
| 243 | def test_1_join_on_shutdown(self): |
| 244 | # The usual case: on exit, wait for a non-daemon thread |
| 245 | script = """if 1: |
| 246 | import os |
| 247 | t = threading.Thread(target=joiningfunc, |
| 248 | args=(threading.currentThread(),)) |
| 249 | t.start() |
| 250 | time.sleep(0.1) |
| 251 | print 'end of main' |
| 252 | """ |
| 253 | self._run_and_join(script) |
| 254 | |
| 255 | |
| 256 | def test_2_join_in_forked_process(self): |
| 257 | # Like the test above, but from a forked interpreter |
| 258 | import os |
| 259 | if not hasattr(os, 'fork'): |
| 260 | return |
| 261 | script = """if 1: |
| 262 | childpid = os.fork() |
| 263 | if childpid != 0: |
| 264 | os.waitpid(childpid, 0) |
| 265 | sys.exit(0) |
| 266 | |
| 267 | t = threading.Thread(target=joiningfunc, |
| 268 | args=(threading.currentThread(),)) |
| 269 | t.start() |
| 270 | print 'end of main' |
| 271 | """ |
| 272 | self._run_and_join(script) |
| 273 | |
| 274 | def test_3_join_in_forked_from_thread(self): |
| 275 | # Like the test above, but fork() was called from a worker thread |
| 276 | # In the forked process, the main Thread object must be marked as stopped. |
| 277 | import os |
| 278 | if not hasattr(os, 'fork'): |
| 279 | return |
Martin v. Löwis | 358076f | 2008-12-13 14:42:53 +0000 | [diff] [blame^] | 280 | # Skip platforms with known problems forking from a worker thread. |
| 281 | # See http://bugs.python.org/issue3863. |
| 282 | if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): |
| 283 | print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread' |
| 284 | ' due to known OS bugs on'), sys.platform |
| 285 | return |
Gregory P. Smith | 5e8dc97 | 2008-08-17 23:01:11 +0000 | [diff] [blame] | 286 | script = """if 1: |
| 287 | main_thread = threading.currentThread() |
| 288 | def worker(): |
| 289 | childpid = os.fork() |
| 290 | if childpid != 0: |
| 291 | os.waitpid(childpid, 0) |
| 292 | sys.exit(0) |
| 293 | |
| 294 | t = threading.Thread(target=joiningfunc, |
| 295 | args=(main_thread,)) |
| 296 | print 'end of main' |
| 297 | t.start() |
| 298 | t.join() # Should not block: main_thread is already stopped |
| 299 | |
| 300 | w = threading.Thread(target=worker) |
| 301 | w.start() |
| 302 | """ |
| 303 | self._run_and_join(script) |
| 304 | |
| 305 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 306 | def test_main(): |
Gregory P. Smith | 5e8dc97 | 2008-08-17 23:01:11 +0000 | [diff] [blame] | 307 | test.test_support.run_unittest(ThreadTests, |
| 308 | ThreadJoinOnShutdown) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 309 | |
| 310 | if __name__ == "__main__": |
| 311 | test_main() |