| 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 | 
| Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 8 | thread = test.test_support.import_module('thread') | 
 | 9 | threading = test.test_support.import_module('threading') | 
| 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 | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 13 | import os | 
 | 14 | import subprocess | 
| Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 15 |  | 
| Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 16 | from test import lock_tests | 
 | 17 |  | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 18 | # A trivial mutable counter. | 
 | 19 | class Counter(object): | 
 | 20 |     def __init__(self): | 
 | 21 |         self.value = 0 | 
 | 22 |     def inc(self): | 
 | 23 |         self.value += 1 | 
 | 24 |     def dec(self): | 
 | 25 |         self.value -= 1 | 
 | 26 |     def get(self): | 
 | 27 |         return self.value | 
| Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 28 |  | 
 | 29 | class TestThread(threading.Thread): | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 30 |     def __init__(self, name, testcase, sema, mutex, nrunning): | 
 | 31 |         threading.Thread.__init__(self, name=name) | 
 | 32 |         self.testcase = testcase | 
 | 33 |         self.sema = sema | 
 | 34 |         self.mutex = mutex | 
 | 35 |         self.nrunning = nrunning | 
 | 36 |  | 
| Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 37 |     def run(self): | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 38 |         delay = random.random() / 10000.0 | 
| Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 39 |         if verbose: | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 40 |             print 'task %s will run for %.1f usec' % ( | 
| Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 41 |                 self.name, delay * 1e6) | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 42 |  | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 43 |         with self.sema: | 
 | 44 |             with self.mutex: | 
 | 45 |                 self.nrunning.inc() | 
 | 46 |                 if verbose: | 
 | 47 |                     print self.nrunning.get(), 'tasks are running' | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 48 |                 self.testcase.assertTrue(self.nrunning.get() <= 3) | 
| 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 |             time.sleep(delay) | 
 | 51 |             if verbose: | 
| Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 52 |                 print 'task', self.name, 'done' | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 53 |  | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 54 |             with self.mutex: | 
 | 55 |                 self.nrunning.dec() | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 56 |                 self.testcase.assertTrue(self.nrunning.get() >= 0) | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 57 |                 if verbose: | 
 | 58 |                     print '%s is finished. %d tasks are running' % ( | 
| Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 59 |                         self.name, self.nrunning.get()) | 
| Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 60 |  | 
| Antoine Pitrou | bb0bb30 | 2009-10-27 20:02:23 +0000 | [diff] [blame] | 61 | class BaseTestCase(unittest.TestCase): | 
 | 62 |     def setUp(self): | 
 | 63 |         self._threads = test.test_support.threading_setup() | 
 | 64 |  | 
 | 65 |     def tearDown(self): | 
 | 66 |         test.test_support.threading_cleanup(*self._threads) | 
 | 67 |         test.test_support.reap_children() | 
 | 68 |  | 
 | 69 |  | 
 | 70 | class ThreadTests(BaseTestCase): | 
| Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 71 |  | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 72 |     # Create a bunch of threads, let each do some work, wait until all are | 
 | 73 |     # done. | 
 | 74 |     def test_various_ops(self): | 
 | 75 |         # This takes about n/3 seconds to run (about n/3 clumps of tasks, | 
 | 76 |         # times about 1 second per clump). | 
 | 77 |         NUMTASKS = 10 | 
 | 78 |  | 
 | 79 |         # no more than 3 of the 10 can run at once | 
 | 80 |         sema = threading.BoundedSemaphore(value=3) | 
 | 81 |         mutex = threading.RLock() | 
 | 82 |         numrunning = Counter() | 
 | 83 |  | 
 | 84 |         threads = [] | 
 | 85 |  | 
 | 86 |         for i in range(NUMTASKS): | 
 | 87 |             t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) | 
 | 88 |             threads.append(t) | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 89 |             self.assertEqual(t.ident, None) | 
 | 90 |             self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 91 |             t.start() | 
 | 92 |  | 
 | 93 |         if verbose: | 
 | 94 |             print 'waiting for all tasks to complete' | 
 | 95 |         for t in threads: | 
| Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 96 |             t.join(NUMTASKS) | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 97 |             self.assertTrue(not t.is_alive()) | 
 | 98 |             self.assertNotEqual(t.ident, 0) | 
| Benjamin Peterson | d906ea6 | 2009-03-31 21:34:42 +0000 | [diff] [blame] | 99 |             self.assertFalse(t.ident is None) | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 100 |             self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 101 |         if verbose: | 
 | 102 |             print 'all tasks done' | 
 | 103 |         self.assertEqual(numrunning.get(), 0) | 
 | 104 |  | 
| Benjamin Peterson | d906ea6 | 2009-03-31 21:34:42 +0000 | [diff] [blame] | 105 |     def test_ident_of_no_threading_threads(self): | 
 | 106 |         # The ident still must work for the main thread and dummy threads. | 
 | 107 |         self.assertFalse(threading.currentThread().ident is None) | 
 | 108 |         def f(): | 
 | 109 |             ident.append(threading.currentThread().ident) | 
 | 110 |             done.set() | 
 | 111 |         done = threading.Event() | 
 | 112 |         ident = [] | 
 | 113 |         thread.start_new_thread(f, ()) | 
 | 114 |         done.wait() | 
 | 115 |         self.assertFalse(ident[0] is None) | 
