Antoine Pitrou | 4c8ce84 | 2013-09-01 19:51:49 +0200 | [diff] [blame] | 1 | """ |
| 2 | Tests for the threading module. |
| 3 | """ |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 4 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 5 | import test.support |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 6 | from test.support import verbose, strip_python_stderr, import_module |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 7 | from test.script_helper import assert_python_ok |
| 8 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 9 | import random |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 10 | import re |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 11 | import sys |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 12 | _thread = import_module('_thread') |
| 13 | threading = import_module('threading') |
Antoine Pitrou | 7eaf3f7 | 2013-08-25 19:48:18 +0200 | [diff] [blame] | 14 | import _testcapi |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 15 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 16 | import unittest |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 17 | import weakref |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 18 | import os |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 19 | from test.script_helper import assert_python_ok, assert_python_failure |
Gregory P. Smith | 4b129d2 | 2011-01-04 00:51:50 +0000 | [diff] [blame] | 20 | import subprocess |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 21 | |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 22 | from test import lock_tests |
| 23 | |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 24 | |
| 25 | # Between fork() and exec(), only async-safe functions are allowed (issues |
| 26 | # #12316 and #11870), and fork() from a worker thread is known to trigger |
| 27 | # problems with some operating systems (issue #3863): skip problematic tests |
| 28 | # on platforms known to behave badly. |
| 29 | platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', |
| 30 | 'hp-ux11') |
| 31 | |
| 32 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 33 | # A trivial mutable counter. |
| 34 | class Counter(object): |
| 35 | def __init__(self): |
| 36 | self.value = 0 |
| 37 | def inc(self): |
| 38 | self.value += 1 |
| 39 | def dec(self): |
| 40 | self.value -= 1 |
| 41 | def get(self): |
| 42 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 43 | |
| 44 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 45 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 46 | threading.Thread.__init__(self, name=name) |
| 47 | self.testcase = testcase |
| 48 | self.sema = sema |
| 49 | self.mutex = mutex |
| 50 | self.nrunning = nrunning |
| 51 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 52 | def run(self): |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 53 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 54 | if verbose: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 55 | print('task %s will run for %.1f usec' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 56 | (self.name, delay * 1e6)) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 57 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 58 | with self.sema: |
| 59 | with self.mutex: |
| 60 | self.nrunning.inc() |
| 61 | if verbose: |
| 62 | print(self.nrunning.get(), 'tasks are running') |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 63 | self.testcase.assertTrue(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 64 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 65 | time.sleep(delay) |
| 66 | if verbose: |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 67 | print('task', self.name, 'done') |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 68 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 69 | with self.mutex: |
| 70 | self.nrunning.dec() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 71 | self.testcase.assertTrue(self.nrunning.get() >= 0) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 72 | if verbose: |
| 73 | print('%s is finished. %d tasks are running' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 74 | (self.name, self.nrunning.get())) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 75 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 76 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 77 | class BaseTestCase(unittest.TestCase): |
| 78 | def setUp(self): |
| 79 | self._threads = test.support.threading_setup() |
| 80 | |
| 81 | def tearDown(self): |
| 82 | test.support.threading_cleanup(*self._threads) |
| 83 | test.support.reap_children() |
| 84 | |
| 85 | |
| 86 | class ThreadTests(BaseTestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 87 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 88 | # Create a bunch of threads, let each do some work, wait until all are |
| 89 | # done. |
| 90 | def test_various_ops(self): |
| 91 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 92 | # times about 1 second per clump). |
| 93 | NUMTASKS = 10 |
| 94 | |
| 95 | # no more than 3 of the 10 can run at once |
| 96 | sema = threading.BoundedSemaphore(value=3) |
| 97 | mutex = threading.RLock() |
| 98 | numrunning = Counter() |
| 99 | |
| 100 | threads = [] |
| 101 | |
| 102 | for i in range(NUMTASKS): |
| 103 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 104 | threads.append(t) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 105 | self.assertEqual(t.ident, None) |
| 106 | self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 107 | t.start() |
| 108 | |
| 109 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 110 | print('waiting for all tasks to complete') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 111 | for t in threads: |
Antoine Pitrou | 5da7e79 | 2013-09-08 13:19:06 +0200 | [diff] [blame] | 112 | t.join() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 113 | self.assertTrue(not t.is_alive()) |
| 114 | self.assertNotEqual(t.ident, 0) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 115 | self.assertFalse(t.ident is None) |
Brett Cannon | 3f5f226 | 2010-07-23 15:50:52 +0000 | [diff] [blame] | 116 | self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>', |
| 117 | repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 118 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 119 | print('all tasks done') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 120 | self.assertEqual(numrunning.get(), 0) |
| 121 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 122 | def test_ident_of_no_threading_threads(self): |
| 123 | # The ident still must work for the main thread and dummy threads. |
| 124 | self.assertFalse(threading.currentThread().ident is None) |
| 125 | def f(): |
| 126 | ident.append(threading.currentThread().ident) |
| 127 | done.set() |
| 128 | done = threading.Event() |
| 129 | ident = [] |
| 130 | _thread.start_new_thread(f, ()) |
| 131 | done.wait() |
| 132 | self.assertFalse(ident[0] is None) |
Antoine Pitrou | ca13a0d | 2009-11-08 00:30:04 +0000 | [diff] [blame] | 133 | # Kill the "immortal" _DummyThread |
| 134 | del threading._active[ident[0]] |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 135 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 136 | # run with a small(ish) thread stack size (256kB) |
| 137 | def test_various_ops_small_stack(self): |
| 138 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 139 | print('with 256kB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 140 | try: |
| 141 | threading.stack_size(262144) |
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 | |
| 148 | # run with a large thread stack size (1MB) |
| 149 | def test_various_ops_large_stack(self): |
| 150 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 151 | print('with 1MB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 152 | try: |
| 153 | threading.stack_size(0x100000) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 154 | except _thread.error: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 155 | raise unittest.SkipTest( |
| 156 | 'platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 157 | self.test_various_ops() |
| 158 | threading.stack_size(0) |
| 159 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 160 | def test_foreign_thread(self): |
| 161 | # Check that a "foreign" thread can use the threading module. |
| 162 | def f(mutex): |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 163 | # Calling current_thread() forces an entry for the foreign |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 164 | # thread to get made in the threading._active map. |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 165 | threading.current_thread() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 166 | mutex.release() |
| 167 | |
| 168 | mutex = threading.Lock() |
| 169 | mutex.acquire() |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 170 | tid = _thread.start_new_thread(f, (mutex,)) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 171 | # Wait for the thread to finish. |
| 172 | mutex.acquire() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 173 | self.assertIn(tid, threading._active) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 174 | self.assertIsInstance(threading._active[tid], threading._DummyThread) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 175 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 176 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 177 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 178 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 179 | def test_PyThreadState_SetAsyncExc(self): |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 180 | ctypes = import_module("ctypes") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 181 | |
| 182 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 183 | |
| 184 | class AsyncExc(Exception): |
| 185 | pass |
| 186 | |
| 187 | exception = ctypes.py_object(AsyncExc) |
| 188 | |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 189 | # First check it works when setting the exception from the same thread. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 190 | tid = threading.get_ident() |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 191 | |
| 192 | try: |
| 193 | result = set_async_exc(ctypes.c_long(tid), exception) |
| 194 | # The exception is async, so we might have to keep the VM busy until |
| 195 | # it notices. |
| 196 | while True: |
| 197 | pass |
| 198 | except AsyncExc: |
| 199 | pass |
| 200 | else: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 201 | # This code is unreachable but it reflects the intent. If we wanted |
| 202 | # to be smarter the above loop wouldn't be infinite. |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 203 | self.fail("AsyncExc not raised") |
| 204 | try: |
| 205 | self.assertEqual(result, 1) # one thread state modified |
| 206 | except UnboundLocalError: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 207 | # The exception was raised too quickly for us to get the result. |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 208 | pass |
| 209 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 210 | # `worker_started` is set by the thread when it's inside a try/except |
| 211 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 212 | # `worker_saw_exception` is set by the thread upon catching that |
| 213 | # exception. |
| 214 | worker_started = threading.Event() |
| 215 | worker_saw_exception = threading.Event() |
| 216 | |
| 217 | class Worker(threading.Thread): |
| 218 | def run(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 219 | self.id = threading.get_ident() |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 220 | self.finished = False |
| 221 | |
| 222 | try: |
| 223 | while True: |
| 224 | worker_started.set() |
| 225 | time.sleep(0.1) |
| 226 | except AsyncExc: |
| 227 | self.finished = True |
| 228 | worker_saw_exception.set() |
| 229 | |
| 230 | t = Worker() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 231 | 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] | 232 | t.start() |
| 233 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 234 | print(" started worker thread") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 235 | |
| 236 | # Try a thread id that doesn't make sense. |
| 237 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 238 | print(" trying nonsensical thread id") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 239 | result = set_async_exc(ctypes.c_long(-1), exception) |
| 240 | self.assertEqual(result, 0) # no thread states modified |
| 241 | |
| 242 | # Now raise an exception in the worker thread. |
| 243 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 244 | print(" waiting for worker thread to get started") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 245 | ret = worker_started.wait() |
| 246 | self.assertTrue(ret) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 247 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 248 | print(" verifying worker hasn't exited") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 249 | self.assertTrue(not t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 250 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 251 | print(" attempting to raise asynch exception in worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 252 | result = set_async_exc(ctypes.c_long(t.id), exception) |
| 253 | self.assertEqual(result, 1) # one thread state modified |
| 254 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 255 | print(" waiting for worker to say it caught the exception") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 256 | worker_saw_exception.wait(timeout=10) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 257 | self.assertTrue(t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 258 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 259 | print(" all OK -- joining worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 260 | if t.finished: |
| 261 | t.join() |
| 262 | # else the thread is still running, and we have no way to kill it |
| 263 | |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 264 | def test_limbo_cleanup(self): |
| 265 | # Issue 7481: Failure to start thread should cleanup the limbo map. |
| 266 | def fail_new_thread(*args): |
| 267 | raise threading.ThreadError() |
| 268 | _start_new_thread = threading._start_new_thread |
| 269 | threading._start_new_thread = fail_new_thread |
| 270 | try: |
| 271 | t = threading.Thread(target=lambda: None) |
Gregory P. Smith | f50f168 | 2010-03-01 03:13:36 +0000 | [diff] [blame] | 272 | self.assertRaises(threading.ThreadError, t.start) |
| 273 | self.assertFalse( |
| 274 | t in threading._limbo, |
| 275 | "Failed to cleanup _limbo map on failure of Thread.start().") |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 276 | finally: |
| 277 | threading._start_new_thread = _start_new_thread |
| 278 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 279 | def test_finalize_runnning_thread(self): |
| 280 | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
| 281 | # very late on python exit: on deallocation of a running thread for |
| 282 | # example. |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 283 | import_module("ctypes") |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 284 | |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 285 | rc, out, err = assert_python_failure("-c", """if 1: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 286 | import ctypes, sys, time, _thread |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 287 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 288 | # This lock is used as a simple event variable. |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 289 | ready = _thread.allocate_lock() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 290 | ready.acquire() |
| 291 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 292 | # Module globals are cleared before __del__ is run |
| 293 | # So we save the functions in class dict |
| 294 | class C: |
| 295 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 296 | release = ctypes.pythonapi.PyGILState_Release |
| 297 | def __del__(self): |
| 298 | state = self.ensure() |
| 299 | self.release(state) |
| 300 | |
| 301 | def waitingThread(): |
| 302 | x = C() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 303 | ready.release() |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 304 | time.sleep(100) |
| 305 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 306 | _thread.start_new_thread(waitingThread, ()) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 307 | ready.acquire() # Be sure the other thread is waiting. |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 308 | sys.exit(42) |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 309 | """) |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 310 | self.assertEqual(rc, 42) |
| 311 | |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 312 | def test_finalize_with_trace(self): |
| 313 | # Issue1733757 |
| 314 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 315 | assert_python_ok("-c", """if 1: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 316 | import sys, threading |
| 317 | |
| 318 | # A deadlock-killer, to prevent the |
| 319 | # testsuite to hang forever |
| 320 | def killer(): |
| 321 | import os, time |
| 322 | time.sleep(2) |
| 323 | print('program blocked; aborting') |
| 324 | os._exit(2) |
| 325 | t = threading.Thread(target=killer) |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 326 | t.daemon = True |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 327 | t.start() |
| 328 | |
| 329 | # This is the trace function |
| 330 | def func(frame, event, arg): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 331 | threading.current_thread() |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 332 | return func |
| 333 | |
| 334 | sys.settrace(func) |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 335 | """) |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 336 | |
Antoine Pitrou | 011bd62 | 2009-10-20 21:52:47 +0000 | [diff] [blame] | 337 | def test_join_nondaemon_on_shutdown(self): |
| 338 | # Issue 1722344 |
| 339 | # Raising SystemExit skipped threading._shutdown |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 340 | rc, out, err = assert_python_ok("-c", """if 1: |
Antoine Pitrou | 011bd62 | 2009-10-20 21:52:47 +0000 | [diff] [blame] | 341 | import threading |
| 342 | from time import sleep |
| 343 | |
| 344 | def child(): |
| 345 | sleep(1) |
| 346 | # As a non-daemon thread we SHOULD wake up and nothing |
| 347 | # should be torn down yet |
| 348 | print("Woke up, sleep function is:", sleep) |
| 349 | |
| 350 | threading.Thread(target=child).start() |
| 351 | raise SystemExit |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 352 | """) |
| 353 | self.assertEqual(out.strip(), |
Antoine Pitrou | 899d1c6 | 2009-10-23 21:55:36 +0000 | [diff] [blame] | 354 | b"Woke up, sleep function is: <built-in function sleep>") |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 355 | self.assertEqual(err, b"") |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 356 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 357 | def test_enumerate_after_join(self): |
| 358 | # Try hard to trigger #1703448: a thread is still returned in |
| 359 | # threading.enumerate() after it has been join()ed. |
| 360 | enum = threading.enumerate |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 361 | old_interval = sys.getswitchinterval() |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 362 | try: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 363 | for i in range(1, 100): |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 364 | sys.setswitchinterval(i * 0.0002) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 365 | t = threading.Thread(target=lambda: None) |
| 366 | t.start() |
| 367 | t.join() |
| 368 | l = enum() |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 369 | self.assertNotIn(t, l, |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 370 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 371 | finally: |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 372 | sys.setswitchinterval(old_interval) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 373 | |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 374 | def test_no_refcycle_through_target(self): |
| 375 | class RunSelfFunction(object): |
| 376 | def __init__(self, should_raise): |
| 377 | # The links in this refcycle from Thread back to self |
| 378 | # should be cleaned up when the thread completes. |
| 379 | self.should_raise = should_raise |
| 380 | self.thread = threading.Thread(target=self._run, |
| 381 | args=(self,), |
| 382 | kwargs={'yet_another':self}) |
| 383 | self.thread.start() |
| 384 | |
| 385 | def _run(self, other_ref, yet_another): |
| 386 | if self.should_raise: |
| 387 | raise SystemExit |
| 388 | |
| 389 | cyclic_object = RunSelfFunction(should_raise=False) |
| 390 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 391 | cyclic_object.thread.join() |
| 392 | del cyclic_object |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 393 | self.assertIsNone(weak_cyclic_object(), |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 394 | msg=('%d references still around' % |
| 395 | sys.getrefcount(weak_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 396 | |
| 397 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 398 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 399 | raising_cyclic_object.thread.join() |
| 400 | del raising_cyclic_object |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 401 | self.assertIsNone(weak_raising_cyclic_object(), |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 402 | msg=('%d references still around' % |
| 403 | sys.getrefcount(weak_raising_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 404 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 405 | def test_old_threading_api(self): |
| 406 | # Just a quick sanity check to make sure the old method names are |
| 407 | # still present |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 408 | t = threading.Thread() |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 409 | t.isDaemon() |
| 410 | t.setDaemon(True) |
| 411 | t.getName() |
| 412 | t.setName("name") |
| 413 | t.isAlive() |
| 414 | e = threading.Event() |
| 415 | e.isSet() |
| 416 | threading.activeCount() |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 417 | |
Brian Curtin | 81a4a6a | 2010-07-23 16:30:10 +0000 | [diff] [blame] | 418 | def test_repr_daemon(self): |
| 419 | t = threading.Thread() |
| 420 | self.assertFalse('daemon' in repr(t)) |
| 421 | t.daemon = True |
| 422 | self.assertTrue('daemon' in repr(t)) |
Brett Cannon | 3f5f226 | 2010-07-23 15:50:52 +0000 | [diff] [blame] | 423 | |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 424 | def test_deamon_param(self): |
| 425 | t = threading.Thread() |
| 426 | self.assertFalse(t.daemon) |
| 427 | t = threading.Thread(daemon=False) |
| 428 | self.assertFalse(t.daemon) |
| 429 | t = threading.Thread(daemon=True) |
| 430 | self.assertTrue(t.daemon) |
| 431 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 432 | @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()') |
| 433 | def test_dummy_thread_after_fork(self): |
| 434 | # Issue #14308: a dummy thread in the active list doesn't mess up |
| 435 | # the after-fork mechanism. |
| 436 | code = """if 1: |
| 437 | import _thread, threading, os, time |
| 438 | |
| 439 | def background_thread(evt): |
| 440 | # Creates and registers the _DummyThread instance |
| 441 | threading.current_thread() |
| 442 | evt.set() |
| 443 | time.sleep(10) |
| 444 | |
| 445 | evt = threading.Event() |
| 446 | _thread.start_new_thread(background_thread, (evt,)) |
| 447 | evt.wait() |
| 448 | assert threading.active_count() == 2, threading.active_count() |
| 449 | if os.fork() == 0: |
| 450 | assert threading.active_count() == 1, threading.active_count() |
| 451 | os._exit(0) |
| 452 | else: |
| 453 | os.wait() |
| 454 | """ |
| 455 | _, out, err = assert_python_ok("-c", code) |
| 456 | self.assertEqual(out, b'') |
| 457 | self.assertEqual(err, b'') |
| 458 | |
Charles-François Natali | 9939cc8 | 2013-08-30 23:32:53 +0200 | [diff] [blame] | 459 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 460 | def test_is_alive_after_fork(self): |
| 461 | # Try hard to trigger #18418: is_alive() could sometimes be True on |
| 462 | # threads that vanished after a fork. |
| 463 | old_interval = sys.getswitchinterval() |
| 464 | self.addCleanup(sys.setswitchinterval, old_interval) |
| 465 | |
| 466 | # Make the bug more likely to manifest. |
| 467 | sys.setswitchinterval(1e-6) |
| 468 | |
| 469 | for i in range(20): |
| 470 | t = threading.Thread(target=lambda: None) |
| 471 | t.start() |
| 472 | self.addCleanup(t.join) |
| 473 | pid = os.fork() |
| 474 | if pid == 0: |
| 475 | os._exit(1 if t.is_alive() else 0) |
| 476 | else: |
| 477 | pid, status = os.waitpid(pid, 0) |
| 478 | self.assertEqual(0, status) |
| 479 | |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 480 | def test_main_thread(self): |
| 481 | main = threading.main_thread() |
| 482 | self.assertEqual(main.name, 'MainThread') |
| 483 | self.assertEqual(main.ident, threading.current_thread().ident) |
| 484 | self.assertEqual(main.ident, threading.get_ident()) |
| 485 | |
| 486 | def f(): |
| 487 | self.assertNotEqual(threading.main_thread().ident, |
| 488 | threading.current_thread().ident) |
| 489 | th = threading.Thread(target=f) |
| 490 | th.start() |
| 491 | th.join() |
| 492 | |
| 493 | @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") |
| 494 | @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()") |
| 495 | def test_main_thread_after_fork(self): |
| 496 | code = """if 1: |
| 497 | import os, threading |
| 498 | |
| 499 | pid = os.fork() |
| 500 | if pid == 0: |
| 501 | main = threading.main_thread() |
| 502 | print(main.name) |
| 503 | print(main.ident == threading.current_thread().ident) |
| 504 | print(main.ident == threading.get_ident()) |
| 505 | else: |
| 506 | os.waitpid(pid, 0) |
| 507 | """ |
| 508 | _, out, err = assert_python_ok("-c", code) |
| 509 | data = out.decode().replace('\r', '') |
| 510 | self.assertEqual(err, b"") |
| 511 | self.assertEqual(data, "MainThread\nTrue\nTrue\n") |
| 512 | |
| 513 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
| 514 | @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") |
| 515 | @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()") |
| 516 | def test_main_thread_after_fork_from_nonmain_thread(self): |
| 517 | code = """if 1: |
| 518 | import os, threading, sys |
| 519 | |
| 520 | def f(): |
| 521 | pid = os.fork() |
| 522 | if pid == 0: |
| 523 | main = threading.main_thread() |
| 524 | print(main.name) |
| 525 | print(main.ident == threading.current_thread().ident) |
| 526 | print(main.ident == threading.get_ident()) |
| 527 | # stdout is fully buffered because not a tty, |
| 528 | # we have to flush before exit. |
| 529 | sys.stdout.flush() |
| 530 | else: |
| 531 | os.waitpid(pid, 0) |
| 532 | |
| 533 | th = threading.Thread(target=f) |
| 534 | th.start() |
| 535 | th.join() |
| 536 | """ |
| 537 | _, out, err = assert_python_ok("-c", code) |
| 538 | data = out.decode().replace('\r', '') |
| 539 | self.assertEqual(err, b"") |
| 540 | self.assertEqual(data, "Thread-1\nTrue\nTrue\n") |
| 541 | |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 542 | def test_tstate_lock(self): |
| 543 | # Test an implementation detail of Thread objects. |
| 544 | started = _thread.allocate_lock() |
| 545 | finish = _thread.allocate_lock() |
| 546 | started.acquire() |
| 547 | finish.acquire() |
| 548 | def f(): |
| 549 | started.release() |
| 550 | finish.acquire() |
| 551 | time.sleep(0.01) |
| 552 | # The tstate lock is None until the thread is started |
| 553 | t = threading.Thread(target=f) |
| 554 | self.assertIs(t._tstate_lock, None) |
| 555 | t.start() |
| 556 | started.acquire() |
| 557 | self.assertTrue(t.is_alive()) |
| 558 | # The tstate lock can't be acquired when the thread is running |
| 559 | # (or suspended). |
| 560 | tstate_lock = t._tstate_lock |
| 561 | self.assertFalse(tstate_lock.acquire(timeout=0), False) |
| 562 | finish.release() |
| 563 | # When the thread ends, the state_lock can be successfully |
| 564 | # acquired. |
| 565 | self.assertTrue(tstate_lock.acquire(timeout=5), False) |
| 566 | # But is_alive() is still True: we hold _tstate_lock now, which |
| 567 | # prevents is_alive() from knowing the thread's end-of-life C code |
| 568 | # is done. |
| 569 | self.assertTrue(t.is_alive()) |
| 570 | # Let is_alive() find out the C code is done. |
| 571 | tstate_lock.release() |
| 572 | self.assertFalse(t.is_alive()) |
| 573 | # And verify the thread disposed of _tstate_lock. |
| 574 | self.assertTrue(t._tstate_lock is None) |
| 575 | |
Tim Peters | 72460fa | 2013-09-09 18:48:24 -0500 | [diff] [blame] | 576 | def test_repr_stopped(self): |
| 577 | # Verify that "stopped" shows up in repr(Thread) appropriately. |
| 578 | started = _thread.allocate_lock() |
| 579 | finish = _thread.allocate_lock() |
| 580 | started.acquire() |
| 581 | finish.acquire() |
| 582 | def f(): |
| 583 | started.release() |
| 584 | finish.acquire() |
| 585 | t = threading.Thread(target=f) |
| 586 | t.start() |
| 587 | started.acquire() |
| 588 | self.assertIn("started", repr(t)) |
| 589 | finish.release() |
| 590 | # "stopped" should appear in the repr in a reasonable amount of time. |
| 591 | # Implementation detail: as of this writing, that's trivially true |
| 592 | # if .join() is called, and almost trivially true if .is_alive() is |
| 593 | # called. The detail we're testing here is that "stopped" shows up |
| 594 | # "all on its own". |
| 595 | LOOKING_FOR = "stopped" |
| 596 | for i in range(500): |
| 597 | if LOOKING_FOR in repr(t): |
| 598 | break |
| 599 | time.sleep(0.01) |
| 600 | self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 601 | |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame] | 602 | def test_BoundedSemaphore_limit(self): |
Tim Peters | 3d1b7a0 | 2013-10-08 21:29:27 -0500 | [diff] [blame] | 603 | # BoundedSemaphore should raise ValueError if released too often. |
| 604 | for limit in range(1, 10): |
| 605 | bs = threading.BoundedSemaphore(limit) |
| 606 | threads = [threading.Thread(target=bs.acquire) |
| 607 | for _ in range(limit)] |
| 608 | for t in threads: |
| 609 | t.start() |
| 610 | for t in threads: |
| 611 | t.join() |
| 612 | threads = [threading.Thread(target=bs.release) |
| 613 | for _ in range(limit)] |
| 614 | for t in threads: |
| 615 | t.start() |
| 616 | for t in threads: |
| 617 | t.join() |
| 618 | self.assertRaises(ValueError, bs.release) |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame] | 619 | |
Victor Stinner | 45956b9 | 2013-11-12 16:37:55 +0100 | [diff] [blame] | 620 | def test_locals_at_exit(self): |
| 621 | # Issue #19466: thread locals must not be deleted before destructors |
| 622 | # are called |
| 623 | rc, out, err = assert_python_ok("-c", """if 1: |
| 624 | import threading |
| 625 | |
| 626 | class Atexit: |
| 627 | def __del__(self): |
| 628 | print("thread_dict.atexit = %r" % thread_dict.atexit) |
| 629 | |
| 630 | thread_dict = threading.local() |
| 631 | thread_dict.atexit = "atexit" |
| 632 | |
| 633 | atexit = Atexit() |
| 634 | """) |
| 635 | self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'atexit'") |
| 636 | |
| 637 | def test_warnings_at_exit(self): |
| 638 | # Issue #19466: try to call most destructors at Python shutdown before |
| 639 | # destroying Python thread states |
| 640 | filename = __file__ |
| 641 | rc, out, err = assert_python_ok("-Wd", "-c", """if 1: |
| 642 | import time |
| 643 | import threading |
| 644 | |
| 645 | def open_sleep(): |
| 646 | # a warning will be emitted when the open file will be |
| 647 | # destroyed (without being explicitly closed) while the daemon |
| 648 | # thread is destroyed |
| 649 | fileobj = open(%a, 'rb') |
| 650 | start_event.set() |
| 651 | time.sleep(60.0) |
| 652 | |
| 653 | start_event = threading.Event() |
| 654 | |
| 655 | thread = threading.Thread(target=open_sleep) |
| 656 | thread.daemon = True |
| 657 | thread.start() |
| 658 | |
| 659 | # wait until the thread started |
| 660 | start_event.wait() |
| 661 | """ % filename) |
| 662 | self.assertRegex(err.rstrip(), |
| 663 | b"^sys:1: ResourceWarning: unclosed file ") |
| 664 | |
| 665 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 666 | class ThreadJoinOnShutdown(BaseTestCase): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 667 | |
| 668 | def _run_and_join(self, script): |
| 669 | script = """if 1: |
| 670 | import sys, os, time, threading |
| 671 | |
| 672 | # a thread, which waits for the main program to terminate |
| 673 | def joiningfunc(mainthread): |
| 674 | mainthread.join() |
| 675 | print('end of thread') |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 676 | # stdout is fully buffered because not a tty, we have to flush |
| 677 | # before exit. |
| 678 | sys.stdout.flush() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 679 | \n""" + script |
| 680 | |
Antoine Pitrou | c4d7864 | 2011-05-05 20:17:32 +0200 | [diff] [blame] | 681 | rc, out, err = assert_python_ok("-c", script) |
| 682 | data = out.decode().replace('\r', '') |
Benjamin Peterson | ad703dc | 2008-07-17 17:02:57 +0000 | [diff] [blame] | 683 | self.assertEqual(data, "end of main\nend of thread\n") |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 684 | |
| 685 | def test_1_join_on_shutdown(self): |
| 686 | # The usual case: on exit, wait for a non-daemon thread |
| 687 | script = """if 1: |
| 688 | import os |
| 689 | t = threading.Thread(target=joiningfunc, |
| 690 | args=(threading.current_thread(),)) |
| 691 | t.start() |
| 692 | time.sleep(0.1) |
| 693 | print('end of main') |
| 694 | """ |
| 695 | self._run_and_join(script) |
| 696 | |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 697 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 698 | @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] | 699 | def test_2_join_in_forked_process(self): |
| 700 | # Like the test above, but from a forked interpreter |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 701 | script = """if 1: |
| 702 | childpid = os.fork() |
| 703 | if childpid != 0: |
| 704 | os.waitpid(childpid, 0) |
| 705 | sys.exit(0) |
| 706 | |
| 707 | t = threading.Thread(target=joiningfunc, |
| 708 | args=(threading.current_thread(),)) |
| 709 | t.start() |
| 710 | print('end of main') |
| 711 | """ |
| 712 | self._run_and_join(script) |
| 713 | |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 714 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 715 | @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] | 716 | def test_3_join_in_forked_from_thread(self): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 717 | # Like the test above, but fork() was called from a worker thread |
| 718 | # 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] | 719 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 720 | script = """if 1: |
| 721 | main_thread = threading.current_thread() |
| 722 | def worker(): |
| 723 | childpid = os.fork() |
| 724 | if childpid != 0: |
| 725 | os.waitpid(childpid, 0) |
| 726 | sys.exit(0) |
| 727 | |
| 728 | t = threading.Thread(target=joiningfunc, |
| 729 | args=(main_thread,)) |
| 730 | print('end of main') |
| 731 | t.start() |
| 732 | t.join() # Should not block: main_thread is already stopped |
| 733 | |
| 734 | w = threading.Thread(target=worker) |
| 735 | w.start() |
| 736 | """ |
| 737 | self._run_and_join(script) |
| 738 | |
Victor Stinner | 26d3186 | 2011-07-01 14:26:24 +0200 | [diff] [blame] | 739 | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 740 | def test_4_daemon_threads(self): |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 741 | # Check that a daemon thread cannot crash the interpreter on shutdown |
| 742 | # by manipulating internal structures that are being disposed of in |
| 743 | # the main thread. |
| 744 | script = """if True: |
| 745 | import os |
| 746 | import random |
| 747 | import sys |
| 748 | import time |
| 749 | import threading |
Victor Stinner | 45956b9 | 2013-11-12 16:37:55 +0100 | [diff] [blame] | 750 | import warnings |
| 751 | |
| 752 | # ignore "unclosed file ..." warnings |
| 753 | warnings.filterwarnings('ignore', '', ResourceWarning) |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 754 | |
| 755 | thread_has_run = set() |
| 756 | |
| 757 | def random_io(): |
| 758 | '''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] | 759 | while True: |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 760 | in_f = open(os.__file__, 'rb') |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 761 | stuff = in_f.read(200) |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 762 | null_f = open(os.devnull, 'wb') |
Antoine Pitrou | 0d5e52d | 2011-05-04 20:02:30 +0200 | [diff] [blame] | 763 | null_f.write(stuff) |
| 764 | time.sleep(random.random() / 1995) |
| 765 | null_f.close() |
| 766 | in_f.close() |
| 767 | thread_has_run.add(threading.current_thread()) |
| 768 | |
| 769 | def main(): |
| 770 | count = 0 |
| 771 | for _ in range(40): |
| 772 | new_thread = threading.Thread(target=random_io) |
| 773 | new_thread.daemon = True |
| 774 | new_thread.start() |
| 775 | count += 1 |
| 776 | while len(thread_has_run) < count: |
| 777 | time.sleep(0.001) |
| 778 | # Trigger process shutdown |
| 779 | sys.exit(0) |
| 780 | |
| 781 | main() |
| 782 | """ |
| 783 | rc, out, err = assert_python_ok('-c', script) |
| 784 | self.assertFalse(err) |
| 785 | |
Charles-François Natali | 6d0d24e | 2012-02-02 20:31:42 +0100 | [diff] [blame] | 786 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Charles-François Natali | b2c9e9a | 2012-02-08 21:29:11 +0100 | [diff] [blame] | 787 | @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] | 788 | def test_reinit_tls_after_fork(self): |
| 789 | # Issue #13817: fork() would deadlock in a multithreaded program with |
| 790 | # the ad-hoc TLS implementation. |
| 791 | |
| 792 | def do_fork_and_wait(): |
| 793 | # just fork a child process and wait it |
| 794 | pid = os.fork() |
| 795 | if pid > 0: |
| 796 | os.waitpid(pid, 0) |
| 797 | else: |
| 798 | os._exit(0) |
| 799 | |
| 800 | # start a bunch of threads that will fork() child processes |
| 801 | threads = [] |
| 802 | for i in range(16): |
| 803 | t = threading.Thread(target=do_fork_and_wait) |
| 804 | threads.append(t) |
| 805 | t.start() |
| 806 | |
| 807 | for t in threads: |
| 808 | t.join() |
| 809 | |
Antoine Pitrou | 8408cea | 2013-05-05 23:47:09 +0200 | [diff] [blame] | 810 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 811 | def test_clear_threads_states_after_fork(self): |
| 812 | # Issue #17094: check that threads states are cleared after fork() |
| 813 | |
| 814 | # start a bunch of threads |
| 815 | threads = [] |
| 816 | for i in range(16): |
| 817 | t = threading.Thread(target=lambda : time.sleep(0.3)) |
| 818 | threads.append(t) |
| 819 | t.start() |
| 820 | |
| 821 | pid = os.fork() |
| 822 | if pid == 0: |
| 823 | # check that threads states have been cleared |
| 824 | if len(sys._current_frames()) == 1: |
| 825 | os._exit(0) |
| 826 | else: |
| 827 | os._exit(1) |
| 828 | else: |
| 829 | _, status = os.waitpid(pid, 0) |
| 830 | self.assertEqual(0, status) |
| 831 | |
| 832 | for t in threads: |
| 833 | t.join() |
| 834 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 835 | |
Antoine Pitrou | 7eaf3f7 | 2013-08-25 19:48:18 +0200 | [diff] [blame] | 836 | class SubinterpThreadingTests(BaseTestCase): |
| 837 | |
| 838 | def test_threads_join(self): |
| 839 | # Non-daemon threads should be joined at subinterpreter shutdown |
| 840 | # (issue #18808) |
| 841 | r, w = os.pipe() |
| 842 | self.addCleanup(os.close, r) |
| 843 | self.addCleanup(os.close, w) |
| 844 | code = r"""if 1: |
| 845 | import os |
| 846 | import threading |
| 847 | import time |
| 848 | |
| 849 | def f(): |
| 850 | # Sleep a bit so that the thread is still running when |
| 851 | # Py_EndInterpreter is called. |
| 852 | time.sleep(0.05) |
| 853 | os.write(%d, b"x") |
| 854 | threading.Thread(target=f).start() |
| 855 | """ % (w,) |
Victor Stinner | ed3b0bc | 2013-11-23 12:27:24 +0100 | [diff] [blame] | 856 | ret = test.support.run_in_subinterp(code) |
Antoine Pitrou | 7eaf3f7 | 2013-08-25 19:48:18 +0200 | [diff] [blame] | 857 | self.assertEqual(ret, 0) |
| 858 | # The thread was joined properly. |
| 859 | self.assertEqual(os.read(r, 1), b"x") |
| 860 | |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 861 | def test_threads_join_2(self): |
| 862 | # Same as above, but a delay gets introduced after the thread's |
| 863 | # Python code returned but before the thread state is deleted. |
| 864 | # To achieve this, we register a thread-local object which sleeps |
| 865 | # a bit when deallocated. |
| 866 | r, w = os.pipe() |
| 867 | self.addCleanup(os.close, r) |
| 868 | self.addCleanup(os.close, w) |
| 869 | code = r"""if 1: |
| 870 | import os |
| 871 | import threading |
| 872 | import time |
| 873 | |
| 874 | class Sleeper: |
| 875 | def __del__(self): |
| 876 | time.sleep(0.05) |
| 877 | |
| 878 | tls = threading.local() |
| 879 | |
| 880 | def f(): |
| 881 | # Sleep a bit so that the thread is still running when |
| 882 | # Py_EndInterpreter is called. |
| 883 | time.sleep(0.05) |
| 884 | tls.x = Sleeper() |
| 885 | os.write(%d, b"x") |
| 886 | threading.Thread(target=f).start() |
| 887 | """ % (w,) |
Victor Stinner | ed3b0bc | 2013-11-23 12:27:24 +0100 | [diff] [blame] | 888 | ret = test.support.run_in_subinterp(code) |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 889 | self.assertEqual(ret, 0) |
| 890 | # The thread was joined properly. |
| 891 | self.assertEqual(os.read(r, 1), b"x") |
| 892 | |
Antoine Pitrou | 7eaf3f7 | 2013-08-25 19:48:18 +0200 | [diff] [blame] | 893 | def test_daemon_threads_fatal_error(self): |
| 894 | subinterp_code = r"""if 1: |
| 895 | import os |
| 896 | import threading |
| 897 | import time |
| 898 | |
| 899 | def f(): |
| 900 | # Make sure the daemon thread is still running when |
| 901 | # Py_EndInterpreter is called. |
| 902 | time.sleep(10) |
| 903 | threading.Thread(target=f, daemon=True).start() |
| 904 | """ |
| 905 | script = r"""if 1: |
| 906 | import _testcapi |
| 907 | |
| 908 | _testcapi.run_in_subinterp(%r) |
| 909 | """ % (subinterp_code,) |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 910 | with test.support.SuppressCrashReport(): |
| 911 | rc, out, err = assert_python_failure("-c", script) |
Antoine Pitrou | 7eaf3f7 | 2013-08-25 19:48:18 +0200 | [diff] [blame] | 912 | self.assertIn("Fatal Python error: Py_EndInterpreter: " |
| 913 | "not the last thread", err.decode()) |
| 914 | |
| 915 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 916 | class ThreadingExceptionTests(BaseTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 917 | # A RuntimeError should be raised if Thread.start() is called |
| 918 | # multiple times. |
| 919 | def test_start_thread_again(self): |
| 920 | thread = threading.Thread() |
| 921 | thread.start() |
| 922 | self.assertRaises(RuntimeError, thread.start) |
| 923 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 924 | def test_joining_current_thread(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 925 | current_thread = threading.current_thread() |
| 926 | self.assertRaises(RuntimeError, current_thread.join); |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 927 | |
| 928 | def test_joining_inactive_thread(self): |
| 929 | thread = threading.Thread() |
| 930 | self.assertRaises(RuntimeError, thread.join) |
| 931 | |
| 932 | def test_daemonize_active_thread(self): |
| 933 | thread = threading.Thread() |
| 934 | thread.start() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 935 | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 936 | |
Antoine Pitrou | fcf81fd | 2011-02-28 22:03:34 +0000 | [diff] [blame] | 937 | def test_releasing_unacquired_lock(self): |
| 938 | lock = threading.Lock() |
| 939 | self.assertRaises(RuntimeError, lock.release) |
| 940 | |
Benjamin Peterson | d541d3f | 2012-10-13 11:46:44 -0400 | [diff] [blame] | 941 | @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(), |
| 942 | 'test macosx problem') |
Ned Deily | 9a7c524 | 2011-05-28 00:19:56 -0700 | [diff] [blame] | 943 | def test_recursion_limit(self): |
| 944 | # Issue 9670 |
| 945 | # test that excessive recursion within a non-main thread causes |
| 946 | # an exception rather than crashing the interpreter on platforms |
| 947 | # like Mac OS X or FreeBSD which have small default stack sizes |
| 948 | # for threads |
| 949 | script = """if True: |
| 950 | import threading |
| 951 | |
| 952 | def recurse(): |
| 953 | return recurse() |
| 954 | |
| 955 | def outer(): |
| 956 | try: |
| 957 | recurse() |
| 958 | except RuntimeError: |
| 959 | pass |
| 960 | |
| 961 | w = threading.Thread(target=outer) |
| 962 | w.start() |
| 963 | w.join() |
| 964 | print('end of main thread') |
| 965 | """ |
| 966 | expected_output = "end of main thread\n" |
| 967 | p = subprocess.Popen([sys.executable, "-c", script], |
Antoine Pitrou | b8b6a68 | 2012-06-29 19:40:35 +0200 | [diff] [blame] | 968 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Ned Deily | 9a7c524 | 2011-05-28 00:19:56 -0700 | [diff] [blame] | 969 | stdout, stderr = p.communicate() |
| 970 | data = stdout.decode().replace('\r', '') |
Antoine Pitrou | b8b6a68 | 2012-06-29 19:40:35 +0200 | [diff] [blame] | 971 | self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode()) |
Ned Deily | 9a7c524 | 2011-05-28 00:19:56 -0700 | [diff] [blame] | 972 | self.assertEqual(data, expected_output) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 973 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 974 | class TimerTests(BaseTestCase): |
| 975 | |
| 976 | def setUp(self): |
| 977 | BaseTestCase.setUp(self) |
| 978 | self.callback_args = [] |
| 979 | self.callback_event = threading.Event() |
| 980 | |
| 981 | def test_init_immutable_default_args(self): |
| 982 | # Issue 17435: constructor defaults were mutable objects, they could be |
| 983 | # mutated via the object attributes and affect other Timer objects. |
| 984 | timer1 = threading.Timer(0.01, self._callback_spy) |
| 985 | timer1.start() |
| 986 | self.callback_event.wait() |
| 987 | timer1.args.append("blah") |
| 988 | timer1.kwargs["foo"] = "bar" |
| 989 | self.callback_event.clear() |
| 990 | timer2 = threading.Timer(0.01, self._callback_spy) |
| 991 | timer2.start() |
| 992 | self.callback_event.wait() |
| 993 | self.assertEqual(len(self.callback_args), 2) |
| 994 | self.assertEqual(self.callback_args, [((), {}), ((), {})]) |
| 995 | |
| 996 | def _callback_spy(self, *args, **kwargs): |
| 997 | self.callback_args.append((args[:], kwargs.copy())) |
| 998 | self.callback_event.set() |
| 999 | |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 1000 | class LockTests(lock_tests.LockTests): |
| 1001 | locktype = staticmethod(threading.Lock) |
| 1002 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 1003 | class PyRLockTests(lock_tests.RLockTests): |
| 1004 | locktype = staticmethod(threading._PyRLock) |
| 1005 | |
Charles-François Natali | 6b671b2 | 2012-01-28 11:36:04 +0100 | [diff] [blame] | 1006 | @unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C') |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 1007 | class CRLockTests(lock_tests.RLockTests): |
| 1008 | locktype = staticmethod(threading._CRLock) |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 1009 | |
| 1010 | class EventTests(lock_tests.EventTests): |
| 1011 | eventtype = staticmethod(threading.Event) |
| 1012 | |
| 1013 | class ConditionAsRLockTests(lock_tests.RLockTests): |
| 1014 | # An Condition uses an RLock by default and exports its API. |
| 1015 | locktype = staticmethod(threading.Condition) |
| 1016 | |
| 1017 | class ConditionTests(lock_tests.ConditionTests): |
| 1018 | condtype = staticmethod(threading.Condition) |
| 1019 | |
| 1020 | class SemaphoreTests(lock_tests.SemaphoreTests): |
| 1021 | semtype = staticmethod(threading.Semaphore) |
| 1022 | |
| 1023 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
| 1024 | semtype = staticmethod(threading.BoundedSemaphore) |
| 1025 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 1026 | class BarrierTests(lock_tests.BarrierTests): |
| 1027 | barriertype = staticmethod(threading.Barrier) |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 1028 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 1029 | if __name__ == "__main__": |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 1030 | unittest.main() |