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