Antoine Pitrou | 4c8ce84 | 2013-09-01 19:51:49 +0200 | [diff] [blame] | 1 | """ |
| 2 | Tests for the threading module. |
| 3 | """ |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 4 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 5 | import test.support |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 6 | from test.support import verbose, strip_python_stderr, import_module |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 7 | from test.script_helper import assert_python_ok |
| 8 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 9 | import random |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 10 | import re |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 11 | import sys |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 12 | _thread = import_module('_thread') |
| 13 | threading = import_module('threading') |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 14 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 15 | import unittest |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 16 | import weakref |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 17 | import os |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 18 | from test.script_helper import assert_python_ok, assert_python_failure |
Gregory P. Smith | 4b129d2 | 2011-01-04 00:51:50 +0000 | [diff] [blame] | 19 | import subprocess |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 20 | |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 21 | from test import lock_tests |
| 22 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 23 | # A trivial mutable counter. |
| 24 | class Counter(object): |
| 25 | def __init__(self): |
| 26 | self.value = 0 |
| 27 | def inc(self): |
| 28 | self.value += 1 |
| 29 | def dec(self): |
| 30 | self.value -= 1 |
| 31 | def get(self): |
| 32 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 33 | |
| 34 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 35 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 36 | threading.Thread.__init__(self, name=name) |
| 37 | self.testcase = testcase |
| 38 | self.sema = sema |
| 39 | self.mutex = mutex |
| 40 | self.nrunning = nrunning |
| 41 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 42 | def run(self): |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 43 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 44 | if verbose: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 45 | print('task %s will run for %.1f usec' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 46 | (self.name, delay * 1e6)) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 47 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 48 | with self.sema: |
| 49 | with self.mutex: |
| 50 | self.nrunning.inc() |
| 51 | if verbose: |
| 52 | print(self.nrunning.get(), 'tasks are running') |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 53 | self.testcase.assertTrue(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 54 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 55 | time.sleep(delay) |
| 56 | if verbose: |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 57 | print('task', self.name, 'done') |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 58 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 59 | with self.mutex: |
| 60 | self.nrunning.dec() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 61 | self.testcase.assertTrue(self.nrunning.get() >= 0) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 62 | if verbose: |
| 63 | print('%s is finished. %d tasks are running' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 64 | (self.name, self.nrunning.get())) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 65 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 66 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 67 | class BaseTestCase(unittest.TestCase): |
| 68 | def setUp(self): |
| 69 | self._threads = test.support.threading_setup() |
| 70 | |
| 71 | def tearDown(self): |
| 72 | test.support.threading_cleanup(*self._threads) |
| 73 | 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 | c9c0f20 | 2009-06-30 23:06:06 +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: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 100 | print('waiting for all tasks to complete') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 101 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 102 | t.join(NUMTASKS) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 103 | self.assertTrue(not t.is_alive()) |
| 104 | self.assertNotEqual(t.ident, 0) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 105 | self.assertFalse(t.ident is None) |
Brett Cannon | 3f5f226 | 2010-07-23 15:50:52 +0000 | [diff] [blame] | 106 | self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>', |
| 107 | repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 108 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 109 | print('all tasks done') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 110 | self.assertEqual(numrunning.get(), 0) |
| 111 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 112 | def test_ident_of_no_threading_threads(self): |
| 113 | # The ident still must work for the main thread and dummy threads. |
| 114 | self.assertFalse(threading.currentThread().ident is None) |
| 115 | def f(): |
| 116 | ident.append(threading.currentThread().ident) |
| 117 | done.set() |
| 118 | done = threading.Event() |
| 119 | ident = [] |
| 120 | _thread.start_new_thread(f, ()) |
| 121 | done.wait() |
| 122 | self.assertFalse(ident[0] is None) |
Antoine Pitrou | ca13a0d | 2009-11-08 00:30:04 +0000 | [diff] [blame] | 123 | # Kill the "immortal" _DummyThread |
| 124 | del threading._active[ident[0]] |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 125 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 126 | # run with a small(ish) thread stack size (256kB) |
| 127 | def test_various_ops_small_stack(self): |
| 128 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 129 | print('with 256kB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 130 | try: |
| 131 | threading.stack_size(262144) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 132 | except _thread.error: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 133 | raise unittest.SkipTest( |
| 134 | 'platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 135 | self.test_various_ops() |
| 136 | threading.stack_size(0) |
| 137 | |
| 138 | # run with a large thread stack size (1MB) |
| 139 | def test_various_ops_large_stack(self): |
| 140 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 141 | print('with 1MB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 142 | try: |
| 143 | threading.stack_size(0x100000) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 144 | except _thread.error: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 145 | raise unittest.SkipTest( |
| 146 | 'platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 147 | self.test_various_ops() |
| 148 | threading.stack_size(0) |
| 149 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 150 | def test_foreign_thread(self): |
| 151 | # Check that a "foreign" thread can use the threading module. |
| 152 | def f(mutex): |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 153 | # Calling current_thread() forces an entry for the foreign |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 154 | # thread to get made in the threading._active map. |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 155 | threading.current_thread() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 156 | mutex.release() |
| 157 | |
| 158 | mutex = threading.Lock() |
| 159 | mutex.acquire() |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 160 | tid = _thread.start_new_thread(f, (mutex,)) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 161 | # Wait for the thread to finish. |
| 162 | mutex.acquire() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 163 | self.assertIn(tid, threading._active) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 164 | self.assertIsInstance(threading._active[tid], threading._DummyThread) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 165 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 166 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 167 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 168 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 169 | def test_PyThreadState_SetAsyncExc(self): |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 170 | ctypes = import_module("ctypes") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +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 | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 179 | # First check it works when setting the exception from the same thread. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 180 | tid = threading.get_ident() |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 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: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +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 | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 193 | self.fail("AsyncExc not raised") |
| 194 | try: |
| 195 | self.assertEqual(result, 1) # one thread state modified |
| 196 | except UnboundLocalError: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 197 | # The exception was raised too quickly for us to get the result. |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 198 | pass |
| 199 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +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): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 209 | self.id = threading.get_ident() |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 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 | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 221 | t.daemon = True # so if this fails, we don't hang Python at shutdown |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 222 | t.start() |
| 223 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 224 | print(" started worker thread") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 225 | |
| 226 | # Try a thread id that doesn't make sense. |
| 227 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 228 | print(" trying nonsensical thread id") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 229 | result = set_async_exc(ctypes.c_long(-1), exception) |
| 230 | self.assertEqual(result, 0) # no thread states modified |
| 231 | |
| 232 | # Now raise an exception in the worker thread. |
| 233 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 234 | print(" waiting for worker thread to get started") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 235 | ret = worker_started.wait() |
| 236 | self.assertTrue(ret) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 237 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 238 | print(" verifying worker hasn't exited") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 239 | self.assertTrue(not t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 240 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 241 | print(" attempting to raise asynch exception in worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 242 | result = set_async_exc(ctypes.c_long(t.id), exception) |
| 243 | self.assertEqual(result, 1) # one thread state modified |
| 244 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 245 | print(" waiting for worker to say it caught the exception") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 246 | worker_saw_exception.wait(timeout=10) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 247 | self.assertTrue(t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 248 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 249 | print(" all OK -- joining worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 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 | 3fdd964 | 2010-02-28 18:57:46 +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 threading.ThreadError() |
| 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 | f50f168 | 2010-03-01 03:13:36 +0000 | [diff] [blame] | 262 | self.assertRaises(threading.ThreadError, t.start) |
| 263 | self.assertFalse( |
| 264 | t in threading._limbo, |
| 265 | "Failed to cleanup _limbo map on failure of Thread.start().") |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 266 | finally: |
| 267 | threading._start_new_thread = _start_new_thread |
| 268 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +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. |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 273 | import_module("ctypes") |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 274 | |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 275 | rc, out, err = assert_python_failure("-c", """if 1: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 276 | import ctypes, sys, time, _thread |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 277 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 278 | # This lock is used as a simple event variable. |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 279 | ready = _thread.allocate_lock() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 280 | ready.acquire() |
| 281 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 282 | # Module globals are cleared before __del__ is run |
| 283 | # So we save the functions in class dict |
| 284 | class C: |
| 285 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 286 | release = ctypes.pythonapi.PyGILState_Release |
| 287 | def __del__(self): |
| 288 | state = self.ensure() |
| 289 | self.release(state) |
| 290 | |
| 291 | def waitingThread(): |
| 292 | x = C() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 293 | ready.release() |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 294 | time.sleep(100) |
| 295 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 296 | _thread.start_new_thread(waitingThread, ()) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 297 | ready.acquire() # Be sure the other thread is waiting. |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 298 | sys.exit(42) |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 299 | """) |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 300 | self.assertEqual(rc, 42) |
| 301 | |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 302 | def test_finalize_with_trace(self): |
| 303 | # Issue1733757 |
| 304 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 305 | assert_python_ok("-c", """if 1: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 306 | import sys, threading |
| 307 | |
| 308 | # A deadlock-killer, to prevent the |
| 309 | # testsuite to hang forever |
| 310 | def killer(): |
| 311 | import os, time |
| 312 | time.sleep(2) |
| 313 | print('program blocked; aborting') |
| 314 | os._exit(2) |
| 315 | t = threading.Thread(target=killer) |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 316 | t.daemon = True |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 317 | t.start() |
| 318 | |
| 319 | # This is the trace function |
| 320 | def func(frame, event, arg): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 321 | threading.current_thread() |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 322 | return func |
| 323 | |
| 324 | sys.settrace(func) |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 325 | """) |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 326 | |
Antoine Pitrou | 011bd62 | 2009-10-20 21:52:47 +0000 | [diff] [blame] | 327 | def test_join_nondaemon_on_shutdown(self): |
| 328 | # Issue 1722344 |
| 329 | # Raising SystemExit skipped threading._shutdown |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 330 | rc, out, err = assert_python_ok("-c", """if 1: |
Antoine Pitrou | 011bd62 | 2009-10-20 21:52:47 +0000 | [diff] [blame] | 331 | import threading |
| 332 | from time import sleep |
| 333 | |
| 334 | def child(): |
| 335 | sleep(1) |
| 336 | # As a non-daemon thread we SHOULD wake up and nothing |
| 337 | # should be torn down yet |
| 338 | print("Woke up, sleep function is:", sleep) |
| 339 | |
| 340 | threading.Thread(target=child).start() |
| 341 | raise SystemExit |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 342 | """) |
| 343 | self.assertEqual(out.strip(), |
Antoine Pitrou | 899d1c6 | 2009-10-23 21:55:36 +0000 | [diff] [blame] | 344 | b"Woke up, sleep function is: <built-in function sleep>") |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 345 | self.assertEqual(err, b"") |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 346 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 347 | def test_enumerate_after_join(self): |
| 348 | # Try hard to trigger #1703448: a thread is still returned in |
| 349 | # threading.enumerate() after it has been join()ed. |
| 350 | enum = threading.enumerate |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 351 | old_interval = sys.getswitchinterval() |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 352 | try: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 353 | for i in range(1, 100): |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 354 | sys.setswitchinterval(i * 0.0002) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 355 | t = threading.Thread(target=lambda: None) |
| 356 | t.start() |
| 357 | t.join() |
| 358 | l = enum() |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 359 | self.assertNotIn(t, l, |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 360 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 361 | finally: |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 362 | sys.setswitchinterval(old_interval) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 363 | |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 364 | def test_no_refcycle_through_target(self): |
| 365 | class RunSelfFunction(object): |
| 366 | def __init__(self, should_raise): |
| 367 | # The links in this refcycle from Thread back to self |
| 368 | # should be cleaned up when the thread completes. |
| 369 | self.should_raise = should_raise |
| 370 | self.thread = threading.Thread(target=self._run, |
| 371 | args=(self,), |
| 372 | kwargs={'yet_another':self}) |
| 373 | self.thread.start() |
| 374 | |
| 375 | def _run(self, other_ref, yet_another): |
| 376 | if self.should_raise: |
| 377 | raise SystemExit |
| 378 | |
| 379 | cyclic_object = RunSelfFunction(should_raise=False) |
| 380 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 381 | cyclic_object.thread.join() |
| 382 | del cyclic_object |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 383 | self.assertIsNone(weak_cyclic_object(), |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 384 | msg=('%d references still around' % |
| 385 | sys.getrefcount(weak_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 386 | |
| 387 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 388 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 389 | raising_cyclic_object.thread.join() |
| 390 | del raising_cyclic_object |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 391 | self.assertIsNone(weak_raising_cyclic_object(), |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 392 | msg=('%d references still around' % |
| 393 | sys.getrefcount(weak_raising_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 394 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 395 | def test_old_threading_api(self): |
| 396 | # Just a quick sanity check to make sure the old method names are |
| 397 | # still present |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 398 | t = threading.Thread() |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 399 | t.isDaemon() |
| 400 | t.setDaemon(True) |
| 401 | t.getName() |
| 402 | t.setName("name") |
| 403 | t.isAlive() |
| 404 | e = threading.Event() |
| 405 | e.isSet() |
| 406 | threading.activeCount() |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 407 | |
Brian Curtin | 81a4a6a | 2010-07-23 16:30:10 +0000 | [diff] [blame] | 408 | def test_repr_daemon(self): |
| 409 | t = threading.Thread() |
| 410 | self.assertFalse('daemon' in repr(t)) |
| 411 | t.daemon = True |
| 412 | self.assertTrue('daemon' in repr(t)) |
Brett Cannon | 3f5f226 | 2010-07-23 15:50:52 +0000 | [diff] [blame] | 413 | |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 414 | def test_deamon_param(self): |
| 415 | t = threading.Thread() |
| 416 | self.assertFalse(t.daemon) |
| 417 | t = threading.Thread(daemon=False) |
| 418 | self.assertFalse(t.daemon) |
| 419 | t = threading.Thread(daemon=True) |
| 420 | self.assertTrue(t.daemon) |
| 421 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 422 | @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()') |
| 423 | def test_dummy_thread_after_fork(self): |
| 424 | # Issue #14308: a dummy thread in the active list doesn't mess up |
| 425 | # the after-fork mechanism. |
| 426 | code = """if 1: |
| 427 | import _thread, threading, os, time |
| 428 | |
| 429 | def background_thread(evt): |
| 430 | # Creates and registers the _DummyThread instance |
| 431 | threading.current_thread() |
| 432 | evt.set() |
| 433 | time.sleep(10) |
| 434 | |
| 435 | evt = threading.Event() |
| 436 | _thread.start_new_thread(background_thread, (evt,)) |
| 437 | evt.wait() |
| 438 | assert threading.active_count() == 2, threading.active_count() |
| 439 | if os.fork() == 0: |
| 440 | assert threading.active_count() == 1, threading.active_count() |
| 441 | os._exit(0) |
| 442 | else: |
| 443 | os.wait() |
| 444 | """ |
| 445 | _, out, err = assert_python_ok("-c", code) |
| 446 | self.assertEqual(out, b'') |
| 447 | self.assertEqual(err, b'') |
| 448 | |
Charles-François Natali | 9939cc8 | 2013-08-30 23:32:53 +0200 | [diff] [blame] | 449 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 450 | def test_is_alive_after_fork(self): |
| 451 | # Try hard to trigger #18418: is_alive() could sometimes be True on |
| 452 | # threads that vanished after a fork. |
| 453 | old_interval = sys.getswitchinterval() |
| 454 | self.addCleanup(sys.setswitchinterval, old_interval) |
| 455 | |
| 456 | # Make the bug more likely to manifest. |
| 457 | sys.setswitchinterval(1e-6) |
| 458 | |
| 459 | for i in range(20): |
| 460 | t = threading.Thread(target=lambda: None) |
| 461 | t.start() |
| 462 | self.addCleanup(t.join) |
| 463 | pid = os.fork() |
| 464 | if pid == 0: |
| 465 | os._exit(1 if t.is_alive() else 0) |
| 466 | else: |
| 467 | pid, status = os.waitpid(pid, 0) |
| 468 | self.assertEqual(0, status) |
| 469 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 470 | |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame^] | 471 | def test_BoundedSemaphore_limit(self): |
| 472 | # BoundedSemaphore should raise ValueError if released too often. |
| 473 | for limit in range(1, 10): |
| 474 | bs = threading.BoundedSemaphore(limit) |
| 475 | threads = [threading.Thread(target=bs.acquire) |
| 476 | for _ in range(limit)] |
| 477 | for t in threads: |
| 478 | t.start() |
| 479 | for t in threads: |
| 480 | t.join() |
| 481 | threads = [threading.Thread(target=bs.release) |
| 482 | for _ in range(limit)] |
| 483 | for t in threads: |
| 484 | t.start() |
| 485 | for t in threads: |
| 486 | t.join() |
| 487 | self.assertRaises(ValueError, bs.release) |
| 488 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 489 | class ThreadJoinOnShutdown(BaseTestCase): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 490 | |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 491 | # Between fork() and exec(), only async-safe functions are allowed (issues |
| 492 | # #12316 and #11870), and fork() from a worker thread is known to trigger |
| 493 | # problems with some operating systems (issue #3863): skip problematic tests |
| 494 | # on platforms known to behave badly. |
| 495 | platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', |
Stefan Krah | fc4aa76 | 2013-01-17 23:29:54 +0100 | [diff] [blame] | 496 | 'os2emx', 'hp-ux11') |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 497 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 498 | def _run_and_join(self, script): |
| 499 | script = """if 1: |
| 500 | import sys, os, time, threading |
| 501 | |
| 502 | # a thread, which waits for the main program to terminate |
| 503 | def joiningfunc(mainthread): |
| 504 | mainthread.join() |
| 505 | print('end of thread') |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 506 | # stdout is fully buffered because not a tty, we have to flush |
| 507 | # before exit. |
| 508 | sys.stdout.flush() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 509 | \n""" + script |
| 510 | |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 511 | rc, out, err = assert_python_ok("-c", script) |
| 512 | data = out.decode().replace('\r', '') |
Benjamin Peterson | ad703dc | 2008-07-17 17:02:57 +0000 | [diff] [blame] | 513 | self.assertEqual(data, "end of main\nend of thread\n") |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 514 | |
| 515 | def test_1_join_on_shutdown(self): |
| 516 | # The usual case: on exit, wait for a non-daemon thread |
| 517 | script = """if 1: |
| 518 | import os |
| 519 | t = threading.Thread(target=joiningfunc, |
| 520 | args=(threading.current_thread(),)) |
| 521 | t.start() |
| 522 | time.sleep(0.1) |
| 523 | print('end of main') |
| 524 | """ |
| 525 | self._run_and_join(script) |
| 526 | |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 527 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 528 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 529 | def test_2_join_in_forked_process(self): |
| 530 | # Like the test above, but from a forked interpreter |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 531 | script = """if 1: |
| 532 | childpid = os.fork() |
| 533 | if childpid != 0: |
| 534 | os.waitpid(childpid, 0) |
| 535 | sys.exit(0) |
| 536 | |
| 537 | t = threading.Thread(target=joiningfunc, |
| 538 | args=(threading.current_thread(),)) |
| 539 | t.start() |
| 540 | print('end of main') |
| 541 | """ |
| 542 | self._run_and_join(script) |
| 543 | |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 544 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 545 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 546 | def test_3_join_in_forked_from_thread(self): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 547 | # Like the test above, but fork() was called from a worker thread |
| 548 | # In the forked process, the main Thread object must be marked as stopped. |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 549 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 550 | script = """if 1: |
| 551 | main_thread = threading.current_thread() |
| 552 | def worker(): |
| 553 | childpid = os.fork() |
| 554 | if childpid != 0: |
| 555 | os.waitpid(childpid, 0) |
| 556 | sys.exit(0) |
| 557 | |
| 558 | t = threading.Thread(target=joiningfunc, |
| 559 | args=(main_thread,)) |
| 560 | print('end of main') |
| 561 | t.start() |
| 562 | t.join() # Should not block: main_thread is already stopped |
| 563 | |
| 564 | w = threading.Thread(target=worker) |
| 565 | w.start() |
| 566 | """ |
| 567 | self._run_and_join(script) |
| 568 | |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 569 | def assertScriptHasOutput(self, script, expected_output): |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 570 | rc, out, err = assert_python_ok("-c", script) |
| 571 | data = out.decode().replace('\r', '') |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 572 | self.assertEqual(data, expected_output) |
| 573 | |
| 574 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 575 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 576 | def test_4_joining_across_fork_in_worker_thread(self): |
| 577 | # There used to be a possible deadlock when forking from a child |
| 578 | # thread. See http://bugs.python.org/issue6643. |
| 579 | |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 580 | # The script takes the following steps: |
| 581 | # - The main thread in the parent process starts a new thread and then |
| 582 | # tries to join it. |
| 583 | # - The join operation acquires the Lock inside the thread's _block |
| 584 | # Condition. (See threading.py:Thread.join().) |
| 585 | # - We stub out the acquire method on the condition to force it to wait |
| 586 | # until the child thread forks. (See LOCK ACQUIRED HERE) |
| 587 | # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS |
| 588 | # HERE) |
| 589 | # - The main thread of the parent process enters Condition.wait(), |
| 590 | # which releases the lock on the child thread. |
| 591 | # - The child process returns. Without the necessary fix, when the |
| 592 | # main thread of the child process (which used to be the child thread |
| 593 | # in the parent process) attempts to exit, it will try to acquire the |
| 594 | # lock in the Thread._block Condition object and hang, because the |
| 595 | # lock was held across the fork. |
| 596 | |
| 597 | script = """if 1: |
| 598 | import os, time, threading |
| 599 | |
| 600 | finish_join = False |
| 601 | start_fork = False |
| 602 | |
| 603 | def worker(): |
| 604 | # Wait until this thread's lock is acquired before forking to |
| 605 | # create the deadlock. |
| 606 | global finish_join |
| 607 | while not start_fork: |
| 608 | time.sleep(0.01) |
| 609 | # LOCK HELD: Main thread holds lock across this call. |
| 610 | childpid = os.fork() |
| 611 | finish_join = True |
| 612 | if childpid != 0: |
| 613 | # Parent process just waits for child. |
| 614 | os.waitpid(childpid, 0) |
| 615 | # Child process should just return. |
| 616 | |
| 617 | w = threading.Thread(target=worker) |
| 618 | |
| 619 | # Stub out the private condition variable's lock acquire method. |
| 620 | # This acquires the lock and then waits until the child has forked |
| 621 | # before returning, which will release the lock soon after. If |
| 622 | # someone else tries to fix this test case by acquiring this lock |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 623 | # before forking instead of resetting it, the test case will |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 624 | # deadlock when it shouldn't. |
| 625 | condition = w._block |
| 626 | orig_acquire = condition.acquire |
| 627 | call_count_lock = threading.Lock() |
| 628 | call_count = 0 |
| 629 | def my_acquire(): |
| 630 | global call_count |
| 631 | global start_fork |
| 632 | orig_acquire() # LOCK ACQUIRED HERE |
| 633 | start_fork = True |
| 634 | if call_count == 0: |
| 635 | while not finish_join: |
| 636 | time.sleep(0.01) # WORKER THREAD FORKS HERE |
| 637 | with call_count_lock: |
| 638 | call_count += 1 |
| 639 | condition.acquire = my_acquire |
| 640 | |
| 641 | w.start() |
| 642 | w.join() |
| 643 | print('end of main') |
| 644 | """ |
| 645 | self.assertScriptHasOutput(script, "end of main\n") |
| 646 | |
| 647 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 648 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 649 | def test_5_clear_waiter_locks_to_avoid_crash(self): |
| 650 | # Check that a spawned thread that forks doesn't segfault on certain |
| 651 | # platforms, namely OS X. This used to happen if there was a waiter |
| 652 | # lock in the thread's condition variable's waiters list. Even though |
| 653 | # we know the lock will be held across the fork, it is not safe to |
| 654 | # release locks held across forks on all platforms, so releasing the |
| 655 | # waiter lock caused a segfault on OS X. Furthermore, since locks on |
| 656 | # OS X are (as of this writing) implemented with a mutex + condition |
| 657 | # variable instead of a semaphore, while we know that the Python-level |
| 658 | # lock will be acquired, we can't know if the internal mutex will be |
| 659 | # acquired at the time of the fork. |
| 660 | |
Gregory P. Smith | 96c886c | 2011-01-03 21:06:12 +0000 | [diff] [blame] | 661 | script = """if True: |
| 662 | import os, time, threading |
| 663 | |
| 664 | start_fork = False |
| 665 | |
| 666 | def worker(): |
| 667 | # Wait until the main thread has attempted to join this thread |
| 668 | # before continuing. |
| 669 | while not start_fork: |
| 670 | time.sleep(0.01) |
| 671 | childpid = os.fork() |
| 672 | if childpid != 0: |
| 673 | # Parent process just waits for child. |
| 674 | (cpid, rc) = os.waitpid(childpid, 0) |
| 675 | assert cpid == childpid |
| 676 | assert rc == 0 |
| 677 | print('end of worker thread') |
| 678 | else: |
| 679 | # Child process should just return. |
| 680 | pass |
| 681 | |
| 682 | w = threading.Thread(target=worker) |
| 683 | |
| 684 | # Stub out the private condition variable's _release_save method. |
| 685 | # This releases the condition's lock and flips the global that |
| 686 | # causes the worker to fork. At this point, the problematic waiter |
| 687 | # lock has been acquired once by the waiter and has been put onto |
| 688 | # the waiters list. |
| 689 | condition = w._block |
| 690 | orig_release_save = condition._release_save |
| 691 | def my_release_save(): |
| 692 | global start_fork |
| 693 | orig_release_save() |
| 694 | # Waiter lock held here, condition lock released. |
| 695 | start_fork = True |
| 696 | condition._release_save = my_release_save |
| 697 | |
| 698 | w.start() |
| 699 | w.join() |
| 700 | print('end of main thread') |
| 701 | """ |
| 702 | output = "end of worker thread\nend of main thread\n" |
| 703 | self.assertScriptHasOutput(script, output) |
| 704 | |
Charles-François Natali | 8e6fe64 | 2012-03-24 20:36:09 +0100 | [diff] [blame] | 705 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 706 | def test_6_daemon_threads(self): |
| 707 | # Check that a daemon thread cannot crash the interpreter on shutdown |
| 708 | # by manipulating internal structures that are being disposed of in |
| 709 | # the main thread. |
| 710 | script = """if True: |
| 711 | import os |
| 712 | import random |
| 713 | import sys |
| 714 | import time |
| 715 | import threading |
| 716 | |
| 717 | thread_has_run = set() |
| 718 | |
| 719 | def random_io(): |
| 720 | '''Loop for a while sleeping random tiny amounts and doing some I/O.''' |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 721 | while True: |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 722 | in_f = open(os.__file__, 'rb') |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 723 | stuff = in_f.read(200) |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 724 | null_f = open(os.devnull, 'wb') |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 725 | null_f.write(stuff) |
| 726 | time.sleep(random.random() / 1995) |
| 727 | null_f.close() |
| 728 | in_f.close() |
| 729 | thread_has_run.add(threading.current_thread()) |
| 730 | |
| 731 | def main(): |
| 732 | count = 0 |
| 733 | for _ in range(40): |
| 734 | new_thread = threading.Thread(target=random_io) |
| 735 | new_thread.daemon = True |
| 736 | new_thread.start() |
| 737 | count += 1 |
| 738 | while len(thread_has_run) < count: |
| 739 | time.sleep(0.001) |
| 740 | # Trigger process shutdown |
| 741 | sys.exit(0) |
| 742 | |
| 743 | main() |
| 744 | """ |
| 745 | rc, out, err = assert_python_ok('-c', script) |
| 746 | self.assertFalse(err) |
| 747 | |
Charles-François Natali | 6d0d24e | 2012-02-02 20:31:42 +0100 | [diff] [blame] | 748 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Charles-François Natali | b2c9e9a | 2012-02-08 21:29:11 +0100 | [diff] [blame] | 749 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Charles-François Natali | 6d0d24e | 2012-02-02 20:31:42 +0100 | [diff] [blame] | 750 | def test_reinit_tls_after_fork(self): |
| 751 | # Issue #13817: fork() would deadlock in a multithreaded program with |
| 752 | # the ad-hoc TLS implementation. |
| 753 | |
| 754 | def do_fork_and_wait(): |
| 755 | # just fork a child process and wait it |
| 756 | pid = os.fork() |
| 757 | if pid > 0: |
| 758 | os.waitpid(pid, 0) |
| 759 | else: |
| 760 | os._exit(0) |
| 761 | |
| 762 | # start a bunch of threads that will fork() child processes |
| 763 | threads = [] |
| 764 | for i in range(16): |
| 765 | t = threading.Thread(target=do_fork_and_wait) |
| 766 | threads.append(t) |
| 767 | t.start() |
| 768 | |
| 769 | for t in threads: |
| 770 | t.join() |
| 771 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 772 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 773 | class ThreadingExceptionTests(BaseTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 774 | # A RuntimeError should be raised if Thread.start() is called |
| 775 | # multiple times. |
| 776 | def test_start_thread_again(self): |
| 777 | thread = threading.Thread() |
| 778 | thread.start() |
| 779 | self.assertRaises(RuntimeError, thread.start) |
| 780 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 781 | def test_joining_current_thread(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 782 | current_thread = threading.current_thread() |
| 783 | self.assertRaises(RuntimeError, current_thread.join); |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 784 | |
| 785 | def test_joining_inactive_thread(self): |
| 786 | thread = threading.Thread() |
| 787 | self.assertRaises(RuntimeError, thread.join) |
| 788 | |
| 789 | def test_daemonize_active_thread(self): |
| 790 | thread = threading.Thread() |
| 791 | thread.start() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 792 | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 793 | |
Antoine Pitrou | fcf81fd | 2011-02-28 22:03:34 +0000 | [diff] [blame] | 794 | def test_releasing_unacquired_lock(self): |
| 795 | lock = threading.Lock() |
| 796 | self.assertRaises(RuntimeError, lock.release) |
| 797 | |
Łukasz Langa | 20ea96f | 2013-04-24 01:29:26 +0200 | [diff] [blame] | 798 | @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(), |
| 799 | 'test macosx problem') |
Ned Deily | 9a7c524 | 2011-05-28 00:19:56 -0700 | [diff] [blame] | 800 | def test_recursion_limit(self): |
| 801 | # Issue 9670 |
| 802 | # test that excessive recursion within a non-main thread causes |
| 803 | # an exception rather than crashing the interpreter on platforms |
| 804 | # like Mac OS X or FreeBSD which have small default stack sizes |
| 805 | # for threads |
| 806 | script = """if True: |
| 807 | import threading |
| 808 | |
| 809 | def recurse(): |
| 810 | return recurse() |
| 811 | |
| 812 | def outer(): |
| 813 | try: |
| 814 | recurse() |
| 815 | except RuntimeError: |
| 816 | pass |
| 817 | |
| 818 | w = threading.Thread(target=outer) |
| 819 | w.start() |
| 820 | w.join() |
| 821 | print('end of main thread') |
| 822 | """ |
| 823 | expected_output = "end of main thread\n" |
| 824 | p = subprocess.Popen([sys.executable, "-c", script], |
Antoine Pitrou | b8b6a68 | 2012-06-29 19:40:35 +0200 | [diff] [blame] | 825 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Ned Deily | 9a7c524 | 2011-05-28 00:19:56 -0700 | [diff] [blame] | 826 | stdout, stderr = p.communicate() |
| 827 | data = stdout.decode().replace('\r', '') |
Antoine Pitrou | b8b6a68 | 2012-06-29 19:40:35 +0200 | [diff] [blame] | 828 | self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode()) |
Ned Deily | 9a7c524 | 2011-05-28 00:19:56 -0700 | [diff] [blame] | 829 | self.assertEqual(data, expected_output) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 830 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 831 | class TimerTests(BaseTestCase): |
| 832 | |
| 833 | def setUp(self): |
| 834 | BaseTestCase.setUp(self) |
| 835 | self.callback_args = [] |
| 836 | self.callback_event = threading.Event() |
| 837 | |
| 838 | def test_init_immutable_default_args(self): |
| 839 | # Issue 17435: constructor defaults were mutable objects, they could be |
| 840 | # mutated via the object attributes and affect other Timer objects. |
| 841 | timer1 = threading.Timer(0.01, self._callback_spy) |
| 842 | timer1.start() |
| 843 | self.callback_event.wait() |
| 844 | timer1.args.append("blah") |
| 845 | timer1.kwargs["foo"] = "bar" |
| 846 | self.callback_event.clear() |
| 847 | timer2 = threading.Timer(0.01, self._callback_spy) |
| 848 | timer2.start() |
| 849 | self.callback_event.wait() |
| 850 | self.assertEqual(len(self.callback_args), 2) |
| 851 | self.assertEqual(self.callback_args, [((), {}), ((), {})]) |
| 852 | |
| 853 | def _callback_spy(self, *args, **kwargs): |
| 854 | self.callback_args.append((args[:], kwargs.copy())) |
| 855 | self.callback_event.set() |
| 856 | |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 857 | class LockTests(lock_tests.LockTests): |
| 858 | locktype = staticmethod(threading.Lock) |
| 859 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 860 | class PyRLockTests(lock_tests.RLockTests): |
| 861 | locktype = staticmethod(threading._PyRLock) |
| 862 | |
Charles-François Natali | 6b671b2 | 2012-01-28 11:36:04 +0100 | [diff] [blame] | 863 | @unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C') |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 864 | class CRLockTests(lock_tests.RLockTests): |
| 865 | locktype = staticmethod(threading._CRLock) |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 866 | |
| 867 | class EventTests(lock_tests.EventTests): |
| 868 | eventtype = staticmethod(threading.Event) |
| 869 | |
| 870 | class ConditionAsRLockTests(lock_tests.RLockTests): |
| 871 | # An Condition uses an RLock by default and exports its API. |
| 872 | locktype = staticmethod(threading.Condition) |
| 873 | |
| 874 | class ConditionTests(lock_tests.ConditionTests): |
| 875 | condtype = staticmethod(threading.Condition) |
| 876 | |
| 877 | class SemaphoreTests(lock_tests.SemaphoreTests): |
| 878 | semtype = staticmethod(threading.Semaphore) |
| 879 | |
| 880 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
| 881 | semtype = staticmethod(threading.BoundedSemaphore) |
| 882 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 883 | class BarrierTests(lock_tests.BarrierTests): |
| 884 | barriertype = staticmethod(threading.Barrier) |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 885 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 886 | if __name__ == "__main__": |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 887 | unittest.main() |