| Antoine Pitrou | 0025330 | 2009-11-08 00:24:12 +0000 | [diff] [blame] | 116 |         # Kill the "immortal" _DummyThread | 
 | 117 |         del threading._active[ident[0]] | 
| Benjamin Peterson | d906ea6 | 2009-03-31 21:34:42 +0000 | [diff] [blame] | 118 |  | 
| Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 119 |     # run with a small(ish) thread stack size (256kB) | 
| Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 120 |     def test_various_ops_small_stack(self): | 
 | 121 |         if verbose: | 
| Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 122 |             print 'with 256kB thread stack size...' | 
| Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 123 |         try: | 
 | 124 |             threading.stack_size(262144) | 
 | 125 |         except thread.error: | 
 | 126 |             if verbose: | 
 | 127 |                 print 'platform does not support changing thread stack size' | 
 | 128 |             return | 
| Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 129 |         self.test_various_ops() | 
 | 130 |         threading.stack_size(0) | 
 | 131 |  | 
 | 132 |     # run with a large thread stack size (1MB) | 
 | 133 |     def test_various_ops_large_stack(self): | 
 | 134 |         if verbose: | 
 | 135 |             print 'with 1MB thread stack size...' | 
| Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 136 |         try: | 
 | 137 |             threading.stack_size(0x100000) | 
 | 138 |         except thread.error: | 
 | 139 |             if verbose: | 
 | 140 |                 print 'platform does not support changing thread stack size' | 
 | 141 |             return | 
| Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 142 |         self.test_various_ops() | 
 | 143 |         threading.stack_size(0) | 
 | 144 |  | 
| Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 145 |     def test_foreign_thread(self): | 
 | 146 |         # Check that a "foreign" thread can use the threading module. | 
 | 147 |         def f(mutex): | 
| Antoine Pitrou | d7158d4 | 2009-11-09 16:00:11 +0000 | [diff] [blame] | 148 |             # Calling current_thread() forces an entry for the foreign | 
| Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 149 |             # thread to get made in the threading._active map. | 
| Antoine Pitrou | d7158d4 | 2009-11-09 16:00:11 +0000 | [diff] [blame] | 150 |             threading.current_thread() | 
| Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 151 |             mutex.release() | 
 | 152 |  | 
 | 153 |         mutex = threading.Lock() | 
 | 154 |         mutex.acquire() | 
 | 155 |         tid = thread.start_new_thread(f, (mutex,)) | 
 | 156 |         # Wait for the thread to finish. | 
 | 157 |         mutex.acquire() | 
| Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 158 |         self.assertIn(tid, threading._active) | 
| Ezio Melotti | b0f5adc | 2010-01-24 16:58:36 +0000 | [diff] [blame] | 159 |         self.assertIsInstance(threading._active[tid], threading._DummyThread) | 
| Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 160 |         del threading._active[tid] | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 161 |  | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 162 |     # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) | 
 | 163 |     # exposed at the Python level.  This test relies on ctypes to get at it. | 
 | 164 |     def test_PyThreadState_SetAsyncExc(self): | 
 | 165 |         try: | 
 | 166 |             import ctypes | 
 | 167 |         except ImportError: | 
 | 168 |             if verbose: | 
 | 169 |                 print "test_PyThreadState_SetAsyncExc can't import ctypes" | 
 | 170 |             return  # can't do anything | 
 | 171 |  | 
 | 172 |         set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc | 
 | 173 |  | 
 | 174 |         class AsyncExc(Exception): | 
 | 175 |             pass | 
 | 176 |  | 
 | 177 |         exception = ctypes.py_object(AsyncExc) | 
 | 178 |  | 
| Antoine Pitrou | 8a172b1 | 2009-10-18 18:22:04 +0000 | [diff] [blame] | 179 |         # First check it works when setting the exception from the same thread. | 
 | 180 |         tid = thread.get_ident() | 
 | 181 |  | 
 | 182 |         try: | 
 | 183 |             result = set_async_exc(ctypes.c_long(tid), exception) | 
 | 184 |             # The exception is async, so we might have to keep the VM busy until | 
 | 185 |             # it notices. | 
 | 186 |             while True: | 
 | 187 |                 pass | 
 | 188 |         except AsyncExc: | 
 | 189 |             pass | 
 | 190 |         else: | 
| Antoine Pitrou | 603acf9 | 2009-10-18 18:37:11 +0000 | [diff] [blame] | 191 |             # This code is unreachable but it reflects the intent. If we wanted | 
 | 192 |             # to be smarter the above loop wouldn't be infinite. | 
| Antoine Pitrou | 8a172b1 | 2009-10-18 18:22:04 +0000 | [diff] [blame] | 193 |             self.fail("AsyncExc not raised") | 
 | 194 |         try: | 
 | 195 |             self.assertEqual(result, 1) # one thread state modified | 
 | 196 |         except UnboundLocalError: | 
