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