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 | 8856dda | 2008-06-01 23:48:47 +0000 | [diff] [blame] | 6 | import re |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 7 | import sys |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 8 | import threading |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 9 | import thread |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 10 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 11 | import unittest |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 12 | import weakref |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 13 | |
Antoine Pitrou | c747d3a | 2009-11-09 16:47:50 +0000 | [diff] [blame] | 14 | from test import lock_tests |
| 15 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 16 | # A trivial mutable counter. |
| 17 | class Counter(object): |
| 18 | def __init__(self): |
| 19 | self.value = 0 |
| 20 | def inc(self): |
| 21 | self.value += 1 |
| 22 | def dec(self): |
| 23 | self.value -= 1 |
| 24 | def get(self): |
| 25 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 26 | |
| 27 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 28 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 29 | threading.Thread.__init__(self, name=name) |
| 30 | self.testcase = testcase |
| 31 | self.sema = sema |
| 32 | self.mutex = mutex |
| 33 | self.nrunning = nrunning |
| 34 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 35 | def run(self): |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 36 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 37 | if verbose: |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 38 | print 'task %s will run for %.1f usec' % ( |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 39 | self.name, delay * 1e6) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 40 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 41 | with self.sema: |
| 42 | with self.mutex: |
| 43 | self.nrunning.inc() |
| 44 | if verbose: |
| 45 | print self.nrunning.get(), 'tasks are running' |
| 46 | self.testcase.assert_(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 47 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 48 | time.sleep(delay) |
| 49 | if verbose: |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 50 | print 'task', self.name, 'done' |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 51 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 52 | with self.mutex: |
| 53 | self.nrunning.dec() |
| 54 | self.testcase.assert_(self.nrunning.get() >= 0) |
| 55 | if verbose: |
| 56 | print '%s is finished. %d tasks are running' % ( |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 57 | self.name, self.nrunning.get()) |
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) |
Benjamin Peterson | d8a8972 | 2008-08-18 16:40:03 +0000 | [diff] [blame] | 78 | self.failUnlessEqual(t.ident, None) |
Gregory P. Smith | 8856dda | 2008-06-01 23:48:47 +0000 | [diff] [blame] | 79 | self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 80 | t.start() |
| 81 | |
| 82 | if verbose: |
| 83 | print 'waiting for all tasks to complete' |
| 84 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 85 | t.join(NUMTASKS) |
Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 86 | self.assert_(not t.is_alive()) |
Benjamin Peterson | d8a8972 | 2008-08-18 16:40:03 +0000 | [diff] [blame] | 87 | self.failIfEqual(t.ident, 0) |
Benjamin Peterson | 61611f8 | 2009-03-31 21:40:18 +0000 | [diff] [blame] | 88 | self.assertFalse(t.ident is None) |
Gregory P. Smith | 8856dda | 2008-06-01 23:48:47 +0000 | [diff] [blame] | 89 | self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 90 | if verbose: |
| 91 | print 'all tasks done' |
| 92 | self.assertEqual(numrunning.get(), 0) |
| 93 | |
Benjamin Peterson | 61611f8 | 2009-03-31 21:40:18 +0000 | [diff] [blame] | 94 | def test_ident_of_no_threading_threads(self): |
| 95 | # The ident still must work for the main thread and dummy threads. |
| 96 | self.assertFalse(threading.currentThread().ident is None) |
| 97 | def f(): |
| 98 | ident.append(threading.currentThread().ident) |
| 99 | done.set() |
| 100 | done = threading.Event() |
| 101 | ident = [] |
| 102 | thread.start_new_thread(f, ()) |
| 103 | done.wait() |
| 104 | self.assertFalse(ident[0] is None) |
Antoine Pitrou | e319983 | 2009-11-08 00:36:33 +0000 | [diff] [blame] | 105 | # Kill the "immortal" _DummyThread |
| 106 | del threading._active[ident[0]] |
Benjamin Peterson | 61611f8 | 2009-03-31 21:40:18 +0000 | [diff] [blame] | 107 | |
Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 108 | # run with a small(ish) thread stack size (256kB) |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 109 | def test_various_ops_small_stack(self): |
| 110 | if verbose: |
Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 111 | print 'with 256kB thread stack size...' |
Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 112 | try: |
| 113 | threading.stack_size(262144) |
| 114 | except thread.error: |
| 115 | if verbose: |
| 116 | print 'platform does not support changing thread stack size' |
| 117 | return |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 118 | self.test_various_ops() |
| 119 | threading.stack_size(0) |
| 120 | |
| 121 | # run with a large thread stack size (1MB) |
| 122 | def test_various_ops_large_stack(self): |
| 123 | if verbose: |
| 124 | print 'with 1MB thread stack size...' |
Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 125 | try: |
| 126 | threading.stack_size(0x100000) |
| 127 | except thread.error: |
| 128 | if verbose: |
| 129 | print 'platform does not support changing thread stack size' |
| 130 | return |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 131 | self.test_various_ops() |
| 132 | threading.stack_size(0) |
| 133 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 134 | def test_foreign_thread(self): |
| 135 | # Check that a "foreign" thread can use the threading module. |
| 136 | def f(mutex): |
Antoine Pitrou | c747d3a | 2009-11-09 16:47:50 +0000 | [diff] [blame] | 137 | # Calling current_thread() forces an entry for the foreign |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 138 | # thread to get made in the threading._active map. |
Antoine Pitrou | c747d3a | 2009-11-09 16:47:50 +0000 | [diff] [blame] | 139 | threading.current_thread() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 140 | mutex.release() |
| 141 | |
| 142 | mutex = threading.Lock() |
| 143 | mutex.acquire() |
| 144 | tid = thread.start_new_thread(f, (mutex,)) |
| 145 | # Wait for the thread to finish. |
| 146 | mutex.acquire() |
| 147 | self.assert_(tid in threading._active) |
| 148 | self.assert_(isinstance(threading._active[tid], |
| 149 | threading._DummyThread)) |
| 150 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 151 | |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 152 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 153 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 154 | def test_PyThreadState_SetAsyncExc(self): |
| 155 | try: |
| 156 | import ctypes |
| 157 | except ImportError: |
| 158 | if verbose: |
| 159 | print "test_PyThreadState_SetAsyncExc can't import ctypes" |
| 160 | return # can't do anything |
| 161 | |
| 162 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 163 | |
| 164 | class AsyncExc(Exception): |
| 165 | pass |
| 166 | |
| 167 | exception = ctypes.py_object(AsyncExc) |
| 168 | |
| 169 | # `worker_started` is set by the thread when it's inside a try/except |
| 170 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 171 | # `worker_saw_exception` is set by the thread upon catching that |
| 172 | # exception. |
| 173 | worker_started = threading.Event() |
| 174 | worker_saw_exception = threading.Event() |
| 175 | |
| 176 | class Worker(threading.Thread): |
| 177 | def run(self): |
| 178 | self.id = thread.get_ident() |
| 179 | self.finished = False |
| 180 | |
| 181 | try: |
| 182 | while True: |
| 183 | worker_started.set() |
| 184 | time.sleep(0.1) |
| 185 | except AsyncExc: |
| 186 | self.finished = True |
| 187 | worker_saw_exception.set() |
| 188 | |
| 189 | t = Worker() |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 190 | t.daemon = True # so if this fails, we don't hang Python at shutdown |
Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 191 | t.start() |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 192 | if verbose: |
| 193 | print " started worker thread" |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 194 | |
| 195 | # Try a thread id that doesn't make sense. |
| 196 | if verbose: |
| 197 | print " trying nonsensical thread id" |
Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 198 | result = set_async_exc(ctypes.c_long(-1), exception) |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 199 | self.assertEqual(result, 0) # no thread states modified |
| 200 | |
| 201 | # Now raise an exception in the worker thread. |
| 202 | if verbose: |
| 203 | print " waiting for worker thread to get started" |
| 204 | worker_started.wait() |
| 205 | if verbose: |
| 206 | print " verifying worker hasn't exited" |
| 207 | self.assert_(not t.finished) |
| 208 | if verbose: |
| 209 | print " attempting to raise asynch exception in worker" |
Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 210 | result = set_async_exc(ctypes.c_long(t.id), exception) |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 211 | self.assertEqual(result, 1) # one thread state modified |
| 212 | if verbose: |
| 213 | print " waiting for worker to say it caught the exception" |
| 214 | worker_saw_exception.wait(timeout=10) |
| 215 | self.assert_(t.finished) |
| 216 | if verbose: |
| 217 | print " all OK -- joining worker" |
| 218 | if t.finished: |
| 219 | t.join() |
| 220 | # else the thread is still running, and we have no way to kill it |
| 221 | |
Gregory P. Smith | 9922a9a | 2010-02-28 18:40:12 +0000 | [diff] [blame] | 222 | def test_limbo_cleanup(self): |
| 223 | # Issue 7481: Failure to start thread should cleanup the limbo map. |
| 224 | def fail_new_thread(*args): |
| 225 | raise thread.error() |
| 226 | _start_new_thread = threading._start_new_thread |
| 227 | threading._start_new_thread = fail_new_thread |
| 228 | try: |
| 229 | t = threading.Thread(target=lambda: None) |
Gregory P. Smith | c5e6279 | 2010-03-01 03:11:09 +0000 | [diff] [blame] | 230 | self.assertRaises(thread.error, t.start) |
| 231 | self.assertFalse( |
| 232 | t in threading._limbo, |
| 233 | "Failed to cleanup _limbo map on failure of Thread.start().") |
Gregory P. Smith | 9922a9a | 2010-02-28 18:40:12 +0000 | [diff] [blame] | 234 | finally: |
| 235 | threading._start_new_thread = _start_new_thread |
| 236 | |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 237 | def test_finalize_runnning_thread(self): |
| 238 | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
| 239 | # very late on python exit: on deallocation of a running thread for |
| 240 | # example. |
| 241 | try: |
| 242 | import ctypes |
| 243 | except ImportError: |
| 244 | if verbose: |
| 245 | print("test_finalize_with_runnning_thread can't import ctypes") |
| 246 | return # can't do anything |
| 247 | |
| 248 | import subprocess |
| 249 | rc = subprocess.call([sys.executable, "-c", """if 1: |
| 250 | import ctypes, sys, time, thread |
| 251 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 252 | # This lock is used as a simple event variable. |
| 253 | ready = thread.allocate_lock() |
| 254 | ready.acquire() |
| 255 | |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 256 | # Module globals are cleared before __del__ is run |
| 257 | # So we save the functions in class dict |
| 258 | class C: |
| 259 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 260 | release = ctypes.pythonapi.PyGILState_Release |
| 261 | def __del__(self): |
| 262 | state = self.ensure() |
| 263 | self.release(state) |
| 264 | |
| 265 | def waitingThread(): |
| 266 | x = C() |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 267 | ready.release() |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 268 | time.sleep(100) |
| 269 | |
| 270 | thread.start_new_thread(waitingThread, ()) |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 271 | ready.acquire() # Be sure the other thread is waiting. |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 272 | sys.exit(42) |
| 273 | """]) |
| 274 | self.assertEqual(rc, 42) |
| 275 | |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 276 | def test_finalize_with_trace(self): |
| 277 | # Issue1733757 |
| 278 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
| 279 | import subprocess |
| 280 | rc = subprocess.call([sys.executable, "-c", """if 1: |
| 281 | import sys, threading |
| 282 | |
| 283 | # A deadlock-killer, to prevent the |
| 284 | # testsuite to hang forever |
| 285 | def killer(): |
| 286 | import os, time |
| 287 | time.sleep(2) |
| 288 | print 'program blocked; aborting' |
| 289 | os._exit(2) |
| 290 | t = threading.Thread(target=killer) |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 291 | t.daemon = True |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 292 | t.start() |
| 293 | |
| 294 | # This is the trace function |
| 295 | def func(frame, event, arg): |
Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 296 | threading.current_thread() |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 297 | return func |
| 298 | |
| 299 | sys.settrace(func) |
| 300 | """]) |
| 301 | self.failIf(rc == 2, "interpreted was blocked") |
| 302 | self.failUnless(rc == 0, "Unexpected error") |
| 303 | |
Antoine Pitrou | 9aece75 | 2009-10-27 12:48:52 +0000 | [diff] [blame] | 304 | def test_join_nondaemon_on_shutdown(self): |
| 305 | # Issue 1722344 |
| 306 | # Raising SystemExit skipped threading._shutdown |
| 307 | import subprocess |
| 308 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 309 | import threading |
| 310 | from time import sleep |
| 311 | |
| 312 | def child(): |
| 313 | sleep(1) |
| 314 | # As a non-daemon thread we SHOULD wake up and nothing |
| 315 | # should be torn down yet |
| 316 | print "Woke up, sleep function is:", sleep |
| 317 | |
| 318 | threading.Thread(target=child).start() |
| 319 | raise SystemExit |
| 320 | """], |
| 321 | stdout=subprocess.PIPE, |
| 322 | stderr=subprocess.PIPE) |
| 323 | stdout, stderr = p.communicate() |
| 324 | self.assertEqual(stdout.strip(), |
| 325 | "Woke up, sleep function is: <built-in function sleep>") |
| 326 | stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip() |
| 327 | self.assertEqual(stderr, "") |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 328 | |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 329 | def test_enumerate_after_join(self): |
| 330 | # Try hard to trigger #1703448: a thread is still returned in |
| 331 | # threading.enumerate() after it has been join()ed. |
| 332 | enum = threading.enumerate |
| 333 | old_interval = sys.getcheckinterval() |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 334 | try: |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 335 | for i in xrange(1, 100): |
| 336 | # Try a couple times at each thread-switching interval |
| 337 | # to get more interleavings. |
| 338 | sys.setcheckinterval(i // 5) |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 339 | t = threading.Thread(target=lambda: None) |
| 340 | t.start() |
| 341 | t.join() |
| 342 | l = enum() |
| 343 | self.assertFalse(t in l, |
| 344 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 345 | finally: |
| 346 | sys.setcheckinterval(old_interval) |
| 347 | |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 348 | def test_no_refcycle_through_target(self): |
| 349 | class RunSelfFunction(object): |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 350 | def __init__(self, should_raise): |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 351 | # The links in this refcycle from Thread back to self |
| 352 | # should be cleaned up when the thread completes. |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 353 | self.should_raise = should_raise |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 354 | self.thread = threading.Thread(target=self._run, |
| 355 | args=(self,), |
| 356 | kwargs={'yet_another':self}) |
| 357 | self.thread.start() |
| 358 | |
| 359 | def _run(self, other_ref, yet_another): |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 360 | if self.should_raise: |
| 361 | raise SystemExit |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 362 | |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 363 | cyclic_object = RunSelfFunction(should_raise=False) |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 364 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 365 | cyclic_object.thread.join() |
| 366 | del cyclic_object |
Jeffrey Yasskin | 8b9091f | 2008-03-28 04:11:18 +0000 | [diff] [blame] | 367 | self.assertEquals(None, weak_cyclic_object(), |
| 368 | msg=('%d references still around' % |
| 369 | sys.getrefcount(weak_cyclic_object()))) |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 370 | |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 371 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 372 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 373 | raising_cyclic_object.thread.join() |
| 374 | del raising_cyclic_object |
Jeffrey Yasskin | 8b9091f | 2008-03-28 04:11:18 +0000 | [diff] [blame] | 375 | self.assertEquals(None, weak_raising_cyclic_object(), |
| 376 | msg=('%d references still around' % |
| 377 | sys.getrefcount(weak_raising_cyclic_object()))) |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 378 | |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 379 | |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 380 | class 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' |
| 390 | \n""" + script |
| 391 | |
| 392 | import subprocess |
| 393 | p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) |
| 394 | rc = p.wait() |
Benjamin Peterson | f5668f1 | 2008-07-17 12:57:22 +0000 | [diff] [blame] | 395 | data = p.stdout.read().replace('\r', '') |
| 396 | self.assertEqual(data, "end of main\nend of thread\n") |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 397 | self.failIf(rc == 2, "interpreter was blocked") |
| 398 | self.failUnless(rc == 0, "Unexpected error") |
| 399 | |
| 400 | def test_1_join_on_shutdown(self): |
| 401 | # The usual case: on exit, wait for a non-daemon thread |
| 402 | script = """if 1: |
| 403 | import os |
| 404 | t = threading.Thread(target=joiningfunc, |
| 405 | args=(threading.current_thread(),)) |
| 406 | t.start() |
| 407 | time.sleep(0.1) |
| 408 | print 'end of main' |
| 409 | """ |
| 410 | self._run_and_join(script) |
| 411 | |
| 412 | |
| 413 | def test_2_join_in_forked_process(self): |
| 414 | # Like the test above, but from a forked interpreter |
| 415 | import os |
| 416 | if not hasattr(os, 'fork'): |
| 417 | return |
| 418 | script = """if 1: |
| 419 | childpid = os.fork() |
| 420 | if childpid != 0: |
| 421 | os.waitpid(childpid, 0) |
| 422 | sys.exit(0) |
| 423 | |
| 424 | t = threading.Thread(target=joiningfunc, |
| 425 | args=(threading.current_thread(),)) |
| 426 | t.start() |
| 427 | print 'end of main' |
| 428 | """ |
| 429 | self._run_and_join(script) |
| 430 | |
| 431 | def test_3_join_in_forked_from_thread(self): |
| 432 | # Like the test above, but fork() was called from a worker thread |
| 433 | # In the forked process, the main Thread object must be marked as stopped. |
| 434 | import os |
| 435 | if not hasattr(os, 'fork'): |
| 436 | return |
Gregory P. Smith | 0806749 | 2008-09-30 20:41:13 +0000 | [diff] [blame] | 437 | # Skip platforms with known problems forking from a worker thread. |
| 438 | # See http://bugs.python.org/issue3863. |
| 439 | if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): |
| 440 | print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread' |
| 441 | ' due to known OS bugs on'), sys.platform |
| 442 | return |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 443 | script = """if 1: |
| 444 | main_thread = threading.current_thread() |
| 445 | def worker(): |
| 446 | childpid = os.fork() |
| 447 | if childpid != 0: |
| 448 | os.waitpid(childpid, 0) |
| 449 | sys.exit(0) |
| 450 | |
| 451 | t = threading.Thread(target=joiningfunc, |
| 452 | args=(main_thread,)) |
| 453 | print 'end of main' |
| 454 | t.start() |
| 455 | t.join() # Should not block: main_thread is already stopped |
| 456 | |
| 457 | w = threading.Thread(target=worker) |
| 458 | w.start() |
| 459 | """ |
| 460 | self._run_and_join(script) |
| 461 | |
| 462 | |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 463 | class ThreadingExceptionTests(unittest.TestCase): |
| 464 | # A RuntimeError should be raised if Thread.start() is called |
| 465 | # multiple times. |
| 466 | def test_start_thread_again(self): |
| 467 | thread = threading.Thread() |
| 468 | thread.start() |
| 469 | self.assertRaises(RuntimeError, thread.start) |
| 470 | |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 471 | def test_joining_current_thread(self): |
Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 472 | current_thread = threading.current_thread() |
| 473 | self.assertRaises(RuntimeError, current_thread.join); |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 474 | |
| 475 | def test_joining_inactive_thread(self): |
| 476 | thread = threading.Thread() |
| 477 | self.assertRaises(RuntimeError, thread.join) |
| 478 | |
| 479 | def test_daemonize_active_thread(self): |
| 480 | thread = threading.Thread() |
| 481 | thread.start() |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 482 | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 483 | |
| 484 | |
Antoine Pitrou | c747d3a | 2009-11-09 16:47:50 +0000 | [diff] [blame] | 485 | class LockTests(lock_tests.LockTests): |
| 486 | locktype = staticmethod(threading.Lock) |
| 487 | |
| 488 | class RLockTests(lock_tests.RLockTests): |
| 489 | locktype = staticmethod(threading.RLock) |
| 490 | |
| 491 | class EventTests(lock_tests.EventTests): |
| 492 | eventtype = staticmethod(threading.Event) |
| 493 | |
| 494 | class ConditionAsRLockTests(lock_tests.RLockTests): |
| 495 | # An Condition uses an RLock by default and exports its API. |
| 496 | locktype = staticmethod(threading.Condition) |
| 497 | |
| 498 | class ConditionTests(lock_tests.ConditionTests): |
| 499 | condtype = staticmethod(threading.Condition) |
| 500 | |
| 501 | class SemaphoreTests(lock_tests.SemaphoreTests): |
| 502 | semtype = staticmethod(threading.Semaphore) |
| 503 | |
| 504 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
| 505 | semtype = staticmethod(threading.BoundedSemaphore) |
| 506 | |
| 507 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 508 | def test_main(): |
Antoine Pitrou | c747d3a | 2009-11-09 16:47:50 +0000 | [diff] [blame] | 509 | test.test_support.run_unittest(LockTests, RLockTests, EventTests, |
| 510 | ConditionAsRLockTests, ConditionTests, |
| 511 | SemaphoreTests, BoundedSemaphoreTests, |
| 512 | ThreadTests, |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 513 | ThreadJoinOnShutdown, |
| 514 | ThreadingExceptionTests, |
| 515 | ) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 516 | |
| 517 | if __name__ == "__main__": |
| 518 | test_main() |