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