| Antoine Pitrou | 603acf9 | 2009-10-18 18:37:11 +0000 | [diff] [blame] | 197 |             # The exception was raised too quickly for us to get the result. | 
| Antoine Pitrou | 8a172b1 | 2009-10-18 18:22:04 +0000 | [diff] [blame] | 198 |             pass | 
 | 199 |  | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 200 |         # `worker_started` is set by the thread when it's inside a try/except | 
 | 201 |         # block waiting to catch the asynchronously set AsyncExc exception. | 
 | 202 |         # `worker_saw_exception` is set by the thread upon catching that | 
 | 203 |         # exception. | 
 | 204 |         worker_started = threading.Event() | 
 | 205 |         worker_saw_exception = threading.Event() | 
 | 206 |  | 
 | 207 |         class Worker(threading.Thread): | 
 | 208 |             def run(self): | 
 | 209 |                 self.id = thread.get_ident() | 
 | 210 |                 self.finished = False | 
 | 211 |  | 
 | 212 |                 try: | 
 | 213 |                     while True: | 
 | 214 |                         worker_started.set() | 
 | 215 |                         time.sleep(0.1) | 
 | 216 |                 except AsyncExc: | 
 | 217 |                     self.finished = True | 
 | 218 |                     worker_saw_exception.set() | 
 | 219 |  | 
 | 220 |         t = Worker() | 
| Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 221 |         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] | 222 |         t.start() | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 223 |         if verbose: | 
 | 224 |             print "    started worker thread" | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 225 |  | 
 | 226 |         # Try a thread id that doesn't make sense. | 
 | 227 |         if verbose: | 
 | 228 |             print "    trying nonsensical thread id" | 
| Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 229 |         result = set_async_exc(ctypes.c_long(-1), exception) | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 230 |         self.assertEqual(result, 0)  # no thread states modified | 
 | 231 |  | 
 | 232 |         # Now raise an exception in the worker thread. | 
 | 233 |         if verbose: | 
 | 234 |             print "    waiting for worker thread to get started" | 
| Georg Brandl | ef660e8 | 2009-03-31 20:41:08 +0000 | [diff] [blame] | 235 |         ret = worker_started.wait() | 
 | 236 |         self.assertTrue(ret) | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 237 |         if verbose: | 
 | 238 |             print "    verifying worker hasn't exited" | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 239 |         self.assertTrue(not t.finished) | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 240 |         if verbose: | 
 | 241 |             print "    attempting to raise asynch exception in worker" | 
| Tim Peters | 0857477 | 2006-08-11 00:49:01 +0000 | [diff] [blame] | 242 |         result = set_async_exc(ctypes.c_long(t.id), exception) | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 243 |         self.assertEqual(result, 1) # one thread state modified | 
 | 244 |         if verbose: | 
 | 245 |             print "    waiting for worker to say it caught the exception" | 
 | 246 |         worker_saw_exception.wait(timeout=10) | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 247 |         self.assertTrue(t.finished) | 
| Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 248 |         if verbose: | 
 | 249 |             print "    all OK -- joining worker" | 
 | 250 |         if t.finished: | 
 | 251 |             t.join() | 
 | 252 |         # else the thread is still running, and we have no way to kill it | 
 | 253 |  | 
| Gregory P. Smith | 613c7a5 | 2010-02-28 18:36:09 +0000 | [diff] [blame] | 254 |     def test_limbo_cleanup(self): | 
 | 255 |         # Issue 7481: Failure to start thread should cleanup the limbo map. | 
 | 256 |         def fail_new_thread(*args): | 
 | 257 |             raise thread.error() | 
 | 258 |         _start_new_thread = threading._start_new_thread | 
 | 259 |         threading._start_new_thread = fail_new_thread | 
 | 260 |         try: | 
 | 261 |             t = threading.Thread(target=lambda: None) | 
| Gregory P. Smith | 3c1586a | 2010-03-01 03:09:19 +0000 | [diff] [blame] | 262 |             self.assertRaises(thread.error, t.start) | 
 | 263 |             self.assertFalse( | 
 | 264 |                 t in threading._limbo, | 
 | 265 |                 "Failed to cleanup _limbo map on failure of Thread.start().") | 
| Gregory P. Smith | 613c7a5 | 2010-02-28 18:36:09 +0000 | [diff] [blame] | 266 |         finally: | 
 | 267 |             threading._start_new_thread = _start_new_thread | 
 | 268 |  | 
| Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 269 |     def test_finalize_runnning_thread(self): | 
 | 270 |         # Issue 1402: the PyGILState_Ensure / _Release functions may be called | 
 | 271 |         # very late on python exit: on deallocation of a running thread for | 
 | 272 |         # example. | 
 | 273 |         try: | 
 | 274 |             import ctypes | 
 | 275 |         except ImportError: | 
 | 276 |             if verbose: | 
 | 277 |                 print("test_finalize_with_runnning_thread can't import ctypes") | 
 | 278 |             return  # can't do anything | 
 | 279 |  | 
| Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 280 |         rc = subprocess.call([sys.executable, "-c", """if 1: | 
 | 281 |             import ctypes, sys, time, thread | 
 | 282 |  | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 283 |             # This lock is used as a simple event variable. | 
 | 284 |             ready = thread.allocate_lock() | 
 | 285 |             ready.acquire() | 
 | 286 |  | 
| Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 287 |             # Module globals are cleared before __del__ is run | 
 | 288 |             # So we save the functions in class dict | 
 | 289 |             class C: | 
 | 290 |                 ensure = ctypes.pythonapi.PyGILState_Ensure | 
 | 291 |                 release = ctypes.pythonapi.PyGILState_Release | 
 | 292 |                 def __del__(self): | 
 | 293 |                     state = self.ensure() | 
 | 294 |                     self.release(state) | 
 | 295 |  | 
 | 296 |             def waitingThread(): | 
 | 297 |                 x = C() | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 298 |                 ready.release() | 
| Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 299 |                 time.sleep(100) | 
 | 300 |  | 
 | 301 |             thread.start_new_thread(waitingThread, ()) | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 302 |             ready.acquire()  # Be sure the other thread is waiting. | 
| Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 303 |             sys.exit(42) | 
 | 304 |             """]) | 
 | 305 |         self.assertEqual(rc, 42) | 
 | 306 |  | 
| Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 307 |     def test_finalize_with_trace(self): | 
 | 308 |         # Issue1733757 | 
 | 309 |         # Avoid a deadlock when sys.settrace steps into threading._shutdown | 
| Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 310 |         p = subprocess.Popen([sys.executable, "-c", """if 1: | 
| Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 311 |             import sys, threading | 
 | 312 |  | 
 | 313 |             # A deadlock-killer, to prevent the | 
 | 314 |             # testsuite to hang forever | 
 | 315 |             def killer(): | 
 | 316 |                 import os, time | 
 | 317 |                 time.sleep(2) | 
 | 318 |                 print 'program blocked; aborting' | 
 | 319 |                 os._exit(2) | 
 | 320 |             t = threading.Thread(target=killer) | 
| Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 321 |             t.daemon = True | 
| Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 322 |             t.start() | 
 | 323 |  | 
 | 324 |             # This is the trace function | 
 | 325 |             def func(frame, event, arg): | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 326 |                 threading.current_thread() | 
| Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 327 |                 return func | 
 | 328 |  | 
 | 329 |             sys.settrace(func) | 
| Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 330 |             """], | 
 | 331 |             stdout=subprocess.PIPE, | 
 | 332 |             stderr=subprocess.PIPE) | 
| Brian Curtin | 51c9b51 | 2010-11-05 17:24:20 +0000 | [diff] [blame] | 333 |         self.addCleanup(p.stdout.close) | 
 | 334 |         self.addCleanup(p.stderr.close) | 
| Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 335 |         stdout, stderr = p.communicate() | 
 | 336 |         rc = p.returncode | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 337 |         self.assertFalse(rc == 2, "interpreted was blocked") | 
| Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 338 |         self.assertTrue(rc == 0, | 
 | 339 |                         "Unexpected error: " + repr(stderr)) | 
| Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 340 |  | 
| Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 341 |     def test_join_nondaemon_on_shutdown(self): | 
 | 342 |         # Issue 1722344 | 
 | 343 |         # Raising SystemExit skipped threading._shutdown | 
| Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 344 |         p = subprocess.Popen([sys.executable, "-c", """if 1: | 
 | 345 |                 import threading | 
 | 346 |                 from time import sleep | 
 | 347 |  | 
 | 348 |                 def child(): | 
 | 349 |                     sleep(1) | 
 | 350 |                     # As a non-daemon thread we SHOULD wake up and nothing | 
 | 351 |                     # should be torn down yet | 
 | 352 |                     print "Woke up, sleep function is:", sleep | 
 | 353 |  | 
 | 354 |                 threading.Thread(target=child).start() | 
 | 355 |                 raise SystemExit | 
 | 356 |             """], | 
 | 357 |             stdout=subprocess.PIPE, | 
 | 358 |             stderr=subprocess.PIPE) | 
| Brian Curtin | 51c9b51 | 2010-11-05 17:24:20 +0000 | [diff] [blame] | 359 |         self.addCleanup(p.stdout.close) | 
 | 360 |         self.addCleanup(p.stderr.close) | 
| Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 361 |         stdout, stderr = p.communicate() | 
| Antoine Pitrou | b119ca9 | 2009-10-23 12:01:13 +0000 | [diff] [blame] | 362 |         self.assertEqual(stdout.strip(), | 
 | 363 |             "Woke up, sleep function is: <built-in function sleep>") | 
| Antoine Pitrou | 9bd246b | 2009-10-20 21:59:25 +0000 | [diff] [blame] | 364 |         stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip() | 
| Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 365 |         self.assertEqual(stderr, "") | 
 | 366 |  | 
| Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 367 |     def test_enumerate_after_join(self): | 
 | 368 |         # Try hard to trigger #1703448: a thread is still returned in | 
 | 369 |         # threading.enumerate() after it has been join()ed. | 
 | 370 |         enum = threading.enumerate | 
 | 371 |         old_interval = sys.getcheckinterval() | 
| Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 372 |         try: | 
| Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 373 |             for i in xrange(1, 100): | 
 | 374 |                 # Try a couple times at each thread-switching interval | 
 | 375 |                 # to get more interleavings. | 
 | 376 |                 sys.setcheckinterval(i // 5) | 
| Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 377 |                 t = threading.Thread(target=lambda: None) | 
 | 378 |                 t.start() | 
 | 379 |                 t.join() | 
 | 380 |                 l = enum() | 
| Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 381 |                 self.assertNotIn(t, l, | 
| Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 382 |                     "#1703448 triggered after %d trials: %s" % (i, l)) | 
 | 383 |         finally: | 
 | 384 |             sys.setcheckinterval(old_interval) | 
 | 385 |  | 
| Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 386 |     def test_no_refcycle_through_target(self): | 
 | 387 |         class RunSelfFunction(object): | 
| Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 388 |             def __init__(self, should_raise): | 
| Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 389 |                 # The links in this refcycle from Thread back to self | 
 | 390 |                 # should be cleaned up when the thread completes. | 
| Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 391 |                 self.should_raise = should_raise | 
| Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 392 |                 self.thread = threading.Thread(target=self._run, | 
 | 393 |                                                args=(self,), | 
 | 394 |                                                kwargs={'yet_another':self}) | 
 | 395 |                 self.thread.start() | 
 | 396 |  | 
 | 397 |             def _run(self, other_ref, yet_another): | 
| Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 398 |                 if self.should_raise: | 
 | 399 |                     raise SystemExit | 
| Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 400 |  | 
| Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 401 |         cyclic_object = RunSelfFunction(should_raise=False) | 
| Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 402 |         weak_cyclic_object = weakref.ref(cyclic_object) | 
 | 403 |         cyclic_object.thread.join() | 
 | 404 |         del cyclic_object | 
| Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 405 |         self.assertEqual(None, weak_cyclic_object(), | 
 | 406 |                          msg=('%d references still around' % | 
 | 407 |                               sys.getrefcount(weak_cyclic_object()))) | 
| Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 408 |  | 
| Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 409 |         raising_cyclic_object = RunSelfFunction(should_raise=True) | 
 | 410 |         weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) | 
 | 411 |         raising_cyclic_object.thread.join() | 
 | 412 |         del raising_cyclic_object | 
| Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 413 |         self.assertEqual(None, weak_raising_cyclic_object(), | 
 | 414 |                          msg=('%d references still around' % | 
 | 415 |                               sys.getrefcount(weak_raising_cyclic_object()))) | 
| Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 416 |  | 
| Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 417 |  | 
| Antoine Pitrou | bb0bb30 | 2009-10-27 20:02:23 +0000 | [diff] [blame] | 418 | class ThreadJoinOnShutdown(BaseTestCase): | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 419 |  | 
| Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 420 |     # Between fork() and exec(), only async-safe functions are allowed (issues | 
 | 421 |     # #12316 and #11870), and fork() from a worker thread is known to trigger | 
 | 422 |     # problems with some operating systems (issue #3863): skip problematic tests | 
 | 423 |     # on platforms known to behave badly. | 
 | 424 |     platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', | 
 | 425 |                          'os2emx') | 
 | 426 |  | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 427 |     def _run_and_join(self, script): | 
 | 428 |         script = """if 1: | 
 | 429 |             import sys, os, time, threading | 
 | 430 |  | 
 | 431 |             # a thread, which waits for the main program to terminate | 
 | 432 |             def joiningfunc(mainthread): | 
 | 433 |                 mainthread.join() | 
 | 434 |                 print 'end of thread' | 
 | 435 |         \n""" + script | 
 | 436 |  | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 437 |         p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) | 
 | 438 |         rc = p.wait() | 
| Benjamin Peterson | f5668f1 | 2008-07-17 12:57:22 +0000 | [diff] [blame] | 439 |         data = p.stdout.read().replace('\r', '') | 
| Brian Curtin | a54bf8b | 2010-11-02 04:04:37 +0000 | [diff] [blame] | 440 |         p.stdout.close() | 
| Benjamin Peterson | f5668f1 | 2008-07-17 12:57:22 +0000 | [diff] [blame] | 441 |         self.assertEqual(data, "end of main\nend of thread\n") | 
| Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 442 |         self.assertFalse(rc == 2, "interpreter was blocked") | 
 | 443 |         self.assertTrue(rc == 0, "Unexpected error") | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 444 |  | 
 | 445 |     def test_1_join_on_shutdown(self): | 
 | 446 |         # The usual case: on exit, wait for a non-daemon thread | 
 | 447 |         script = """if 1: | 
 | 448 |             import os | 
 | 449 |             t = threading.Thread(target=joiningfunc, | 
 | 450 |                                  args=(threading.current_thread(),)) | 
 | 451 |             t.start() | 
 | 452 |             time.sleep(0.1) | 
 | 453 |             print 'end of main' | 
 | 454 |             """ | 
 | 455 |         self._run_and_join(script) | 
 | 456 |  | 
 | 457 |  | 
| Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 458 |     @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") | 
 | 459 |     @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 460 |     def test_2_join_in_forked_process(self): | 
 | 461 |         # Like the test above, but from a forked interpreter | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 462 |         script = """if 1: | 
 | 463 |             childpid = os.fork() | 
 | 464 |             if childpid != 0: | 
 | 465 |                 os.waitpid(childpid, 0) | 
 | 466 |                 sys.exit(0) | 
 | 467 |  | 
 | 468 |             t = threading.Thread(target=joiningfunc, | 
 | 469 |                                  args=(threading.current_thread(),)) | 
 | 470 |             t.start() | 
 | 471 |             print 'end of main' | 
 | 472 |             """ | 
 | 473 |         self._run_and_join(script) | 
 | 474 |  | 
| Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 475 |     @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") | 
 | 476 |     @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 477 |     def test_3_join_in_forked_from_thread(self): | 
 | 478 |         # Like the test above, but fork() was called from a worker thread | 
 | 479 |         # In the forked process, the main Thread object must be marked as stopped. | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 480 |         script = """if 1: | 
 | 481 |             main_thread = threading.current_thread() | 
 | 482 |             def worker(): | 
 | 483 |                 childpid = os.fork() | 
 | 484 |                 if childpid != 0: | 
 | 485 |                     os.waitpid(childpid, 0) | 
 | 486 |                     sys.exit(0) | 
 | 487 |  | 
 | 488 |                 t = threading.Thread(target=joiningfunc, | 
 | 489 |                                      args=(main_thread,)) | 
 | 490 |                 print 'end of main' | 
 | 491 |                 t.start() | 
 | 492 |                 t.join() # Should not block: main_thread is already stopped | 
 | 493 |  | 
 | 494 |             w = threading.Thread(target=worker) | 
 | 495 |             w.start() | 
 | 496 |             """ | 
 | 497 |         self._run_and_join(script) | 
 | 498 |  | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 499 |     def assertScriptHasOutput(self, script, expected_output): | 
 | 500 |         p = subprocess.Popen([sys.executable, "-c", script], | 
 | 501 |                              stdout=subprocess.PIPE) | 
 | 502 |         rc = p.wait() | 
 | 503 |         data = p.stdout.read().decode().replace('\r', '') | 
 | 504 |         self.assertEqual(rc, 0, "Unexpected error") | 
 | 505 |         self.assertEqual(data, expected_output) | 
 | 506 |  | 
 | 507 |     @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") | 
| Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 508 |     @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 509 |     def test_4_joining_across_fork_in_worker_thread(self): | 
 | 510 |         # There used to be a possible deadlock when forking from a child | 
 | 511 |         # thread.  See http://bugs.python.org/issue6643. | 
 | 512 |  | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 513 |         # The script takes the following steps: | 
 | 514 |         # - The main thread in the parent process starts a new thread and then | 
 | 515 |         #   tries to join it. | 
 | 516 |         # - The join operation acquires the Lock inside the thread's _block | 
 | 517 |         #   Condition.  (See threading.py:Thread.join().) | 
 | 518 |         # - We stub out the acquire method on the condition to force it to wait | 
 | 519 |         #   until the child thread forks.  (See LOCK ACQUIRED HERE) | 
 | 520 |         # - The child thread forks.  (See LOCK HELD and WORKER THREAD FORKS | 
 | 521 |         #   HERE) | 
 | 522 |         # - The main thread of the parent process enters Condition.wait(), | 
 | 523 |         #   which releases the lock on the child thread. | 
 | 524 |         # - The child process returns.  Without the necessary fix, when the | 
 | 525 |         #   main thread of the child process (which used to be the child thread | 
 | 526 |         #   in the parent process) attempts to exit, it will try to acquire the | 
 | 527 |         #   lock in the Thread._block Condition object and hang, because the | 
 | 528 |         #   lock was held across the fork. | 
 | 529 |  | 
 | 530 |         script = """if 1: | 
 | 531 |             import os, time, threading | 
 | 532 |  | 
 | 533 |             finish_join = False | 
 | 534 |             start_fork = False | 
 | 535 |  | 
 | 536 |             def worker(): | 
 | 537 |                 # Wait until this thread's lock is acquired before forking to | 
 | 538 |                 # create the deadlock. | 
 | 539 |                 global finish_join | 
 | 540 |                 while not start_fork: | 
 | 541 |                     time.sleep(0.01) | 
 | 542 |                 # LOCK HELD: Main thread holds lock across this call. | 
 | 543 |                 childpid = os.fork() | 
 | 544 |                 finish_join = True | 
 | 545 |                 if childpid != 0: | 
 | 546 |                     # Parent process just waits for child. | 
 | 547 |                     os.waitpid(childpid, 0) | 
 | 548 |                 # Child process should just return. | 
 | 549 |  | 
 | 550 |             w = threading.Thread(target=worker) | 
 | 551 |  | 
 | 552 |             # Stub out the private condition variable's lock acquire method. | 
 | 553 |             # This acquires the lock and then waits until the child has forked | 
 | 554 |             # before returning, which will release the lock soon after.  If | 
 | 555 |             # someone else tries to fix this test case by acquiring this lock | 
