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