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