| Ezio Melotti | c2077b0 | 2011-03-16 12:34:31 +0200 | [diff] [blame] | 556 |             # before forking instead of resetting it, the test case will | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 557 |             # deadlock when it shouldn't. | 
 | 558 |             condition = w._block | 
 | 559 |             orig_acquire = condition.acquire | 
 | 560 |             call_count_lock = threading.Lock() | 
 | 561 |             call_count = 0 | 
 | 562 |             def my_acquire(): | 
 | 563 |                 global call_count | 
 | 564 |                 global start_fork | 
 | 565 |                 orig_acquire()  # LOCK ACQUIRED HERE | 
 | 566 |                 start_fork = True | 
 | 567 |                 if call_count == 0: | 
 | 568 |                     while not finish_join: | 
 | 569 |                         time.sleep(0.01)  # WORKER THREAD FORKS HERE | 
 | 570 |                 with call_count_lock: | 
 | 571 |                     call_count += 1 | 
 | 572 |             condition.acquire = my_acquire | 
 | 573 |  | 
 | 574 |             w.start() | 
 | 575 |             w.join() | 
 | 576 |             print('end of main') | 
 | 577 |             """ | 
 | 578 |         self.assertScriptHasOutput(script, "end of main\n") | 
 | 579 |  | 
 | 580 |     @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") | 
| Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 581 |     @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 582 |     def test_5_clear_waiter_locks_to_avoid_crash(self): | 
 | 583 |         # Check that a spawned thread that forks doesn't segfault on certain | 
 | 584 |         # platforms, namely OS X.  This used to happen if there was a waiter | 
 | 585 |         # lock in the thread's condition variable's waiters list.  Even though | 
 | 586 |         # we know the lock will be held across the fork, it is not safe to | 
 | 587 |         # release locks held across forks on all platforms, so releasing the | 
 | 588 |         # waiter lock caused a segfault on OS X.  Furthermore, since locks on | 
 | 589 |         # OS X are (as of this writing) implemented with a mutex + condition | 
 | 590 |         # variable instead of a semaphore, while we know that the Python-level | 
 | 591 |         # lock will be acquired, we can't know if the internal mutex will be | 
 | 592 |         # acquired at the time of the fork. | 
 | 593 |  | 
| Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 594 |         script = """if True: | 
 | 595 |             import os, time, threading | 
 | 596 |  | 
 | 597 |             start_fork = False | 
 | 598 |  | 
 | 599 |             def worker(): | 
 | 600 |                 # Wait until the main thread has attempted to join this thread | 
 | 601 |                 # before continuing. | 
 | 602 |                 while not start_fork: | 
 | 603 |                     time.sleep(0.01) | 
 | 604 |                 childpid = os.fork() | 
 | 605 |                 if childpid != 0: | 
 | 606 |                     # Parent process just waits for child. | 
 | 607 |                     (cpid, rc) = os.waitpid(childpid, 0) | 
 | 608 |                     assert cpid == childpid | 
 | 609 |                     assert rc == 0 | 
 | 610 |                     print('end of worker thread') | 
 | 611 |                 else: | 
 | 612 |                     # Child process should just return. | 
 | 613 |                     pass | 
 | 614 |  | 
 | 615 |             w = threading.Thread(target=worker) | 
 | 616 |  | 
 | 617 |             # Stub out the private condition variable's _release_save method. | 
 | 618 |             # This releases the condition's lock and flips the global that | 
 | 619 |             # causes the worker to fork.  At this point, the problematic waiter | 
 | 620 |             # lock has been acquired once by the waiter and has been put onto | 
 | 621 |             # the waiters list. | 
 | 622 |             condition = w._block | 
 | 623 |             orig_release_save = condition._release_save | 
 | 624 |             def my_release_save(): | 
 | 625 |                 global start_fork | 
 | 626 |                 orig_release_save() | 
 | 627 |                 # Waiter lock held here, condition lock released. | 
 | 628 |                 start_fork = True | 
 | 629 |             condition._release_save = my_release_save | 
 | 630 |  | 
 | 631 |             w.start() | 
 | 632 |             w.join() | 
 | 633 |             print('end of main thread') | 
 | 634 |             """ | 
 | 635 |         output = "end of worker thread\nend of main thread\n" | 
 | 636 |         self.assertScriptHasOutput(script, output) | 
 | 637 |  | 
| Charles-François Natali | e0e88b0 | 2012-02-02 19:57:19 +0100 | [diff] [blame^] | 638 |     @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") | 
 | 639 |     def test_reinit_tls_after_fork(self): | 
 | 640 |         # Issue #13817: fork() would deadlock in a multithreaded program with | 
 | 641 |         # the ad-hoc TLS implementation. | 
 | 642 |  | 
 | 643 |         def do_fork_and_wait(): | 
 | 644 |             # just fork a child process and wait it | 
 | 645 |             pid = os.fork() | 
 | 646 |             if pid > 0: | 
 | 647 |                 os.waitpid(pid, 0) | 
 | 648 |             else: | 
 | 649 |                 os._exit(0) | 
 | 650 |  | 
 | 651 |         # start a bunch of threads that will fork() child processes | 
 | 652 |         threads = [] | 
 | 653 |         for i in range(16): | 
 | 654 |             t = threading.Thread(target=do_fork_and_wait) | 
 | 655 |             threads.append(t) | 
 | 656 |             t.start() | 
 | 657 |  | 
 | 658 |         for t in threads: | 
 | 659 |             t.join() | 
 | 660 |  | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 661 |  | 
| Antoine Pitrou | bb0bb30 | 2009-10-27 20:02:23 +0000 | [diff] [blame] | 662 | class ThreadingExceptionTests(BaseTestCase): | 
| Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 663 |     # A RuntimeError should be raised if Thread.start() is called | 
 | 664 |     # multiple times. | 
 | 665 |     def test_start_thread_again(self): | 
 | 666 |         thread = threading.Thread() | 
 | 667 |         thread.start() | 
 | 668 |         self.assertRaises(RuntimeError, thread.start) | 
 | 669 |  | 
| Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 670 |     def test_joining_current_thread(self): | 
| Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 671 |         current_thread = threading.current_thread() | 
 | 672 |         self.assertRaises(RuntimeError, current_thread.join); | 
| Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 673 |  | 
 | 674 |     def test_joining_inactive_thread(self): | 
 | 675 |         thread = threading.Thread() | 
 | 676 |         self.assertRaises(RuntimeError, thread.join) | 
 | 677 |  | 
 | 678 |     def test_daemonize_active_thread(self): | 
 | 679 |         thread = threading.Thread() | 
 | 680 |         thread.start() | 
| Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 681 |         self.assertRaises(RuntimeError, setattr, thread, "daemon", True) | 
| Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 682 |  | 
 | 683 |  | 
| Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 684 | class LockTests(lock_tests.LockTests): | 
 | 685 |     locktype = staticmethod(threading.Lock) | 
 | 686 |  | 
 | 687 | class RLockTests(lock_tests.RLockTests): | 
 | 688 |     locktype = staticmethod(threading.RLock) | 
 | 689 |  | 
 | 690 | class EventTests(lock_tests.EventTests): | 
 | 691 |     eventtype = staticmethod(threading.Event) | 
 | 692 |  | 
 | 693 | class ConditionAsRLockTests(lock_tests.RLockTests): | 
 | 694 |     # An Condition uses an RLock by default and exports its API. | 
 | 695 |     locktype = staticmethod(threading.Condition) | 
 | 696 |  | 
 | 697 | class ConditionTests(lock_tests.ConditionTests): | 
 | 698 |     condtype = staticmethod(threading.Condition) | 
 | 699 |  | 
 | 700 | class SemaphoreTests(lock_tests.SemaphoreTests): | 
 | 701 |     semtype = staticmethod(threading.Semaphore) | 
 | 702 |  | 
 | 703 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): | 
 | 704 |     semtype = staticmethod(threading.BoundedSemaphore) | 
 | 705 |  | 
| Ned Deily | 482f908 | 2011-05-28 00:11:54 -0700 | [diff] [blame] | 706 |     @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem') | 
 | 707 |     def test_recursion_limit(self): | 
 | 708 |         # Issue 9670 | 
 | 709 |         # test that excessive recursion within a non-main thread causes | 
 | 710 |         # an exception rather than crashing the interpreter on platforms | 
 | 711 |         # like Mac OS X or FreeBSD which have small default stack sizes | 
 | 712 |         # for threads | 
 | 713 |         script = """if True: | 
 | 714 |             import threading | 
 | 715 |  | 
 | 716 |             def recurse(): | 
 | 717 |                 return recurse() | 
 | 718 |  | 
 | 719 |             def outer(): | 
 | 720 |                 try: | 
 | 721 |                     recurse() | 
 | 722 |                 except RuntimeError: | 
 | 723 |                     pass | 
 | 724 |  | 
 | 725 |             w = threading.Thread(target=outer) | 
 | 726 |             w.start() | 
 | 727 |             w.join() | 
 | 728 |             print('end of main thread') | 
 | 729 |             """ | 
 | 730 |         expected_output = "end of main thread\n" | 
 | 731 |         p = subprocess.Popen([sys.executable, "-c", script], | 
 | 732 |                              stdout=subprocess.PIPE) | 
 | 733 |         stdout, stderr = p.communicate() | 
 | 734 |         data = stdout.decode().replace('\r', '') | 
 | 735 |         self.assertEqual(p.returncode, 0, "Unexpected error") | 
 | 736 |         self.assertEqual(data, expected_output) | 
| Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 737 |  | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 738 | def test_main(): | 
| Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 739 |     test.test_support.run_unittest(LockTests, RLockTests, EventTests, | 
 | 740 |                                    ConditionAsRLockTests, ConditionTests, | 
 | 741 |                                    SemaphoreTests, BoundedSemaphoreTests, | 
 | 742 |                                    ThreadTests, | 
| Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 743 |                                    ThreadJoinOnShutdown, | 
 | 744 |                                    ThreadingExceptionTests, | 
 | 745 |                                    ) | 
| Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 746 |  | 
 | 747 | if __name__ == "__main__": | 
 | 748 |     test_main() |