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