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