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 |
Antoine Pitrou | 52849bf | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 5 | from test.script_helper import assert_python_ok |
| 6 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 7 | import random |
Gregory P. Smith | 8856dda | 2008-06-01 23:48:47 +0000 | [diff] [blame] | 8 | import re |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 9 | import sys |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 10 | thread = test.test_support.import_module('thread') |
| 11 | threading = test.test_support.import_module('threading') |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 12 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 13 | import unittest |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 14 | import weakref |
Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 15 | import os |
| 16 | import subprocess |
Victor Stinner | 66c6e9d | 2013-12-13 02:37:09 +0100 | [diff] [blame^] | 17 | try: |
| 18 | import _testcapi |
| 19 | except ImportError: |
| 20 | _testcapi = None |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 21 | |
Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 22 | from test import lock_tests |
| 23 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 24 | # A trivial mutable counter. |
| 25 | class Counter(object): |
| 26 | def __init__(self): |
| 27 | self.value = 0 |
| 28 | def inc(self): |
| 29 | self.value += 1 |
| 30 | def dec(self): |
| 31 | self.value -= 1 |
| 32 | def get(self): |
| 33 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 34 | |
| 35 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 36 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 37 | threading.Thread.__init__(self, name=name) |
| 38 | self.testcase = testcase |
| 39 | self.sema = sema |
| 40 | self.mutex = mutex |
| 41 | self.nrunning = nrunning |
| 42 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 43 | def run(self): |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 44 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 45 | if verbose: |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 46 | print 'task %s will run for %.1f usec' % ( |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 47 | self.name, delay * 1e6) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 48 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 49 | with self.sema: |
| 50 | with self.mutex: |
| 51 | self.nrunning.inc() |
| 52 | if verbose: |
| 53 | print self.nrunning.get(), 'tasks are running' |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 54 | self.testcase.assertTrue(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 55 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 56 | time.sleep(delay) |
| 57 | if verbose: |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 58 | print 'task', self.name, 'done' |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 59 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 60 | with self.mutex: |
| 61 | self.nrunning.dec() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 62 | self.testcase.assertTrue(self.nrunning.get() >= 0) |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 63 | if verbose: |
| 64 | print '%s is finished. %d tasks are running' % ( |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 65 | self.name, self.nrunning.get()) |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 66 | |
Antoine Pitrou | bb0bb30 | 2009-10-27 20:02:23 +0000 | [diff] [blame] | 67 | class BaseTestCase(unittest.TestCase): |
| 68 | def setUp(self): |
| 69 | self._threads = test.test_support.threading_setup() |
| 70 | |
| 71 | def tearDown(self): |
| 72 | test.test_support.threading_cleanup(*self._threads) |
| 73 | test.test_support.reap_children() |
| 74 | |
| 75 | |
| 76 | class ThreadTests(BaseTestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 77 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 78 | # Create a bunch of threads, let each do some work, wait until all are |
| 79 | # done. |
| 80 | def test_various_ops(self): |
| 81 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 82 | # times about 1 second per clump). |
| 83 | NUMTASKS = 10 |
| 84 | |
| 85 | # no more than 3 of the 10 can run at once |
| 86 | sema = threading.BoundedSemaphore(value=3) |
| 87 | mutex = threading.RLock() |
| 88 | numrunning = Counter() |
| 89 | |
| 90 | threads = [] |
| 91 | |
| 92 | for i in range(NUMTASKS): |
| 93 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 94 | threads.append(t) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 95 | self.assertEqual(t.ident, None) |
| 96 | self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 97 | t.start() |
| 98 | |
| 99 | if verbose: |
| 100 | print 'waiting for all tasks to complete' |
| 101 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 102 | t.join(NUMTASKS) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 103 | self.assertTrue(not t.is_alive()) |
| 104 | self.assertNotEqual(t.ident, 0) |
Benjamin Peterson | d906ea6 | 2009-03-31 21:34:42 +0000 | [diff] [blame] | 105 | self.assertFalse(t.ident is None) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 106 | self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 107 | if verbose: |
| 108 | print 'all tasks done' |
| 109 | self.assertEqual(numrunning.get(), 0) |
| 110 | |
Benjamin Peterson | d906ea6 | 2009-03-31 21:34:42 +0000 | [diff] [blame] | 111 | def test_ident_of_no_threading_threads(self): |
| 112 | # The ident still must work for the main thread and dummy threads. |
| 113 | self.assertFalse(threading.currentThread().ident is None) |
| 114 | def f(): |
| 115 | ident.append(threading.currentThread().ident) |
| 116 | done.set() |
| 117 | done = threading.Event() |
| 118 | ident = [] |
| 119 | thread.start_new_thread(f, ()) |
| 120 | done.wait() |
| 121 | self.assertFalse(ident[0] is None) |
Antoine Pitrou | 0025330 | 2009-11-08 00:24:12 +0000 | [diff] [blame] | 122 | # Kill the "immortal" _DummyThread |
| 123 | del threading._active[ident[0]] |
Benjamin Peterson | d906ea6 | 2009-03-31 21:34:42 +0000 | [diff] [blame] | 124 | |
Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 125 | # run with a small(ish) thread stack size (256kB) |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 126 | def test_various_ops_small_stack(self): |
| 127 | if verbose: |
Andrew MacIntyre | 93e3ecb | 2006-06-13 19:02:35 +0000 | [diff] [blame] | 128 | print 'with 256kB thread stack size...' |
Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 129 | try: |
| 130 | threading.stack_size(262144) |
| 131 | except thread.error: |
Zachary Ware | 1f70221 | 2013-12-10 14:09:20 -0600 | [diff] [blame] | 132 | self.skipTest('platform does not support changing thread stack size') |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 133 | self.test_various_ops() |
| 134 | threading.stack_size(0) |
| 135 | |
| 136 | # run with a large thread stack size (1MB) |
| 137 | def test_various_ops_large_stack(self): |
| 138 | if verbose: |
| 139 | print 'with 1MB thread stack size...' |
Andrew MacIntyre | 16ee33a | 2006-08-06 12:37:03 +0000 | [diff] [blame] | 140 | try: |
| 141 | threading.stack_size(0x100000) |
| 142 | except thread.error: |
Zachary Ware | 1f70221 | 2013-12-10 14:09:20 -0600 | [diff] [blame] | 143 | self.skipTest('platform does not support changing thread stack size') |
Andrew MacIntyre | 9291332 | 2006-06-13 15:04:24 +0000 | [diff] [blame] | 144 | self.test_various_ops() |
| 145 | threading.stack_size(0) |
| 146 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 147 | def test_foreign_thread(self): |
| 148 | # Check that a "foreign" thread can use the threading module. |
| 149 | def f(mutex): |
Antoine Pitrou | d7158d4 | 2009-11-09 16:00:11 +0000 | [diff] [blame] | 150 | # Calling current_thread() forces an entry for the foreign |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 151 | # thread to get made in the threading._active map. |
Antoine Pitrou | d7158d4 | 2009-11-09 16:00:11 +0000 | [diff] [blame] | 152 | threading.current_thread() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 153 | mutex.release() |
| 154 | |
| 155 | mutex = threading.Lock() |
| 156 | mutex.acquire() |
| 157 | tid = thread.start_new_thread(f, (mutex,)) |
| 158 | # Wait for the thread to finish. |
| 159 | mutex.acquire() |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 160 | self.assertIn(tid, threading._active) |
Ezio Melotti | b0f5adc | 2010-01-24 16:58:36 +0000 | [diff] [blame] | 161 | self.assertIsInstance(threading._active[tid], threading._DummyThread) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 162 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 163 | |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 164 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 165 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 166 | def test_PyThreadState_SetAsyncExc(self): |
| 167 | try: |
| 168 | import ctypes |
| 169 | except ImportError: |
Zachary Ware | 1f70221 | 2013-12-10 14:09:20 -0600 | [diff] [blame] | 170 | self.skipTest('requires ctypes') |
Tim Peters | 4643c2f | 2006-08-10 22:45:34 +0000 | [diff] [blame] | 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: |
Zachary Ware | 1f70221 | 2013-12-10 14:09:20 -0600 | [diff] [blame] | 276 | self.skipTest('requires ctypes') |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 277 | |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 278 | rc = subprocess.call([sys.executable, "-c", """if 1: |
| 279 | import ctypes, sys, time, thread |
| 280 | |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 281 | # This lock is used as a simple event variable. |
| 282 | ready = thread.allocate_lock() |
| 283 | ready.acquire() |
| 284 | |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 285 | # Module globals are cleared before __del__ is run |
| 286 | # So we save the functions in class dict |
| 287 | class C: |
| 288 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 289 | release = ctypes.pythonapi.PyGILState_Release |
| 290 | def __del__(self): |
| 291 | state = self.ensure() |
| 292 | self.release(state) |
| 293 | |
| 294 | def waitingThread(): |
| 295 | x = C() |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 296 | ready.release() |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 297 | time.sleep(100) |
| 298 | |
| 299 | thread.start_new_thread(waitingThread, ()) |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 300 | ready.acquire() # Be sure the other thread is waiting. |
Amaury Forgeot d'Arc | 025c347 | 2007-11-29 23:35:25 +0000 | [diff] [blame] | 301 | sys.exit(42) |
| 302 | """]) |
| 303 | self.assertEqual(rc, 42) |
| 304 | |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 305 | def test_finalize_with_trace(self): |
| 306 | # Issue1733757 |
| 307 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 308 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 309 | import sys, threading |
| 310 | |
| 311 | # A deadlock-killer, to prevent the |
| 312 | # testsuite to hang forever |
| 313 | def killer(): |
| 314 | import os, time |
| 315 | time.sleep(2) |
| 316 | print 'program blocked; aborting' |
| 317 | os._exit(2) |
| 318 | t = threading.Thread(target=killer) |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 319 | t.daemon = True |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 320 | t.start() |
| 321 | |
| 322 | # This is the trace function |
| 323 | def func(frame, event, arg): |
Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 324 | threading.current_thread() |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 325 | return func |
| 326 | |
| 327 | sys.settrace(func) |
Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 328 | """], |
| 329 | stdout=subprocess.PIPE, |
| 330 | stderr=subprocess.PIPE) |
Brian Curtin | 51c9b51 | 2010-11-05 17:24:20 +0000 | [diff] [blame] | 331 | self.addCleanup(p.stdout.close) |
| 332 | self.addCleanup(p.stderr.close) |
Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 333 | stdout, stderr = p.communicate() |
| 334 | rc = p.returncode |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 335 | self.assertFalse(rc == 2, "interpreted was blocked") |
Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 336 | self.assertTrue(rc == 0, |
| 337 | "Unexpected error: " + repr(stderr)) |
Amaury Forgeot d'Arc | d7a2651 | 2008-04-03 23:07:55 +0000 | [diff] [blame] | 338 | |
Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 339 | def test_join_nondaemon_on_shutdown(self): |
| 340 | # Issue 1722344 |
| 341 | # Raising SystemExit skipped threading._shutdown |
Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 342 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 343 | import threading |
| 344 | from time import sleep |
| 345 | |
| 346 | def child(): |
| 347 | sleep(1) |
| 348 | # As a non-daemon thread we SHOULD wake up and nothing |
| 349 | # should be torn down yet |
| 350 | print "Woke up, sleep function is:", sleep |
| 351 | |
| 352 | threading.Thread(target=child).start() |
| 353 | raise SystemExit |
| 354 | """], |
| 355 | stdout=subprocess.PIPE, |
| 356 | stderr=subprocess.PIPE) |
Brian Curtin | 51c9b51 | 2010-11-05 17:24:20 +0000 | [diff] [blame] | 357 | self.addCleanup(p.stdout.close) |
| 358 | self.addCleanup(p.stderr.close) |
Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 359 | stdout, stderr = p.communicate() |
Antoine Pitrou | b119ca9 | 2009-10-23 12:01:13 +0000 | [diff] [blame] | 360 | self.assertEqual(stdout.strip(), |
| 361 | "Woke up, sleep function is: <built-in function sleep>") |
Antoine Pitrou | 9bd246b | 2009-10-20 21:59:25 +0000 | [diff] [blame] | 362 | stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip() |
Antoine Pitrou | efb60c0 | 2009-10-20 21:29:37 +0000 | [diff] [blame] | 363 | self.assertEqual(stderr, "") |
| 364 | |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 365 | def test_enumerate_after_join(self): |
| 366 | # Try hard to trigger #1703448: a thread is still returned in |
| 367 | # threading.enumerate() after it has been join()ed. |
| 368 | enum = threading.enumerate |
| 369 | old_interval = sys.getcheckinterval() |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 370 | try: |
Jeffrey Yasskin | 510eab5 | 2008-03-21 18:48:04 +0000 | [diff] [blame] | 371 | for i in xrange(1, 100): |
| 372 | # Try a couple times at each thread-switching interval |
| 373 | # to get more interleavings. |
| 374 | sys.setcheckinterval(i // 5) |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 375 | t = threading.Thread(target=lambda: None) |
| 376 | t.start() |
| 377 | t.join() |
| 378 | l = enum() |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 379 | self.assertNotIn(t, l, |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 380 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 381 | finally: |
| 382 | sys.setcheckinterval(old_interval) |
| 383 | |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 384 | def test_no_refcycle_through_target(self): |
| 385 | class RunSelfFunction(object): |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 386 | def __init__(self, should_raise): |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 387 | # The links in this refcycle from Thread back to self |
| 388 | # should be cleaned up when the thread completes. |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 389 | self.should_raise = should_raise |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 390 | self.thread = threading.Thread(target=self._run, |
| 391 | args=(self,), |
| 392 | kwargs={'yet_another':self}) |
| 393 | self.thread.start() |
| 394 | |
| 395 | def _run(self, other_ref, yet_another): |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 396 | if self.should_raise: |
| 397 | raise SystemExit |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 398 | |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 399 | cyclic_object = RunSelfFunction(should_raise=False) |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 400 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 401 | cyclic_object.thread.join() |
| 402 | del cyclic_object |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 403 | self.assertEqual(None, weak_cyclic_object(), |
| 404 | msg=('%d references still around' % |
| 405 | sys.getrefcount(weak_cyclic_object()))) |
Jeffrey Yasskin | 3414ea9 | 2008-02-23 19:40:54 +0000 | [diff] [blame] | 406 | |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 407 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 408 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 409 | raising_cyclic_object.thread.join() |
| 410 | del raising_cyclic_object |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 411 | self.assertEqual(None, weak_raising_cyclic_object(), |
| 412 | msg=('%d references still around' % |
| 413 | sys.getrefcount(weak_raising_cyclic_object()))) |
Jeffrey Yasskin | a885c15 | 2008-02-23 20:40:35 +0000 | [diff] [blame] | 414 | |
Antoine Pitrou | 52849bf | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 415 | @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()') |
| 416 | def test_dummy_thread_after_fork(self): |
| 417 | # Issue #14308: a dummy thread in the active list doesn't mess up |
| 418 | # the after-fork mechanism. |
| 419 | code = """if 1: |
| 420 | import thread, threading, os, time |
| 421 | |
| 422 | def background_thread(evt): |
| 423 | # Creates and registers the _DummyThread instance |
| 424 | threading.current_thread() |
| 425 | evt.set() |
| 426 | time.sleep(10) |
| 427 | |
| 428 | evt = threading.Event() |
| 429 | thread.start_new_thread(background_thread, (evt,)) |
| 430 | evt.wait() |
| 431 | assert threading.active_count() == 2, threading.active_count() |
| 432 | if os.fork() == 0: |
| 433 | assert threading.active_count() == 1, threading.active_count() |
| 434 | os._exit(0) |
| 435 | else: |
| 436 | os.wait() |
| 437 | """ |
| 438 | _, out, err = assert_python_ok("-c", code) |
| 439 | self.assertEqual(out, '') |
| 440 | self.assertEqual(err, '') |
| 441 | |
Charles-François Natali | 30a5445 | 2013-08-30 23:30:50 +0200 | [diff] [blame] | 442 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 443 | def test_is_alive_after_fork(self): |
| 444 | # Try hard to trigger #18418: is_alive() could sometimes be True on |
| 445 | # threads that vanished after a fork. |
| 446 | old_interval = sys.getcheckinterval() |
| 447 | |
| 448 | # Make the bug more likely to manifest. |
| 449 | sys.setcheckinterval(10) |
| 450 | |
| 451 | try: |
| 452 | for i in range(20): |
| 453 | t = threading.Thread(target=lambda: None) |
| 454 | t.start() |
| 455 | pid = os.fork() |
| 456 | if pid == 0: |
| 457 | os._exit(1 if t.is_alive() else 0) |
| 458 | else: |
| 459 | t.join() |
| 460 | pid, status = os.waitpid(pid, 0) |
| 461 | self.assertEqual(0, status) |
| 462 | finally: |
| 463 | sys.setcheckinterval(old_interval) |
| 464 | |
Tim Peters | 641d621 | 2013-10-08 20:55:51 -0500 | [diff] [blame] | 465 | def test_BoundedSemaphore_limit(self): |
| 466 | # BoundedSemaphore should raise ValueError if released too often. |
| 467 | for limit in range(1, 10): |
| 468 | bs = threading.BoundedSemaphore(limit) |
| 469 | threads = [threading.Thread(target=bs.acquire) |
| 470 | for _ in range(limit)] |
| 471 | for t in threads: |
| 472 | t.start() |
| 473 | for t in threads: |
| 474 | t.join() |
| 475 | threads = [threading.Thread(target=bs.release) |
| 476 | for _ in range(limit)] |
| 477 | for t in threads: |
| 478 | t.start() |
| 479 | for t in threads: |
| 480 | t.join() |
| 481 | self.assertRaises(ValueError, bs.release) |
Gregory P. Smith | 95cd5c0 | 2008-01-22 01:20:42 +0000 | [diff] [blame] | 482 | |
Antoine Pitrou | bb0bb30 | 2009-10-27 20:02:23 +0000 | [diff] [blame] | 483 | class ThreadJoinOnShutdown(BaseTestCase): |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 484 | |
Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 485 | # Between fork() and exec(), only async-safe functions are allowed (issues |
| 486 | # #12316 and #11870), and fork() from a worker thread is known to trigger |
| 487 | # problems with some operating systems (issue #3863): skip problematic tests |
| 488 | # on platforms known to behave badly. |
| 489 | platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', |
| 490 | 'os2emx') |
| 491 | |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 492 | def _run_and_join(self, script): |
| 493 | script = """if 1: |
| 494 | import sys, os, time, threading |
| 495 | |
| 496 | # a thread, which waits for the main program to terminate |
| 497 | def joiningfunc(mainthread): |
| 498 | mainthread.join() |
| 499 | print 'end of thread' |
| 500 | \n""" + script |
| 501 | |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 502 | p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) |
| 503 | rc = p.wait() |
Benjamin Peterson | f5668f1 | 2008-07-17 12:57:22 +0000 | [diff] [blame] | 504 | data = p.stdout.read().replace('\r', '') |
Brian Curtin | a54bf8b | 2010-11-02 04:04:37 +0000 | [diff] [blame] | 505 | p.stdout.close() |
Benjamin Peterson | f5668f1 | 2008-07-17 12:57:22 +0000 | [diff] [blame] | 506 | self.assertEqual(data, "end of main\nend of thread\n") |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 507 | self.assertFalse(rc == 2, "interpreter was blocked") |
| 508 | self.assertTrue(rc == 0, "Unexpected error") |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 509 | |
| 510 | def test_1_join_on_shutdown(self): |
| 511 | # The usual case: on exit, wait for a non-daemon thread |
| 512 | script = """if 1: |
| 513 | import os |
| 514 | t = threading.Thread(target=joiningfunc, |
| 515 | args=(threading.current_thread(),)) |
| 516 | t.start() |
| 517 | time.sleep(0.1) |
| 518 | print 'end of main' |
| 519 | """ |
| 520 | self._run_and_join(script) |
| 521 | |
| 522 | |
Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 523 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 524 | @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] | 525 | def test_2_join_in_forked_process(self): |
| 526 | # Like the test above, but from a forked interpreter |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 527 | script = """if 1: |
| 528 | childpid = os.fork() |
| 529 | if childpid != 0: |
| 530 | os.waitpid(childpid, 0) |
| 531 | sys.exit(0) |
| 532 | |
| 533 | t = threading.Thread(target=joiningfunc, |
| 534 | args=(threading.current_thread(),)) |
| 535 | t.start() |
| 536 | print 'end of main' |
| 537 | """ |
| 538 | self._run_and_join(script) |
| 539 | |
Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 540 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 541 | @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] | 542 | def test_3_join_in_forked_from_thread(self): |
| 543 | # Like the test above, but fork() was called from a worker thread |
| 544 | # 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] | 545 | script = """if 1: |
| 546 | main_thread = threading.current_thread() |
| 547 | def worker(): |
| 548 | childpid = os.fork() |
| 549 | if childpid != 0: |
| 550 | os.waitpid(childpid, 0) |
| 551 | sys.exit(0) |
| 552 | |
| 553 | t = threading.Thread(target=joiningfunc, |
| 554 | args=(main_thread,)) |
| 555 | print 'end of main' |
| 556 | t.start() |
| 557 | t.join() # Should not block: main_thread is already stopped |
| 558 | |
| 559 | w = threading.Thread(target=worker) |
| 560 | w.start() |
| 561 | """ |
| 562 | self._run_and_join(script) |
| 563 | |
Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 564 | def assertScriptHasOutput(self, script, expected_output): |
| 565 | p = subprocess.Popen([sys.executable, "-c", script], |
| 566 | stdout=subprocess.PIPE) |
| 567 | rc = p.wait() |
| 568 | data = p.stdout.read().decode().replace('\r', '') |
| 569 | self.assertEqual(rc, 0, "Unexpected error") |
| 570 | self.assertEqual(data, expected_output) |
| 571 | |
| 572 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 573 | @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] | 574 | def test_4_joining_across_fork_in_worker_thread(self): |
| 575 | # There used to be a possible deadlock when forking from a child |
| 576 | # thread. See http://bugs.python.org/issue6643. |
| 577 | |
Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 578 | # The script takes the following steps: |
| 579 | # - The main thread in the parent process starts a new thread and then |
| 580 | # tries to join it. |
| 581 | # - The join operation acquires the Lock inside the thread's _block |
| 582 | # Condition. (See threading.py:Thread.join().) |
| 583 | # - We stub out the acquire method on the condition to force it to wait |
| 584 | # until the child thread forks. (See LOCK ACQUIRED HERE) |
| 585 | # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS |
| 586 | # HERE) |
| 587 | # - The main thread of the parent process enters Condition.wait(), |
| 588 | # which releases the lock on the child thread. |
| 589 | # - The child process returns. Without the necessary fix, when the |
| 590 | # main thread of the child process (which used to be the child thread |
| 591 | # in the parent process) attempts to exit, it will try to acquire the |
| 592 | # lock in the Thread._block Condition object and hang, because the |
| 593 | # lock was held across the fork. |
| 594 | |
| 595 | script = """if 1: |
| 596 | import os, time, threading |
| 597 | |
| 598 | finish_join = False |
| 599 | start_fork = False |
| 600 | |
| 601 | def worker(): |
| 602 | # Wait until this thread's lock is acquired before forking to |
| 603 | # create the deadlock. |
| 604 | global finish_join |
| 605 | while not start_fork: |
| 606 | time.sleep(0.01) |
| 607 | # LOCK HELD: Main thread holds lock across this call. |
| 608 | childpid = os.fork() |
| 609 | finish_join = True |
| 610 | if childpid != 0: |
| 611 | # Parent process just waits for child. |
| 612 | os.waitpid(childpid, 0) |
| 613 | # Child process should just return. |
| 614 | |
| 615 | w = threading.Thread(target=worker) |
| 616 | |
| 617 | # Stub out the private condition variable's lock acquire method. |
| 618 | # This acquires the lock and then waits until the child has forked |
| 619 | # before returning, which will release the lock soon after. If |
| 620 | # someone else tries to fix this test case by acquiring this lock |
Ezio Melotti | c2077b0 | 2011-03-16 12:34:31 +0200 | [diff] [blame] | 621 | # before forking instead of resetting it, the test case will |
Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 622 | # deadlock when it shouldn't. |
| 623 | condition = w._block |
| 624 | orig_acquire = condition.acquire |
| 625 | call_count_lock = threading.Lock() |
| 626 | call_count = 0 |
| 627 | def my_acquire(): |
| 628 | global call_count |
| 629 | global start_fork |
| 630 | orig_acquire() # LOCK ACQUIRED HERE |
| 631 | start_fork = True |
| 632 | if call_count == 0: |
| 633 | while not finish_join: |
| 634 | time.sleep(0.01) # WORKER THREAD FORKS HERE |
| 635 | with call_count_lock: |
| 636 | call_count += 1 |
| 637 | condition.acquire = my_acquire |
| 638 | |
| 639 | w.start() |
| 640 | w.join() |
| 641 | print('end of main') |
| 642 | """ |
| 643 | self.assertScriptHasOutput(script, "end of main\n") |
| 644 | |
| 645 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 041d2e1 | 2011-07-01 15:04:03 +0200 | [diff] [blame] | 646 | @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] | 647 | def test_5_clear_waiter_locks_to_avoid_crash(self): |
| 648 | # Check that a spawned thread that forks doesn't segfault on certain |
| 649 | # platforms, namely OS X. This used to happen if there was a waiter |
| 650 | # lock in the thread's condition variable's waiters list. Even though |
| 651 | # we know the lock will be held across the fork, it is not safe to |
| 652 | # release locks held across forks on all platforms, so releasing the |
| 653 | # waiter lock caused a segfault on OS X. Furthermore, since locks on |
| 654 | # OS X are (as of this writing) implemented with a mutex + condition |
| 655 | # variable instead of a semaphore, while we know that the Python-level |
| 656 | # lock will be acquired, we can't know if the internal mutex will be |
| 657 | # acquired at the time of the fork. |
| 658 | |
Gregory P. Smith | 2b79a81 | 2011-01-04 01:10:08 +0000 | [diff] [blame] | 659 | script = """if True: |
| 660 | import os, time, threading |
| 661 | |
| 662 | start_fork = False |
| 663 | |
| 664 | def worker(): |
| 665 | # Wait until the main thread has attempted to join this thread |
| 666 | # before continuing. |
| 667 | while not start_fork: |
| 668 | time.sleep(0.01) |
| 669 | childpid = os.fork() |
| 670 | if childpid != 0: |
| 671 | # Parent process just waits for child. |
| 672 | (cpid, rc) = os.waitpid(childpid, 0) |
| 673 | assert cpid == childpid |
| 674 | assert rc == 0 |
| 675 | print('end of worker thread') |
| 676 | else: |
| 677 | # Child process should just return. |
| 678 | pass |
| 679 | |
| 680 | w = threading.Thread(target=worker) |
| 681 | |
| 682 | # Stub out the private condition variable's _release_save method. |
| 683 | # This releases the condition's lock and flips the global that |
| 684 | # causes the worker to fork. At this point, the problematic waiter |
| 685 | # lock has been acquired once by the waiter and has been put onto |
| 686 | # the waiters list. |
| 687 | condition = w._block |
| 688 | orig_release_save = condition._release_save |
| 689 | def my_release_save(): |
| 690 | global start_fork |
| 691 | orig_release_save() |
| 692 | # Waiter lock held here, condition lock released. |
| 693 | start_fork = True |
| 694 | condition._release_save = my_release_save |
| 695 | |
| 696 | w.start() |
| 697 | w.join() |
| 698 | print('end of main thread') |
| 699 | """ |
| 700 | output = "end of worker thread\nend of main thread\n" |
| 701 | self.assertScriptHasOutput(script, output) |
| 702 | |
Charles-François Natali | e0e88b0 | 2012-02-02 19:57:19 +0100 | [diff] [blame] | 703 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Charles-François Natali | ebf691d | 2012-02-08 21:27:56 +0100 | [diff] [blame] | 704 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Charles-François Natali | e0e88b0 | 2012-02-02 19:57:19 +0100 | [diff] [blame] | 705 | def test_reinit_tls_after_fork(self): |
| 706 | # Issue #13817: fork() would deadlock in a multithreaded program with |
| 707 | # the ad-hoc TLS implementation. |
| 708 | |
| 709 | def do_fork_and_wait(): |
| 710 | # just fork a child process and wait it |
| 711 | pid = os.fork() |
| 712 | if pid > 0: |
| 713 | os.waitpid(pid, 0) |
| 714 | else: |
| 715 | os._exit(0) |
| 716 | |
| 717 | # start a bunch of threads that will fork() child processes |
| 718 | threads = [] |
| 719 | for i in range(16): |
| 720 | t = threading.Thread(target=do_fork_and_wait) |
| 721 | threads.append(t) |
| 722 | t.start() |
| 723 | |
| 724 | for t in threads: |
| 725 | t.join() |
| 726 | |
Victor Stinner | 66c6e9d | 2013-12-13 02:37:09 +0100 | [diff] [blame^] | 727 | @unittest.skipIf(_testcapi is None, "need _testcapi module") |
| 728 | def test_frame_tstate_tracing(self): |
| 729 | # Issue #14432: Crash when a generator is created in a C thread that is |
| 730 | # destroyed while the generator is still used. The issue was that a |
| 731 | # generator contains a frame, and the frame kept a reference to the |
| 732 | # Python state of the destroyed C thread. The crash occurs when a trace |
| 733 | # function is setup. |
| 734 | |
| 735 | def noop_trace(frame, event, arg): |
| 736 | # no operation |
| 737 | return noop_trace |
| 738 | |
| 739 | def generator(): |
| 740 | while 1: |
| 741 | yield "genereator" |
| 742 | |
| 743 | def callback(): |
| 744 | if callback.gen is None: |
| 745 | callback.gen = generator() |
| 746 | return next(callback.gen) |
| 747 | callback.gen = None |
| 748 | |
| 749 | old_trace = sys.gettrace() |
| 750 | sys.settrace(noop_trace) |
| 751 | try: |
| 752 | # Install a trace function |
| 753 | threading.settrace(noop_trace) |
| 754 | |
| 755 | # Create a generator in a C thread which exits after the call |
| 756 | _testcapi.call_in_temporary_c_thread(callback) |
| 757 | |
| 758 | # Call the generator in a different Python thread, check that the |
| 759 | # generator didn't keep a reference to the destroyed thread state |
| 760 | for test in range(3): |
| 761 | # The trace function is still called here |
| 762 | callback() |
| 763 | finally: |
| 764 | sys.settrace(old_trace) |
| 765 | |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 766 | |
Antoine Pitrou | bb0bb30 | 2009-10-27 20:02:23 +0000 | [diff] [blame] | 767 | class ThreadingExceptionTests(BaseTestCase): |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 768 | # A RuntimeError should be raised if Thread.start() is called |
| 769 | # multiple times. |
| 770 | def test_start_thread_again(self): |
| 771 | thread = threading.Thread() |
| 772 | thread.start() |
| 773 | self.assertRaises(RuntimeError, thread.start) |
| 774 | |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 775 | def test_joining_current_thread(self): |
Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 776 | current_thread = threading.current_thread() |
| 777 | self.assertRaises(RuntimeError, current_thread.join); |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 778 | |
| 779 | def test_joining_inactive_thread(self): |
| 780 | thread = threading.Thread() |
| 781 | self.assertRaises(RuntimeError, thread.join) |
| 782 | |
| 783 | def test_daemonize_active_thread(self): |
| 784 | thread = threading.Thread() |
| 785 | thread.start() |
Benjamin Peterson | cbae869 | 2008-08-18 17:45:09 +0000 | [diff] [blame] | 786 | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
Collin Winter | 50b79ce | 2007-06-06 00:17:35 +0000 | [diff] [blame] | 787 | |
| 788 | |
Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 789 | class LockTests(lock_tests.LockTests): |
| 790 | locktype = staticmethod(threading.Lock) |
| 791 | |
| 792 | class RLockTests(lock_tests.RLockTests): |
| 793 | locktype = staticmethod(threading.RLock) |
| 794 | |
| 795 | class EventTests(lock_tests.EventTests): |
| 796 | eventtype = staticmethod(threading.Event) |
| 797 | |
| 798 | class ConditionAsRLockTests(lock_tests.RLockTests): |
| 799 | # An Condition uses an RLock by default and exports its API. |
| 800 | locktype = staticmethod(threading.Condition) |
| 801 | |
| 802 | class ConditionTests(lock_tests.ConditionTests): |
| 803 | condtype = staticmethod(threading.Condition) |
| 804 | |
| 805 | class SemaphoreTests(lock_tests.SemaphoreTests): |
| 806 | semtype = staticmethod(threading.Semaphore) |
| 807 | |
| 808 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
| 809 | semtype = staticmethod(threading.BoundedSemaphore) |
| 810 | |
Ned Deily | 482f908 | 2011-05-28 00:11:54 -0700 | [diff] [blame] | 811 | @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem') |
| 812 | def test_recursion_limit(self): |
| 813 | # Issue 9670 |
| 814 | # test that excessive recursion within a non-main thread causes |
| 815 | # an exception rather than crashing the interpreter on platforms |
| 816 | # like Mac OS X or FreeBSD which have small default stack sizes |
| 817 | # for threads |
| 818 | script = """if True: |
| 819 | import threading |
| 820 | |
| 821 | def recurse(): |
| 822 | return recurse() |
| 823 | |
| 824 | def outer(): |
| 825 | try: |
| 826 | recurse() |
| 827 | except RuntimeError: |
| 828 | pass |
| 829 | |
| 830 | w = threading.Thread(target=outer) |
| 831 | w.start() |
| 832 | w.join() |
| 833 | print('end of main thread') |
| 834 | """ |
| 835 | expected_output = "end of main thread\n" |
| 836 | p = subprocess.Popen([sys.executable, "-c", script], |
| 837 | stdout=subprocess.PIPE) |
| 838 | stdout, stderr = p.communicate() |
| 839 | data = stdout.decode().replace('\r', '') |
| 840 | self.assertEqual(p.returncode, 0, "Unexpected error") |
| 841 | self.assertEqual(data, expected_output) |
Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 842 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 843 | def test_main(): |
Antoine Pitrou | c98efe0 | 2009-11-06 22:34:35 +0000 | [diff] [blame] | 844 | test.test_support.run_unittest(LockTests, RLockTests, EventTests, |
| 845 | ConditionAsRLockTests, ConditionTests, |
| 846 | SemaphoreTests, BoundedSemaphoreTests, |
| 847 | ThreadTests, |
Jesse Noller | 5e62ca4 | 2008-07-16 20:03:47 +0000 | [diff] [blame] | 848 | ThreadJoinOnShutdown, |
| 849 | ThreadingExceptionTests, |
| 850 | ) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 851 | |
| 852 | if __name__ == "__main__": |
| 853 | test_main() |