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 | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 4 | from test.support import verbose, strip_python_stderr |
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 |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 8 | _thread = test.support.import_module('_thread') |
| 9 | threading = test.support.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 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 14 | |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 15 | from test import lock_tests |
| 16 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 17 | # A trivial mutable counter. |
| 18 | class Counter(object): |
| 19 | def __init__(self): |
| 20 | self.value = 0 |
| 21 | def inc(self): |
| 22 | self.value += 1 |
| 23 | def dec(self): |
| 24 | self.value -= 1 |
| 25 | def get(self): |
| 26 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 27 | |
| 28 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 29 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 30 | threading.Thread.__init__(self, name=name) |
| 31 | self.testcase = testcase |
| 32 | self.sema = sema |
| 33 | self.mutex = mutex |
| 34 | self.nrunning = nrunning |
| 35 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 36 | def run(self): |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 37 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 38 | if verbose: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 39 | print('task %s will run for %.1f usec' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 40 | (self.name, delay * 1e6)) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 41 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 42 | with self.sema: |
| 43 | with self.mutex: |
| 44 | self.nrunning.inc() |
| 45 | if verbose: |
| 46 | print(self.nrunning.get(), 'tasks are running') |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 47 | self.testcase.assertTrue(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 48 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 49 | time.sleep(delay) |
| 50 | if verbose: |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 51 | print('task', self.name, 'done') |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 52 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 53 | with self.mutex: |
| 54 | self.nrunning.dec() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 55 | self.testcase.assertTrue(self.nrunning.get() >= 0) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 56 | if verbose: |
| 57 | print('%s is finished. %d tasks are running' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 58 | (self.name, self.nrunning.get())) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 59 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 60 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 61 | class BaseTestCase(unittest.TestCase): |
| 62 | def setUp(self): |
| 63 | self._threads = test.support.threading_setup() |
| 64 | |
| 65 | def tearDown(self): |
| 66 | test.support.threading_cleanup(*self._threads) |
| 67 | test.support.reap_children() |
| 68 | |
| 69 | |
| 70 | class ThreadTests(BaseTestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 71 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 72 | # Create a bunch of threads, let each do some work, wait until all are |
| 73 | # done. |
| 74 | def test_various_ops(self): |
| 75 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 76 | # times about 1 second per clump). |
| 77 | NUMTASKS = 10 |
| 78 | |
| 79 | # no more than 3 of the 10 can run at once |
| 80 | sema = threading.BoundedSemaphore(value=3) |
| 81 | mutex = threading.RLock() |
| 82 | numrunning = Counter() |
| 83 | |
| 84 | threads = [] |
| 85 | |
| 86 | for i in range(NUMTASKS): |
| 87 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 88 | threads.append(t) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 89 | self.assertEqual(t.ident, None) |
| 90 | self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 91 | t.start() |
| 92 | |
| 93 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 94 | print('waiting for all tasks to complete') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 95 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 96 | t.join(NUMTASKS) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 97 | self.assertTrue(not t.is_alive()) |
| 98 | self.assertNotEqual(t.ident, 0) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 99 | self.assertFalse(t.ident is None) |
Brett Cannon | 3f5f226 | 2010-07-23 15:50:52 +0000 | [diff] [blame] | 100 | self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>', |
| 101 | repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 102 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 103 | print('all tasks done') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 104 | self.assertEqual(numrunning.get(), 0) |
| 105 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 106 | def test_ident_of_no_threading_threads(self): |
| 107 | # The ident still must work for the main thread and dummy threads. |
| 108 | self.assertFalse(threading.currentThread().ident is None) |
| 109 | def f(): |
| 110 | ident.append(threading.currentThread().ident) |
| 111 | done.set() |
| 112 | done = threading.Event() |
| 113 | ident = [] |
| 114 | _thread.start_new_thread(f, ()) |
| 115 | done.wait() |
| 116 | self.assertFalse(ident[0] is None) |
Antoine Pitrou | ca13a0d | 2009-11-08 00:30:04 +0000 | [diff] [blame] | 117 | # Kill the "immortal" _DummyThread |
| 118 | del threading._active[ident[0]] |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 119 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 120 | # run with a small(ish) thread stack size (256kB) |
| 121 | def test_various_ops_small_stack(self): |
| 122 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 123 | print('with 256kB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 124 | try: |
| 125 | threading.stack_size(262144) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 126 | except _thread.error: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 127 | raise unittest.SkipTest( |
| 128 | 'platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 129 | self.test_various_ops() |
| 130 | threading.stack_size(0) |
| 131 | |
| 132 | # run with a large thread stack size (1MB) |
| 133 | def test_various_ops_large_stack(self): |
| 134 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 135 | print('with 1MB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 136 | try: |
| 137 | threading.stack_size(0x100000) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 138 | except _thread.error: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 139 | raise unittest.SkipTest( |
| 140 | 'platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 141 | self.test_various_ops() |
| 142 | threading.stack_size(0) |
| 143 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 144 | def test_foreign_thread(self): |
| 145 | # Check that a "foreign" thread can use the threading module. |
| 146 | def f(mutex): |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 147 | # Calling current_thread() forces an entry for the foreign |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 148 | # thread to get made in the threading._active map. |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 149 | threading.current_thread() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 150 | mutex.release() |
| 151 | |
| 152 | mutex = threading.Lock() |
| 153 | mutex.acquire() |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 154 | tid = _thread.start_new_thread(f, (mutex,)) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 155 | # Wait for the thread to finish. |
| 156 | mutex.acquire() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 157 | self.assertIn(tid, threading._active) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 158 | self.assertIsInstance(threading._active[tid], threading._DummyThread) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 159 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 160 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 161 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 162 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 163 | def test_PyThreadState_SetAsyncExc(self): |
| 164 | try: |
| 165 | import ctypes |
| 166 | except ImportError: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 167 | raise unittest.SkipTest("cannot import ctypes") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 168 | |
| 169 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 170 | |
| 171 | class AsyncExc(Exception): |
| 172 | pass |
| 173 | |
| 174 | exception = ctypes.py_object(AsyncExc) |
| 175 | |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 176 | # First check it works when setting the exception from the same thread. |
| 177 | tid = _thread.get_ident() |
| 178 | |
| 179 | try: |
| 180 | result = set_async_exc(ctypes.c_long(tid), exception) |
| 181 | # The exception is async, so we might have to keep the VM busy until |
| 182 | # it notices. |
| 183 | while True: |
| 184 | pass |
| 185 | except AsyncExc: |
| 186 | pass |
| 187 | else: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 188 | # This code is unreachable but it reflects the intent. If we wanted |
| 189 | # to be smarter the above loop wouldn't be infinite. |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 190 | self.fail("AsyncExc not raised") |
| 191 | try: |
| 192 | self.assertEqual(result, 1) # one thread state modified |
| 193 | except UnboundLocalError: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 194 | # The exception was raised too quickly for us to get the result. |
Antoine Pitrou | be4d809 | 2009-10-18 18:27:17 +0000 | [diff] [blame] | 195 | pass |
| 196 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 197 | # `worker_started` is set by the thread when it's inside a try/except |
| 198 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 199 | # `worker_saw_exception` is set by the thread upon catching that |
| 200 | # exception. |
| 201 | worker_started = threading.Event() |
| 202 | worker_saw_exception = threading.Event() |
| 203 | |
| 204 | class Worker(threading.Thread): |
| 205 | def run(self): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 206 | self.id = _thread.get_ident() |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 207 | self.finished = False |
| 208 | |
| 209 | try: |
| 210 | while True: |
| 211 | worker_started.set() |
| 212 | time.sleep(0.1) |
| 213 | except AsyncExc: |
| 214 | self.finished = True |
| 215 | worker_saw_exception.set() |
| 216 | |
| 217 | t = Worker() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 218 | 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] | 219 | t.start() |
| 220 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 221 | print(" started worker thread") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 222 | |
| 223 | # Try a thread id that doesn't make sense. |
| 224 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 225 | print(" trying nonsensical thread id") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 226 | result = set_async_exc(ctypes.c_long(-1), exception) |
| 227 | self.assertEqual(result, 0) # no thread states modified |
| 228 | |
| 229 | # Now raise an exception in the worker thread. |
| 230 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 231 | print(" waiting for worker thread to get started") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 232 | ret = worker_started.wait() |
| 233 | self.assertTrue(ret) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 234 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 235 | print(" verifying worker hasn't exited") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 236 | self.assertTrue(not t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 237 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 238 | print(" attempting to raise asynch exception in worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 239 | result = set_async_exc(ctypes.c_long(t.id), exception) |
| 240 | self.assertEqual(result, 1) # one thread state modified |
| 241 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 242 | print(" waiting for worker to say it caught the exception") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 243 | worker_saw_exception.wait(timeout=10) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 244 | self.assertTrue(t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 245 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 246 | print(" all OK -- joining worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 247 | if t.finished: |
| 248 | t.join() |
| 249 | # else the thread is still running, and we have no way to kill it |
| 250 | |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 251 | def test_limbo_cleanup(self): |
| 252 | # Issue 7481: Failure to start thread should cleanup the limbo map. |
| 253 | def fail_new_thread(*args): |
| 254 | raise threading.ThreadError() |
| 255 | _start_new_thread = threading._start_new_thread |
| 256 | threading._start_new_thread = fail_new_thread |
| 257 | try: |
| 258 | t = threading.Thread(target=lambda: None) |
Gregory P. Smith | f50f168 | 2010-03-01 03:13:36 +0000 | [diff] [blame] | 259 | self.assertRaises(threading.ThreadError, t.start) |
| 260 | self.assertFalse( |
| 261 | t in threading._limbo, |
| 262 | "Failed to cleanup _limbo map on failure of Thread.start().") |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 263 | finally: |
| 264 | threading._start_new_thread = _start_new_thread |
| 265 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 266 | def test_finalize_runnning_thread(self): |
| 267 | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
| 268 | # very late on python exit: on deallocation of a running thread for |
| 269 | # example. |
| 270 | try: |
| 271 | import ctypes |
| 272 | except ImportError: |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 273 | raise unittest.SkipTest("cannot import ctypes") |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 274 | |
| 275 | import subprocess |
| 276 | rc = subprocess.call([sys.executable, "-c", """if 1: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 277 | import ctypes, sys, time, _thread |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 278 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 279 | # This lock is used as a simple event variable. |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 280 | ready = _thread.allocate_lock() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 281 | ready.acquire() |
| 282 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 283 | # Module globals are cleared before __del__ is run |
| 284 | # So we save the functions in class dict |
| 285 | class C: |
| 286 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 287 | release = ctypes.pythonapi.PyGILState_Release |
| 288 | def __del__(self): |
| 289 | state = self.ensure() |
| 290 | self.release(state) |
| 291 | |
| 292 | def waitingThread(): |
| 293 | x = C() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 294 | ready.release() |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 295 | time.sleep(100) |
| 296 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 297 | _thread.start_new_thread(waitingThread, ()) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 298 | ready.acquire() # Be sure the other thread is waiting. |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 299 | sys.exit(42) |
| 300 | """]) |
| 301 | self.assertEqual(rc, 42) |
| 302 | |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 303 | def test_finalize_with_trace(self): |
| 304 | # Issue1733757 |
| 305 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
| 306 | import subprocess |
Antoine Pitrou | 7c08744 | 2010-09-19 23:28:30 +0000 | [diff] [blame] | 307 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 308 | import sys, threading |
| 309 | |
| 310 | # A deadlock-killer, to prevent the |
| 311 | # testsuite to hang forever |
| 312 | def killer(): |
| 313 | import os, time |
| 314 | time.sleep(2) |
| 315 | print('program blocked; aborting') |
| 316 | os._exit(2) |
| 317 | t = threading.Thread(target=killer) |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 318 | t.daemon = True |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 319 | t.start() |
| 320 | |
| 321 | # This is the trace function |
| 322 | def func(frame, event, arg): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 323 | threading.current_thread() |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 324 | return func |
| 325 | |
| 326 | sys.settrace(func) |
Antoine Pitrou | 7c08744 | 2010-09-19 23:28:30 +0000 | [diff] [blame] | 327 | """], |
| 328 | stdout=subprocess.PIPE, |
| 329 | stderr=subprocess.PIPE) |
| 330 | stdout, stderr = p.communicate() |
| 331 | rc = p.returncode |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 332 | self.assertFalse(rc == 2, "interpreted was blocked") |
Antoine Pitrou | 7c08744 | 2010-09-19 23:28:30 +0000 | [diff] [blame] | 333 | self.assertTrue(rc == 0, |
| 334 | "Unexpected error: " + ascii(stderr)) |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 335 | |
Antoine Pitrou | 011bd62 | 2009-10-20 21:52:47 +0000 | [diff] [blame] | 336 | def test_join_nondaemon_on_shutdown(self): |
| 337 | # Issue 1722344 |
| 338 | # Raising SystemExit skipped threading._shutdown |
| 339 | import subprocess |
| 340 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 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 |
| 352 | """], |
| 353 | stdout=subprocess.PIPE, |
| 354 | stderr=subprocess.PIPE) |
| 355 | stdout, stderr = p.communicate() |
Antoine Pitrou | 899d1c6 | 2009-10-23 21:55:36 +0000 | [diff] [blame] | 356 | self.assertEqual(stdout.strip(), |
| 357 | b"Woke up, sleep function is: <built-in function sleep>") |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 358 | stderr = strip_python_stderr(stderr) |
Antoine Pitrou | 011bd62 | 2009-10-20 21:52:47 +0000 | [diff] [blame] | 359 | self.assertEqual(stderr, b"") |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 360 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 361 | def test_enumerate_after_join(self): |
| 362 | # Try hard to trigger #1703448: a thread is still returned in |
| 363 | # threading.enumerate() after it has been join()ed. |
| 364 | enum = threading.enumerate |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 365 | old_interval = sys.getswitchinterval() |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 366 | try: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 367 | for i in range(1, 100): |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 368 | sys.setswitchinterval(i * 0.0002) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 369 | t = threading.Thread(target=lambda: None) |
| 370 | t.start() |
| 371 | t.join() |
| 372 | l = enum() |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 373 | self.assertNotIn(t, l, |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 374 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 375 | finally: |
Antoine Pitrou | c3b0757 | 2009-11-13 22:19:19 +0000 | [diff] [blame] | 376 | sys.setswitchinterval(old_interval) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 377 | |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 378 | def test_no_refcycle_through_target(self): |
| 379 | class RunSelfFunction(object): |
| 380 | def __init__(self, should_raise): |
| 381 | # The links in this refcycle from Thread back to self |
| 382 | # should be cleaned up when the thread completes. |
| 383 | self.should_raise = should_raise |
| 384 | self.thread = threading.Thread(target=self._run, |
| 385 | args=(self,), |
| 386 | kwargs={'yet_another':self}) |
| 387 | self.thread.start() |
| 388 | |
| 389 | def _run(self, other_ref, yet_another): |
| 390 | if self.should_raise: |
| 391 | raise SystemExit |
| 392 | |
| 393 | cyclic_object = RunSelfFunction(should_raise=False) |
| 394 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 395 | cyclic_object.thread.join() |
| 396 | del cyclic_object |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 397 | self.assertEquals(None, weak_cyclic_object(), |
| 398 | msg=('%d references still around' % |
| 399 | sys.getrefcount(weak_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 400 | |
| 401 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 402 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 403 | raising_cyclic_object.thread.join() |
| 404 | del raising_cyclic_object |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 405 | self.assertEquals(None, weak_raising_cyclic_object(), |
| 406 | msg=('%d references still around' % |
| 407 | sys.getrefcount(weak_raising_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 408 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 409 | def test_old_threading_api(self): |
| 410 | # Just a quick sanity check to make sure the old method names are |
| 411 | # still present |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 412 | t = threading.Thread() |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 413 | t.isDaemon() |
| 414 | t.setDaemon(True) |
| 415 | t.getName() |
| 416 | t.setName("name") |
| 417 | t.isAlive() |
| 418 | e = threading.Event() |
| 419 | e.isSet() |
| 420 | threading.activeCount() |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 421 | |
Brian Curtin | 81a4a6a | 2010-07-23 16:30:10 +0000 | [diff] [blame] | 422 | def test_repr_daemon(self): |
| 423 | t = threading.Thread() |
| 424 | self.assertFalse('daemon' in repr(t)) |
| 425 | t.daemon = True |
| 426 | self.assertTrue('daemon' in repr(t)) |
Brett Cannon | 3f5f226 | 2010-07-23 15:50:52 +0000 | [diff] [blame] | 427 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 428 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 429 | class ThreadJoinOnShutdown(BaseTestCase): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 430 | |
| 431 | def _run_and_join(self, script): |
| 432 | script = """if 1: |
| 433 | import sys, os, time, threading |
| 434 | |
| 435 | # a thread, which waits for the main program to terminate |
| 436 | def joiningfunc(mainthread): |
| 437 | mainthread.join() |
| 438 | print('end of thread') |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 439 | # stdout is fully buffered because not a tty, we have to flush |
| 440 | # before exit. |
| 441 | sys.stdout.flush() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 442 | \n""" + script |
| 443 | |
| 444 | import subprocess |
| 445 | p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) |
| 446 | rc = p.wait() |
Benjamin Peterson | ad703dc | 2008-07-17 17:02:57 +0000 | [diff] [blame] | 447 | data = p.stdout.read().decode().replace('\r', '') |
| 448 | self.assertEqual(data, "end of main\nend of thread\n") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 449 | self.assertFalse(rc == 2, "interpreter was blocked") |
| 450 | self.assertTrue(rc == 0, "Unexpected error") |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 451 | |
| 452 | def test_1_join_on_shutdown(self): |
| 453 | # The usual case: on exit, wait for a non-daemon thread |
| 454 | script = """if 1: |
| 455 | import os |
| 456 | t = threading.Thread(target=joiningfunc, |
| 457 | args=(threading.current_thread(),)) |
| 458 | t.start() |
| 459 | time.sleep(0.1) |
| 460 | print('end of main') |
| 461 | """ |
| 462 | self._run_and_join(script) |
| 463 | |
| 464 | |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 465 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 466 | def test_2_join_in_forked_process(self): |
| 467 | # Like the test above, but from a forked interpreter |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 468 | script = """if 1: |
| 469 | childpid = os.fork() |
| 470 | if childpid != 0: |
| 471 | os.waitpid(childpid, 0) |
| 472 | sys.exit(0) |
| 473 | |
| 474 | t = threading.Thread(target=joiningfunc, |
| 475 | args=(threading.current_thread(),)) |
| 476 | t.start() |
| 477 | print('end of main') |
| 478 | """ |
| 479 | self._run_and_join(script) |
| 480 | |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 481 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 482 | def test_3_join_in_forked_from_thread(self): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 483 | # Like the test above, but fork() was called from a worker thread |
| 484 | # 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] | 485 | |
Benjamin Peterson | bcd8ac3 | 2008-10-10 22:20:52 +0000 | [diff] [blame] | 486 | # Skip platforms with known problems forking from a worker thread. |
| 487 | # See http://bugs.python.org/issue3863. |
| 488 | if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): |
Alexandre Vassalotti | 93f2cd2 | 2009-07-22 04:54:52 +0000 | [diff] [blame] | 489 | raise unittest.SkipTest('due to known OS bugs on ' + sys.platform) |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 490 | script = """if 1: |
| 491 | main_thread = threading.current_thread() |
| 492 | def worker(): |
| 493 | childpid = os.fork() |
| 494 | if childpid != 0: |
| 495 | os.waitpid(childpid, 0) |
| 496 | sys.exit(0) |
| 497 | |
| 498 | t = threading.Thread(target=joiningfunc, |
| 499 | args=(main_thread,)) |
| 500 | print('end of main') |
| 501 | t.start() |
| 502 | t.join() # Should not block: main_thread is already stopped |
| 503 | |
| 504 | w = threading.Thread(target=worker) |
| 505 | w.start() |
| 506 | """ |
| 507 | self._run_and_join(script) |
| 508 | |
| 509 | |
Antoine Pitrou | b0e9bd4 | 2009-10-27 20:05:26 +0000 | [diff] [blame] | 510 | class ThreadingExceptionTests(BaseTestCase): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 511 | # A RuntimeError should be raised if Thread.start() is called |
| 512 | # multiple times. |
| 513 | def test_start_thread_again(self): |
| 514 | thread = threading.Thread() |
| 515 | thread.start() |
| 516 | self.assertRaises(RuntimeError, thread.start) |
| 517 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 518 | def test_joining_current_thread(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 519 | current_thread = threading.current_thread() |
| 520 | self.assertRaises(RuntimeError, current_thread.join); |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 521 | |
| 522 | def test_joining_inactive_thread(self): |
| 523 | thread = threading.Thread() |
| 524 | self.assertRaises(RuntimeError, thread.join) |
| 525 | |
| 526 | def test_daemonize_active_thread(self): |
| 527 | thread = threading.Thread() |
| 528 | thread.start() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 529 | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 530 | |
| 531 | |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 532 | class LockTests(lock_tests.LockTests): |
| 533 | locktype = staticmethod(threading.Lock) |
| 534 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 535 | class PyRLockTests(lock_tests.RLockTests): |
| 536 | locktype = staticmethod(threading._PyRLock) |
| 537 | |
| 538 | class CRLockTests(lock_tests.RLockTests): |
| 539 | locktype = staticmethod(threading._CRLock) |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 540 | |
| 541 | class EventTests(lock_tests.EventTests): |
| 542 | eventtype = staticmethod(threading.Event) |
| 543 | |
| 544 | class ConditionAsRLockTests(lock_tests.RLockTests): |
| 545 | # An Condition uses an RLock by default and exports its API. |
| 546 | locktype = staticmethod(threading.Condition) |
| 547 | |
| 548 | class ConditionTests(lock_tests.ConditionTests): |
| 549 | condtype = staticmethod(threading.Condition) |
| 550 | |
| 551 | class SemaphoreTests(lock_tests.SemaphoreTests): |
| 552 | semtype = staticmethod(threading.Semaphore) |
| 553 | |
| 554 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
| 555 | semtype = staticmethod(threading.BoundedSemaphore) |
| 556 | |
| 557 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 558 | def test_main(): |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 559 | test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests, |
Antoine Pitrou | 557934f | 2009-11-06 22:41:14 +0000 | [diff] [blame] | 560 | ConditionAsRLockTests, ConditionTests, |
| 561 | SemaphoreTests, BoundedSemaphoreTests, |
| 562 | ThreadTests, |
| 563 | ThreadJoinOnShutdown, |
| 564 | ThreadingExceptionTests, |
| 565 | ) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 566 | |
| 567 | if __name__ == "__main__": |
| 568 | test_main() |