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 |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 4 | from test.support import verbose |
Gregory P. Smith | 4b129d2 | 2011-01-04 00:51:50 +0000 | [diff] [blame] | 5 | import os |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 6 | import random |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 7 | import re |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 8 | import sys |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 9 | import threading |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 10 | import _thread |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 11 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 12 | import unittest |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 13 | import weakref |
Gregory P. Smith | 4b129d2 | 2011-01-04 00:51:50 +0000 | [diff] [blame] | 14 | import subprocess |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 15 | |
Antoine Pitrou | 959f3e5 | 2009-11-09 16:52:46 +0000 | [diff] [blame] | 16 | from test import lock_tests |
| 17 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 18 | # A trivial mutable counter. |
| 19 | class Counter(object): |
| 20 | def __init__(self): |
| 21 | self.value = 0 |
| 22 | def inc(self): |
| 23 | self.value += 1 |
| 24 | def dec(self): |
| 25 | self.value -= 1 |
| 26 | def get(self): |
| 27 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 28 | |
| 29 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 30 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 31 | threading.Thread.__init__(self, name=name) |
| 32 | self.testcase = testcase |
| 33 | self.sema = sema |
| 34 | self.mutex = mutex |
| 35 | self.nrunning = nrunning |
| 36 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 37 | def run(self): |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 38 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 39 | if verbose: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 40 | print('task %s will run for %.1f usec' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 41 | (self.name, delay * 1e6)) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 42 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 43 | with self.sema: |
| 44 | with self.mutex: |
| 45 | self.nrunning.inc() |
| 46 | if verbose: |
| 47 | print(self.nrunning.get(), 'tasks are running') |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 48 | self.testcase.assertTrue(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 49 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 50 | time.sleep(delay) |
| 51 | if verbose: |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 52 | print('task', self.name, 'done') |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 53 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 54 | with self.mutex: |
| 55 | self.nrunning.dec() |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 56 | self.testcase.assertTrue(self.nrunning.get() >= 0) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 57 | if verbose: |
| 58 | print('%s is finished. %d tasks are running' % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 59 | (self.name, self.nrunning.get())) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 60 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 61 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 62 | class ThreadTests(unittest.TestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 63 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 64 | # Create a bunch of threads, let each do some work, wait until all are |
| 65 | # done. |
| 66 | def test_various_ops(self): |
| 67 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 68 | # times about 1 second per clump). |
| 69 | NUMTASKS = 10 |
| 70 | |
| 71 | # no more than 3 of the 10 can run at once |
| 72 | sema = threading.BoundedSemaphore(value=3) |
| 73 | mutex = threading.RLock() |
| 74 | numrunning = Counter() |
| 75 | |
| 76 | threads = [] |
| 77 | |
| 78 | for i in range(NUMTASKS): |
| 79 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 80 | threads.append(t) |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 81 | self.assertEqual(t.ident, None) |
| 82 | self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 83 | t.start() |
| 84 | |
| 85 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 86 | print('waiting for all tasks to complete') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 87 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 88 | t.join(NUMTASKS) |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 89 | self.assertTrue(not t.is_alive()) |
| 90 | self.assertNotEqual(t.ident, 0) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 91 | self.assertFalse(t.ident is None) |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 92 | self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 93 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 94 | print('all tasks done') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 95 | self.assertEqual(numrunning.get(), 0) |
| 96 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 97 | def test_ident_of_no_threading_threads(self): |
| 98 | # The ident still must work for the main thread and dummy threads. |
| 99 | self.assertFalse(threading.currentThread().ident is None) |
| 100 | def f(): |
| 101 | ident.append(threading.currentThread().ident) |
| 102 | done.set() |
| 103 | done = threading.Event() |
| 104 | ident = [] |
| 105 | _thread.start_new_thread(f, ()) |
| 106 | done.wait() |
| 107 | self.assertFalse(ident[0] is None) |
Antoine Pitrou | debfafd | 2009-11-08 00:36:36 +0000 | [diff] [blame] | 108 | # Kill the "immortal" _DummyThread |
| 109 | del threading._active[ident[0]] |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 110 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 111 | # run with a small(ish) thread stack size (256kB) |
| 112 | def test_various_ops_small_stack(self): |
| 113 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 114 | print('with 256kB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 115 | try: |
| 116 | threading.stack_size(262144) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 117 | except _thread.error: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 118 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 119 | print('platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 120 | return |
| 121 | self.test_various_ops() |
| 122 | threading.stack_size(0) |
| 123 | |
| 124 | # run with a large thread stack size (1MB) |
| 125 | def test_various_ops_large_stack(self): |
| 126 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 127 | print('with 1MB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 128 | try: |
| 129 | threading.stack_size(0x100000) |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 130 | except _thread.error: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 131 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 132 | print('platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 133 | return |
| 134 | self.test_various_ops() |
| 135 | threading.stack_size(0) |
| 136 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 137 | def test_foreign_thread(self): |
| 138 | # Check that a "foreign" thread can use the threading module. |
| 139 | def f(mutex): |
Antoine Pitrou | 959f3e5 | 2009-11-09 16:52:46 +0000 | [diff] [blame] | 140 | # Calling current_thread() forces an entry for the foreign |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 141 | # thread to get made in the threading._active map. |
Antoine Pitrou | 959f3e5 | 2009-11-09 16:52:46 +0000 | [diff] [blame] | 142 | threading.current_thread() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 143 | mutex.release() |
| 144 | |
| 145 | mutex = threading.Lock() |
| 146 | mutex.acquire() |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 147 | tid = _thread.start_new_thread(f, (mutex,)) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 148 | # Wait for the thread to finish. |
| 149 | mutex.acquire() |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 150 | self.assertTrue(tid in threading._active) |
| 151 | self.assertTrue(isinstance(threading._active[tid], |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 152 | threading._DummyThread)) |
| 153 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 154 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 155 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 156 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 157 | def test_PyThreadState_SetAsyncExc(self): |
| 158 | try: |
| 159 | import ctypes |
| 160 | except ImportError: |
| 161 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 162 | print("test_PyThreadState_SetAsyncExc can't import ctypes") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 163 | return # can't do anything |
| 164 | |
| 165 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 166 | |
| 167 | class AsyncExc(Exception): |
| 168 | pass |
| 169 | |
| 170 | exception = ctypes.py_object(AsyncExc) |
| 171 | |
| 172 | # `worker_started` is set by the thread when it's inside a try/except |
| 173 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 174 | # `worker_saw_exception` is set by the thread upon catching that |
| 175 | # exception. |
| 176 | worker_started = threading.Event() |
| 177 | worker_saw_exception = threading.Event() |
| 178 | |
| 179 | class Worker(threading.Thread): |
| 180 | def run(self): |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 181 | self.id = _thread.get_ident() |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 182 | self.finished = False |
| 183 | |
| 184 | try: |
| 185 | while True: |
| 186 | worker_started.set() |
| 187 | time.sleep(0.1) |
| 188 | except AsyncExc: |
| 189 | self.finished = True |
| 190 | worker_saw_exception.set() |
| 191 | |
| 192 | t = Worker() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 193 | 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] | 194 | t.start() |
| 195 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 196 | print(" started worker thread") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 197 | |
| 198 | # Try a thread id that doesn't make sense. |
| 199 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 200 | print(" trying nonsensical thread id") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 201 | result = set_async_exc(ctypes.c_long(-1), exception) |
| 202 | self.assertEqual(result, 0) # no thread states modified |
| 203 | |
| 204 | # Now raise an exception in the worker thread. |
| 205 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 206 | print(" waiting for worker thread to get started") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 207 | ret = worker_started.wait() |
| 208 | self.assertTrue(ret) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 209 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 210 | print(" verifying worker hasn't exited") |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 211 | self.assertTrue(not t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 212 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 213 | print(" attempting to raise asynch exception in worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 214 | result = set_async_exc(ctypes.c_long(t.id), exception) |
| 215 | self.assertEqual(result, 1) # one thread state modified |
| 216 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 217 | print(" waiting for worker to say it caught the exception") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 218 | worker_saw_exception.wait(timeout=10) |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 219 | self.assertTrue(t.finished) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 220 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 221 | print(" all OK -- joining worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 222 | if t.finished: |
| 223 | t.join() |
| 224 | # else the thread is still running, and we have no way to kill it |
| 225 | |
Gregory P. Smith | 31d12ca | 2010-02-28 19:21:42 +0000 | [diff] [blame] | 226 | def test_limbo_cleanup(self): |
| 227 | # Issue 7481: Failure to start thread should cleanup the limbo map. |
| 228 | def fail_new_thread(*args): |
| 229 | raise threading.ThreadError() |
| 230 | _start_new_thread = threading._start_new_thread |
| 231 | threading._start_new_thread = fail_new_thread |
| 232 | try: |
| 233 | t = threading.Thread(target=lambda: None) |
Gregory P. Smith | ff31864 | 2010-03-01 03:19:29 +0000 | [diff] [blame] | 234 | self.assertRaises(threading.ThreadError, t.start) |
| 235 | self.assertFalse( |
| 236 | t in threading._limbo, |
| 237 | "Failed to cleanup _limbo map on failure of Thread.start().") |
Gregory P. Smith | 31d12ca | 2010-02-28 19:21:42 +0000 | [diff] [blame] | 238 | finally: |
| 239 | threading._start_new_thread = _start_new_thread |
| 240 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 241 | def test_finalize_runnning_thread(self): |
| 242 | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
| 243 | # very late on python exit: on deallocation of a running thread for |
| 244 | # example. |
| 245 | try: |
| 246 | import ctypes |
| 247 | except ImportError: |
| 248 | if verbose: |
| 249 | print("test_finalize_with_runnning_thread can't import ctypes") |
| 250 | return # can't do anything |
| 251 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 252 | rc = subprocess.call([sys.executable, "-c", """if 1: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 253 | import ctypes, sys, time, _thread |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 254 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 255 | # This lock is used as a simple event variable. |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 256 | ready = _thread.allocate_lock() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 257 | ready.acquire() |
| 258 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 259 | # Module globals are cleared before __del__ is run |
| 260 | # So we save the functions in class dict |
| 261 | class C: |
| 262 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 263 | release = ctypes.pythonapi.PyGILState_Release |
| 264 | def __del__(self): |
| 265 | state = self.ensure() |
| 266 | self.release(state) |
| 267 | |
| 268 | def waitingThread(): |
| 269 | x = C() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 270 | ready.release() |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 271 | time.sleep(100) |
| 272 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 273 | _thread.start_new_thread(waitingThread, ()) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 274 | ready.acquire() # Be sure the other thread is waiting. |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 275 | sys.exit(42) |
| 276 | """]) |
| 277 | self.assertEqual(rc, 42) |
| 278 | |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 279 | def test_finalize_with_trace(self): |
| 280 | # Issue1733757 |
| 281 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
Antoine Pitrou | 4a5dd5c | 2010-09-20 11:17:39 +0000 | [diff] [blame] | 282 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 283 | import sys, threading |
| 284 | |
| 285 | # A deadlock-killer, to prevent the |
| 286 | # testsuite to hang forever |
| 287 | def killer(): |
| 288 | import os, time |
| 289 | time.sleep(2) |
| 290 | print('program blocked; aborting') |
| 291 | os._exit(2) |
| 292 | t = threading.Thread(target=killer) |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 293 | t.daemon = True |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 294 | t.start() |
| 295 | |
| 296 | # This is the trace function |
| 297 | def func(frame, event, arg): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 298 | threading.current_thread() |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 299 | return func |
| 300 | |
| 301 | sys.settrace(func) |
Antoine Pitrou | 4a5dd5c | 2010-09-20 11:17:39 +0000 | [diff] [blame] | 302 | """], |
| 303 | stdout=subprocess.PIPE, |
| 304 | stderr=subprocess.PIPE) |
| 305 | stdout, stderr = p.communicate() |
| 306 | rc = p.returncode |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 307 | self.assertFalse(rc == 2, "interpreted was blocked") |
Antoine Pitrou | 4a5dd5c | 2010-09-20 11:17:39 +0000 | [diff] [blame] | 308 | self.assertTrue(rc == 0, |
| 309 | "Unexpected error: " + ascii(stderr)) |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 310 | |
Antoine Pitrou | cefb316 | 2009-10-20 22:08:36 +0000 | [diff] [blame] | 311 | def test_join_nondaemon_on_shutdown(self): |
| 312 | # Issue 1722344 |
| 313 | # Raising SystemExit skipped threading._shutdown |
Antoine Pitrou | cefb316 | 2009-10-20 22:08:36 +0000 | [diff] [blame] | 314 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 315 | import threading |
| 316 | from time import sleep |
| 317 | |
| 318 | def child(): |
| 319 | sleep(1) |
| 320 | # As a non-daemon thread we SHOULD wake up and nothing |
| 321 | # should be torn down yet |
| 322 | print("Woke up, sleep function is:", sleep) |
| 323 | |
| 324 | threading.Thread(target=child).start() |
| 325 | raise SystemExit |
| 326 | """], |
| 327 | stdout=subprocess.PIPE, |
| 328 | stderr=subprocess.PIPE) |
| 329 | stdout, stderr = p.communicate() |
Antoine Pitrou | f6779fb | 2009-10-23 22:06:37 +0000 | [diff] [blame] | 330 | self.assertEqual(stdout.strip(), |
| 331 | b"Woke up, sleep function is: <built-in function sleep>") |
Antoine Pitrou | cefb316 | 2009-10-20 22:08:36 +0000 | [diff] [blame] | 332 | stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip() |
| 333 | self.assertEqual(stderr, b"") |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 334 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 335 | def test_enumerate_after_join(self): |
| 336 | # Try hard to trigger #1703448: a thread is still returned in |
| 337 | # threading.enumerate() after it has been join()ed. |
| 338 | enum = threading.enumerate |
| 339 | old_interval = sys.getcheckinterval() |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 340 | try: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 341 | for i in range(1, 100): |
| 342 | # Try a couple times at each thread-switching interval |
| 343 | # to get more interleavings. |
| 344 | sys.setcheckinterval(i // 5) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 345 | t = threading.Thread(target=lambda: None) |
| 346 | t.start() |
| 347 | t.join() |
| 348 | l = enum() |
| 349 | self.assertFalse(t in l, |
| 350 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 351 | finally: |
| 352 | sys.setcheckinterval(old_interval) |
| 353 | |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 354 | def test_no_refcycle_through_target(self): |
| 355 | class RunSelfFunction(object): |
| 356 | def __init__(self, should_raise): |
| 357 | # The links in this refcycle from Thread back to self |
| 358 | # should be cleaned up when the thread completes. |
| 359 | self.should_raise = should_raise |
| 360 | self.thread = threading.Thread(target=self._run, |
| 361 | args=(self,), |
| 362 | kwargs={'yet_another':self}) |
| 363 | self.thread.start() |
| 364 | |
| 365 | def _run(self, other_ref, yet_another): |
| 366 | if self.should_raise: |
| 367 | raise SystemExit |
| 368 | |
| 369 | cyclic_object = RunSelfFunction(should_raise=False) |
| 370 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 371 | cyclic_object.thread.join() |
| 372 | del cyclic_object |
Ezio Melotti | 19f2aeb | 2010-11-21 01:30:29 +0000 | [diff] [blame] | 373 | self.assertEqual(None, weak_cyclic_object(), |
| 374 | msg=('%d references still around' % |
| 375 | sys.getrefcount(weak_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 376 | |
| 377 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 378 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 379 | raising_cyclic_object.thread.join() |
| 380 | del raising_cyclic_object |
Ezio Melotti | 19f2aeb | 2010-11-21 01:30:29 +0000 | [diff] [blame] | 381 | self.assertEqual(None, weak_raising_cyclic_object(), |
| 382 | msg=('%d references still around' % |
| 383 | sys.getrefcount(weak_raising_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 384 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 385 | def test_old_threading_api(self): |
| 386 | # Just a quick sanity check to make sure the old method names are |
| 387 | # still present |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 388 | t = threading.Thread() |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 389 | t.isDaemon() |
| 390 | t.setDaemon(True) |
| 391 | t.getName() |
| 392 | t.setName("name") |
| 393 | t.isAlive() |
| 394 | e = threading.Event() |
| 395 | e.isSet() |
| 396 | threading.activeCount() |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 397 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 398 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 399 | class ThreadJoinOnShutdown(unittest.TestCase): |
| 400 | |
| 401 | def _run_and_join(self, script): |
| 402 | script = """if 1: |
| 403 | import sys, os, time, threading |
| 404 | |
| 405 | # a thread, which waits for the main program to terminate |
| 406 | def joiningfunc(mainthread): |
| 407 | mainthread.join() |
| 408 | print('end of thread') |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 409 | # stdout is fully buffered because not a tty, we have to flush |
| 410 | # before exit. |
| 411 | sys.stdout.flush() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 412 | \n""" + script |
| 413 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 414 | p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) |
| 415 | rc = p.wait() |
Benjamin Peterson | ad703dc | 2008-07-17 17:02:57 +0000 | [diff] [blame] | 416 | data = p.stdout.read().decode().replace('\r', '') |
Brian Curtin | e509ff4 | 2010-11-02 04:01:17 +0000 | [diff] [blame] | 417 | p.stdout.close() |
Benjamin Peterson | ad703dc | 2008-07-17 17:02:57 +0000 | [diff] [blame] | 418 | self.assertEqual(data, "end of main\nend of thread\n") |
Georg Brandl | ab91fde | 2009-08-13 08:51:18 +0000 | [diff] [blame] | 419 | self.assertFalse(rc == 2, "interpreter was blocked") |
| 420 | self.assertTrue(rc == 0, "Unexpected error") |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 421 | |
| 422 | def test_1_join_on_shutdown(self): |
| 423 | # The usual case: on exit, wait for a non-daemon thread |
| 424 | script = """if 1: |
| 425 | import os |
| 426 | t = threading.Thread(target=joiningfunc, |
| 427 | args=(threading.current_thread(),)) |
| 428 | t.start() |
| 429 | time.sleep(0.1) |
| 430 | print('end of main') |
| 431 | """ |
| 432 | self._run_and_join(script) |
| 433 | |
| 434 | |
| 435 | def test_2_join_in_forked_process(self): |
| 436 | # Like the test above, but from a forked interpreter |
| 437 | import os |
| 438 | if not hasattr(os, 'fork'): |
| 439 | return |
| 440 | script = """if 1: |
| 441 | childpid = os.fork() |
| 442 | if childpid != 0: |
| 443 | os.waitpid(childpid, 0) |
| 444 | sys.exit(0) |
| 445 | |
| 446 | t = threading.Thread(target=joiningfunc, |
| 447 | args=(threading.current_thread(),)) |
| 448 | t.start() |
| 449 | print('end of main') |
| 450 | """ |
| 451 | self._run_and_join(script) |
| 452 | |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 453 | def test_3_join_in_forked_from_thread(self): |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 454 | # Like the test above, but fork() was called from a worker thread |
| 455 | # In the forked process, the main Thread object must be marked as stopped. |
| 456 | import os |
| 457 | if not hasattr(os, 'fork'): |
| 458 | return |
Benjamin Peterson | bcd8ac3 | 2008-10-10 22:20:52 +0000 | [diff] [blame] | 459 | # Skip platforms with known problems forking from a worker thread. |
| 460 | # See http://bugs.python.org/issue3863. |
Gregory P. Smith | 397cd8a | 2010-10-17 04:23:21 +0000 | [diff] [blame] | 461 | if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', |
| 462 | 'os2emx'): |
R. David Murray | 9948da0 | 2009-10-26 03:27:32 +0000 | [diff] [blame] | 463 | print('Skipping test_3_join_in_forked_from_thread' |
| 464 | ' due to known OS bugs on', sys.platform, file=sys.stderr) |
Benjamin Peterson | bcd8ac3 | 2008-10-10 22:20:52 +0000 | [diff] [blame] | 465 | return |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 466 | script = """if 1: |
| 467 | main_thread = threading.current_thread() |
| 468 | def worker(): |
| 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=(main_thread,)) |
| 476 | print('end of main') |
| 477 | t.start() |
| 478 | t.join() # Should not block: main_thread is already stopped |
| 479 | |
| 480 | w = threading.Thread(target=worker) |
| 481 | w.start() |
| 482 | """ |
| 483 | self._run_and_join(script) |
| 484 | |
Gregory P. Smith | 4b129d2 | 2011-01-04 00:51:50 +0000 | [diff] [blame] | 485 | def assertScriptHasOutput(self, script, expected_output): |
| 486 | p = subprocess.Popen([sys.executable, "-c", script], |
| 487 | stdout=subprocess.PIPE) |
| 488 | rc = p.wait() |
| 489 | data = p.stdout.read().decode().replace('\r', '') |
| 490 | self.assertEqual(rc, 0, "Unexpected error") |
| 491 | self.assertEqual(data, expected_output) |
| 492 | |
| 493 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 494 | def test_4_joining_across_fork_in_worker_thread(self): |
| 495 | # There used to be a possible deadlock when forking from a child |
| 496 | # thread. See http://bugs.python.org/issue6643. |
| 497 | |
| 498 | # Skip platforms with known problems forking from a worker thread. |
| 499 | # See http://bugs.python.org/issue3863. |
| 500 | if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): |
| 501 | raise unittest.SkipTest('due to known OS bugs on ' + sys.platform) |
| 502 | |
| 503 | # The script takes the following steps: |
| 504 | # - The main thread in the parent process starts a new thread and then |
| 505 | # tries to join it. |
| 506 | # - The join operation acquires the Lock inside the thread's _block |
| 507 | # Condition. (See threading.py:Thread.join().) |
| 508 | # - We stub out the acquire method on the condition to force it to wait |
| 509 | # until the child thread forks. (See LOCK ACQUIRED HERE) |
| 510 | # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS |
| 511 | # HERE) |
| 512 | # - The main thread of the parent process enters Condition.wait(), |
| 513 | # which releases the lock on the child thread. |
| 514 | # - The child process returns. Without the necessary fix, when the |
| 515 | # main thread of the child process (which used to be the child thread |
| 516 | # in the parent process) attempts to exit, it will try to acquire the |
| 517 | # lock in the Thread._block Condition object and hang, because the |
| 518 | # lock was held across the fork. |
| 519 | |
| 520 | script = """if 1: |
| 521 | import os, time, threading |
| 522 | |
| 523 | finish_join = False |
| 524 | start_fork = False |
| 525 | |
| 526 | def worker(): |
| 527 | # Wait until this thread's lock is acquired before forking to |
| 528 | # create the deadlock. |
| 529 | global finish_join |
| 530 | while not start_fork: |
| 531 | time.sleep(0.01) |
| 532 | # LOCK HELD: Main thread holds lock across this call. |
| 533 | childpid = os.fork() |
| 534 | finish_join = True |
| 535 | if childpid != 0: |
| 536 | # Parent process just waits for child. |
| 537 | os.waitpid(childpid, 0) |
| 538 | # Child process should just return. |
| 539 | |
| 540 | w = threading.Thread(target=worker) |
| 541 | |
| 542 | # Stub out the private condition variable's lock acquire method. |
| 543 | # This acquires the lock and then waits until the child has forked |
| 544 | # before returning, which will release the lock soon after. If |
| 545 | # someone else tries to fix this test case by acquiring this lock |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 546 | # before forking instead of resetting it, the test case will |
Gregory P. Smith | 4b129d2 | 2011-01-04 00:51:50 +0000 | [diff] [blame] | 547 | # deadlock when it shouldn't. |
| 548 | condition = w._block |
| 549 | orig_acquire = condition.acquire |
| 550 | call_count_lock = threading.Lock() |
| 551 | call_count = 0 |
| 552 | def my_acquire(): |
| 553 | global call_count |
| 554 | global start_fork |
| 555 | orig_acquire() # LOCK ACQUIRED HERE |
| 556 | start_fork = True |
| 557 | if call_count == 0: |
| 558 | while not finish_join: |
| 559 | time.sleep(0.01) # WORKER THREAD FORKS HERE |
| 560 | with call_count_lock: |
| 561 | call_count += 1 |
| 562 | condition.acquire = my_acquire |
| 563 | |
| 564 | w.start() |
| 565 | w.join() |
| 566 | print('end of main') |
| 567 | """ |
| 568 | self.assertScriptHasOutput(script, "end of main\n") |
| 569 | |
| 570 | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
| 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 | |
| 583 | # Skip platforms with known problems forking from a worker thread. |
| 584 | # See http://bugs.python.org/issue3863. |
| 585 | if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): |
| 586 | raise unittest.SkipTest('due to known OS bugs on ' + sys.platform) |
| 587 | script = """if True: |
| 588 | import os, time, threading |
| 589 | |
| 590 | start_fork = False |
| 591 | |
| 592 | def worker(): |
| 593 | # Wait until the main thread has attempted to join this thread |
| 594 | # before continuing. |
| 595 | while not start_fork: |
| 596 | time.sleep(0.01) |
| 597 | childpid = os.fork() |
| 598 | if childpid != 0: |
| 599 | # Parent process just waits for child. |
| 600 | (cpid, rc) = os.waitpid(childpid, 0) |
| 601 | assert cpid == childpid |
| 602 | assert rc == 0 |
| 603 | print('end of worker thread') |
| 604 | else: |
| 605 | # Child process should just return. |
| 606 | pass |
| 607 | |
| 608 | w = threading.Thread(target=worker) |
| 609 | |
| 610 | # Stub out the private condition variable's _release_save method. |
| 611 | # This releases the condition's lock and flips the global that |
| 612 | # causes the worker to fork. At this point, the problematic waiter |
| 613 | # lock has been acquired once by the waiter and has been put onto |
| 614 | # the waiters list. |
| 615 | condition = w._block |
| 616 | orig_release_save = condition._release_save |
| 617 | def my_release_save(): |
| 618 | global start_fork |
| 619 | orig_release_save() |
| 620 | # Waiter lock held here, condition lock released. |
| 621 | start_fork = True |
| 622 | condition._release_save = my_release_save |
| 623 | |
| 624 | w.start() |
| 625 | w.join() |
| 626 | print('end of main thread') |
| 627 | """ |
| 628 | output = "end of worker thread\nend of main thread\n" |
| 629 | self.assertScriptHasOutput(script, output) |
| 630 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 631 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 632 | class ThreadingExceptionTests(unittest.TestCase): |
| 633 | # A RuntimeError should be raised if Thread.start() is called |
| 634 | # multiple times. |
| 635 | def test_start_thread_again(self): |
| 636 | thread = threading.Thread() |
| 637 | thread.start() |
| 638 | self.assertRaises(RuntimeError, thread.start) |
| 639 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 640 | def test_joining_current_thread(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 641 | current_thread = threading.current_thread() |
| 642 | self.assertRaises(RuntimeError, current_thread.join); |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 643 | |
| 644 | def test_joining_inactive_thread(self): |
| 645 | thread = threading.Thread() |
| 646 | self.assertRaises(RuntimeError, thread.join) |
| 647 | |
| 648 | def test_daemonize_active_thread(self): |
| 649 | thread = threading.Thread() |
| 650 | thread.start() |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 651 | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 652 | |
| 653 | |
Antoine Pitrou | 959f3e5 | 2009-11-09 16:52:46 +0000 | [diff] [blame] | 654 | class LockTests(lock_tests.LockTests): |
| 655 | locktype = staticmethod(threading.Lock) |
| 656 | |
| 657 | class RLockTests(lock_tests.RLockTests): |
| 658 | locktype = staticmethod(threading.RLock) |
| 659 | |
| 660 | class EventTests(lock_tests.EventTests): |
| 661 | eventtype = staticmethod(threading.Event) |
| 662 | |
| 663 | class ConditionAsRLockTests(lock_tests.RLockTests): |
| 664 | # An Condition uses an RLock by default and exports its API. |
| 665 | locktype = staticmethod(threading.Condition) |
| 666 | |
| 667 | class ConditionTests(lock_tests.ConditionTests): |
| 668 | condtype = staticmethod(threading.Condition) |
| 669 | |
| 670 | class SemaphoreTests(lock_tests.SemaphoreTests): |
| 671 | semtype = staticmethod(threading.Semaphore) |
| 672 | |
| 673 | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
| 674 | semtype = staticmethod(threading.BoundedSemaphore) |
| 675 | |
| 676 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 677 | def test_main(): |
Antoine Pitrou | 959f3e5 | 2009-11-09 16:52:46 +0000 | [diff] [blame] | 678 | test.support.run_unittest(LockTests, RLockTests, EventTests, |
| 679 | ConditionAsRLockTests, ConditionTests, |
| 680 | SemaphoreTests, BoundedSemaphoreTests, |
| 681 | ThreadTests, |
| 682 | ThreadJoinOnShutdown, |
| 683 | ThreadingExceptionTests, |
| 684 | ) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 685 | |
| 686 | if __name__ == "__main__": |
| 687 | test_main() |