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 |
| 4 | from test.support import verbose |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 5 | import random |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 6 | import sys |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 7 | import threading |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 8 | import thread |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 9 | import time |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 10 | import unittest |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 11 | import weakref |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 12 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 13 | # A trivial mutable counter. |
| 14 | class Counter(object): |
| 15 | def __init__(self): |
| 16 | self.value = 0 |
| 17 | def inc(self): |
| 18 | self.value += 1 |
| 19 | def dec(self): |
| 20 | self.value -= 1 |
| 21 | def get(self): |
| 22 | return self.value |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 23 | |
| 24 | class TestThread(threading.Thread): |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 25 | def __init__(self, name, testcase, sema, mutex, nrunning): |
| 26 | threading.Thread.__init__(self, name=name) |
| 27 | self.testcase = testcase |
| 28 | self.sema = sema |
| 29 | self.mutex = mutex |
| 30 | self.nrunning = nrunning |
| 31 | |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 32 | def run(self): |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 33 | delay = random.random() / 10000.0 |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 34 | if verbose: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 35 | print('task %s will run for %.1f usec' % |
| 36 | (self.getName(), delay * 1e6)) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 37 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 38 | with self.sema: |
| 39 | with self.mutex: |
| 40 | self.nrunning.inc() |
| 41 | if verbose: |
| 42 | print(self.nrunning.get(), 'tasks are running') |
| 43 | self.testcase.assert_(self.nrunning.get() <= 3) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 44 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 45 | time.sleep(delay) |
| 46 | if verbose: |
| 47 | print('task', self.getName(), 'done') |
| 48 | with self.mutex: |
| 49 | self.nrunning.dec() |
| 50 | self.testcase.assert_(self.nrunning.get() >= 0) |
| 51 | if verbose: |
| 52 | print('%s is finished. %d tasks are running' % |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 53 | (self.getName(), self.nrunning.get())) |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 54 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 55 | class ThreadTests(unittest.TestCase): |
Skip Montanaro | 4533f60 | 2001-08-20 20:28:48 +0000 | [diff] [blame] | 56 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 57 | # Create a bunch of threads, let each do some work, wait until all are |
| 58 | # done. |
| 59 | def test_various_ops(self): |
| 60 | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
| 61 | # times about 1 second per clump). |
| 62 | NUMTASKS = 10 |
| 63 | |
| 64 | # no more than 3 of the 10 can run at once |
| 65 | sema = threading.BoundedSemaphore(value=3) |
| 66 | mutex = threading.RLock() |
| 67 | numrunning = Counter() |
| 68 | |
| 69 | threads = [] |
| 70 | |
| 71 | for i in range(NUMTASKS): |
| 72 | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
| 73 | threads.append(t) |
| 74 | t.start() |
| 75 | |
| 76 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 77 | print('waiting for all tasks to complete') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 78 | for t in threads: |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 79 | t.join(NUMTASKS) |
| 80 | self.assert_(not t.isAlive()) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 81 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 82 | print('all tasks done') |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 83 | self.assertEqual(numrunning.get(), 0) |
| 84 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 85 | # run with a small(ish) thread stack size (256kB) |
| 86 | def test_various_ops_small_stack(self): |
| 87 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 88 | print('with 256kB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 89 | try: |
| 90 | threading.stack_size(262144) |
| 91 | except thread.error: |
| 92 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 93 | print('platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 94 | return |
| 95 | self.test_various_ops() |
| 96 | threading.stack_size(0) |
| 97 | |
| 98 | # run with a large thread stack size (1MB) |
| 99 | def test_various_ops_large_stack(self): |
| 100 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 101 | print('with 1MB thread stack size...') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 102 | try: |
| 103 | threading.stack_size(0x100000) |
| 104 | except thread.error: |
| 105 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 106 | print('platform does not support changing thread stack size') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 107 | return |
| 108 | self.test_various_ops() |
| 109 | threading.stack_size(0) |
| 110 | |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 111 | def test_foreign_thread(self): |
| 112 | # Check that a "foreign" thread can use the threading module. |
| 113 | def f(mutex): |
| 114 | # Acquiring an RLock forces an entry for the foreign |
| 115 | # thread to get made in the threading._active map. |
| 116 | r = threading.RLock() |
| 117 | r.acquire() |
| 118 | r.release() |
| 119 | mutex.release() |
| 120 | |
| 121 | mutex = threading.Lock() |
| 122 | mutex.acquire() |
| 123 | tid = thread.start_new_thread(f, (mutex,)) |
| 124 | # Wait for the thread to finish. |
| 125 | mutex.acquire() |
| 126 | self.assert_(tid in threading._active) |
| 127 | self.assert_(isinstance(threading._active[tid], |
| 128 | threading._DummyThread)) |
| 129 | del threading._active[tid] |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 130 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 131 | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
| 132 | # exposed at the Python level. This test relies on ctypes to get at it. |
| 133 | def test_PyThreadState_SetAsyncExc(self): |
| 134 | try: |
| 135 | import ctypes |
| 136 | except ImportError: |
| 137 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 138 | print("test_PyThreadState_SetAsyncExc can't import ctypes") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 139 | return # can't do anything |
| 140 | |
| 141 | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
| 142 | |
| 143 | class AsyncExc(Exception): |
| 144 | pass |
| 145 | |
| 146 | exception = ctypes.py_object(AsyncExc) |
| 147 | |
| 148 | # `worker_started` is set by the thread when it's inside a try/except |
| 149 | # block waiting to catch the asynchronously set AsyncExc exception. |
| 150 | # `worker_saw_exception` is set by the thread upon catching that |
| 151 | # exception. |
| 152 | worker_started = threading.Event() |
| 153 | worker_saw_exception = threading.Event() |
| 154 | |
| 155 | class Worker(threading.Thread): |
| 156 | def run(self): |
| 157 | self.id = thread.get_ident() |
| 158 | self.finished = False |
| 159 | |
| 160 | try: |
| 161 | while True: |
| 162 | worker_started.set() |
| 163 | time.sleep(0.1) |
| 164 | except AsyncExc: |
| 165 | self.finished = True |
| 166 | worker_saw_exception.set() |
| 167 | |
| 168 | t = Worker() |
| 169 | t.setDaemon(True) # so if this fails, we don't hang Python at shutdown |
| 170 | t.start() |
| 171 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 172 | print(" started worker thread") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 173 | |
| 174 | # Try a thread id that doesn't make sense. |
| 175 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 176 | print(" trying nonsensical thread id") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 177 | result = set_async_exc(ctypes.c_long(-1), exception) |
| 178 | self.assertEqual(result, 0) # no thread states modified |
| 179 | |
| 180 | # Now raise an exception in the worker thread. |
| 181 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 182 | print(" waiting for worker thread to get started") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 183 | worker_started.wait() |
| 184 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 185 | print(" verifying worker hasn't exited") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 186 | self.assert_(not t.finished) |
| 187 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 188 | print(" attempting to raise asynch exception in worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 189 | result = set_async_exc(ctypes.c_long(t.id), exception) |
| 190 | self.assertEqual(result, 1) # one thread state modified |
| 191 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 192 | print(" waiting for worker to say it caught the exception") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 193 | worker_saw_exception.wait(timeout=10) |
| 194 | self.assert_(t.finished) |
| 195 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 196 | print(" all OK -- joining worker") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 197 | if t.finished: |
| 198 | t.join() |
| 199 | # else the thread is still running, and we have no way to kill it |
| 200 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 201 | def test_finalize_runnning_thread(self): |
| 202 | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
| 203 | # very late on python exit: on deallocation of a running thread for |
| 204 | # example. |
| 205 | try: |
| 206 | import ctypes |
| 207 | except ImportError: |
| 208 | if verbose: |
| 209 | print("test_finalize_with_runnning_thread can't import ctypes") |
| 210 | return # can't do anything |
| 211 | |
| 212 | import subprocess |
| 213 | rc = subprocess.call([sys.executable, "-c", """if 1: |
| 214 | import ctypes, sys, time, thread |
| 215 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 216 | # This lock is used as a simple event variable. |
| 217 | ready = thread.allocate_lock() |
| 218 | ready.acquire() |
| 219 | |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 220 | # Module globals are cleared before __del__ is run |
| 221 | # So we save the functions in class dict |
| 222 | class C: |
| 223 | ensure = ctypes.pythonapi.PyGILState_Ensure |
| 224 | release = ctypes.pythonapi.PyGILState_Release |
| 225 | def __del__(self): |
| 226 | state = self.ensure() |
| 227 | self.release(state) |
| 228 | |
| 229 | def waitingThread(): |
| 230 | x = C() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 231 | ready.release() |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 232 | time.sleep(100) |
| 233 | |
| 234 | thread.start_new_thread(waitingThread, ()) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 235 | ready.acquire() # Be sure the other thread is waiting. |
Christian Heimes | 7d2ff88 | 2007-11-30 14:35:04 +0000 | [diff] [blame] | 236 | sys.exit(42) |
| 237 | """]) |
| 238 | self.assertEqual(rc, 42) |
| 239 | |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 240 | def test_finalize_with_trace(self): |
| 241 | # Issue1733757 |
| 242 | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
| 243 | import subprocess |
| 244 | rc = subprocess.call([sys.executable, "-c", """if 1: |
| 245 | import sys, threading |
| 246 | |
| 247 | # A deadlock-killer, to prevent the |
| 248 | # testsuite to hang forever |
| 249 | def killer(): |
| 250 | import os, time |
| 251 | time.sleep(2) |
| 252 | print('program blocked; aborting') |
| 253 | os._exit(2) |
| 254 | t = threading.Thread(target=killer) |
| 255 | t.setDaemon(True) |
| 256 | t.start() |
| 257 | |
| 258 | # This is the trace function |
| 259 | def func(frame, event, arg): |
| 260 | threading.currentThread() |
| 261 | return func |
| 262 | |
| 263 | sys.settrace(func) |
| 264 | """]) |
| 265 | self.failIf(rc == 2, "interpreted was blocked") |
| 266 | self.failUnless(rc == 0, "Unexpected error") |
| 267 | |
| 268 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 269 | def test_enumerate_after_join(self): |
| 270 | # Try hard to trigger #1703448: a thread is still returned in |
| 271 | # threading.enumerate() after it has been join()ed. |
| 272 | enum = threading.enumerate |
| 273 | old_interval = sys.getcheckinterval() |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 274 | try: |
Jeffrey Yasskin | ca67412 | 2008-03-29 05:06:52 +0000 | [diff] [blame] | 275 | for i in range(1, 100): |
| 276 | # Try a couple times at each thread-switching interval |
| 277 | # to get more interleavings. |
| 278 | sys.setcheckinterval(i // 5) |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 279 | t = threading.Thread(target=lambda: None) |
| 280 | t.start() |
| 281 | t.join() |
| 282 | l = enum() |
| 283 | self.assertFalse(t in l, |
| 284 | "#1703448 triggered after %d trials: %s" % (i, l)) |
| 285 | finally: |
| 286 | sys.setcheckinterval(old_interval) |
| 287 | |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 288 | def test_no_refcycle_through_target(self): |
| 289 | class RunSelfFunction(object): |
| 290 | def __init__(self, should_raise): |
| 291 | # The links in this refcycle from Thread back to self |
| 292 | # should be cleaned up when the thread completes. |
| 293 | self.should_raise = should_raise |
| 294 | self.thread = threading.Thread(target=self._run, |
| 295 | args=(self,), |
| 296 | kwargs={'yet_another':self}) |
| 297 | self.thread.start() |
| 298 | |
| 299 | def _run(self, other_ref, yet_another): |
| 300 | if self.should_raise: |
| 301 | raise SystemExit |
| 302 | |
| 303 | cyclic_object = RunSelfFunction(should_raise=False) |
| 304 | weak_cyclic_object = weakref.ref(cyclic_object) |
| 305 | cyclic_object.thread.join() |
| 306 | del cyclic_object |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 307 | self.assertEquals(None, weak_cyclic_object(), |
| 308 | msg=('%d references still around' % |
| 309 | sys.getrefcount(weak_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 310 | |
| 311 | raising_cyclic_object = RunSelfFunction(should_raise=True) |
| 312 | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
| 313 | raising_cyclic_object.thread.join() |
| 314 | del raising_cyclic_object |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 315 | self.assertEquals(None, weak_raising_cyclic_object(), |
| 316 | msg=('%d references still around' % |
| 317 | sys.getrefcount(weak_raising_cyclic_object()))) |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 318 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 319 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 320 | class ThreadingExceptionTests(unittest.TestCase): |
| 321 | # A RuntimeError should be raised if Thread.start() is called |
| 322 | # multiple times. |
| 323 | def test_start_thread_again(self): |
| 324 | thread = threading.Thread() |
| 325 | thread.start() |
| 326 | self.assertRaises(RuntimeError, thread.start) |
| 327 | |
| 328 | def test_releasing_unacquired_rlock(self): |
| 329 | rlock = threading.RLock() |
| 330 | self.assertRaises(RuntimeError, rlock.release) |
| 331 | |
| 332 | def test_waiting_on_unacquired_condition(self): |
| 333 | cond = threading.Condition() |
| 334 | self.assertRaises(RuntimeError, cond.wait) |
| 335 | |
| 336 | def test_notify_on_unacquired_condition(self): |
| 337 | cond = threading.Condition() |
| 338 | self.assertRaises(RuntimeError, cond.notify) |
| 339 | |
| 340 | def test_semaphore_with_negative_value(self): |
| 341 | self.assertRaises(ValueError, threading.Semaphore, value = -1) |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 342 | self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 343 | |
| 344 | def test_joining_current_thread(self): |
| 345 | currentThread = threading.currentThread() |
| 346 | self.assertRaises(RuntimeError, currentThread.join); |
| 347 | |
| 348 | def test_joining_inactive_thread(self): |
| 349 | thread = threading.Thread() |
| 350 | self.assertRaises(RuntimeError, thread.join) |
| 351 | |
| 352 | def test_daemonize_active_thread(self): |
| 353 | thread = threading.Thread() |
| 354 | thread.start() |
| 355 | self.assertRaises(RuntimeError, thread.setDaemon, True) |
| 356 | |
| 357 | |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 358 | def test_main(): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame^] | 359 | test.support.run_unittest(ThreadTests, |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 360 | ThreadingExceptionTests) |
Tim Peters | 84d5489 | 2005-01-08 06:03:17 +0000 | [diff] [blame] | 361 | |
| 362 | if __name__ == "__main__": |
| 363 | test_main() |