| 1 | n/a | """ |
|---|
| 2 | n/a | Tests for the threading module. |
|---|
| 3 | n/a | """ |
|---|
| 4 | n/a | |
|---|
| 5 | n/a | import test.support |
|---|
| 6 | n/a | from test.support import (verbose, import_module, cpython_only, |
|---|
| 7 | n/a | requires_type_collecting) |
|---|
| 8 | n/a | from test.support.script_helper import assert_python_ok, assert_python_failure |
|---|
| 9 | n/a | |
|---|
| 10 | n/a | import random |
|---|
| 11 | n/a | import sys |
|---|
| 12 | n/a | _thread = import_module('_thread') |
|---|
| 13 | n/a | threading = import_module('threading') |
|---|
| 14 | n/a | import time |
|---|
| 15 | n/a | import unittest |
|---|
| 16 | n/a | import weakref |
|---|
| 17 | n/a | import os |
|---|
| 18 | n/a | import subprocess |
|---|
| 19 | n/a | |
|---|
| 20 | n/a | from test import lock_tests |
|---|
| 21 | n/a | from test import support |
|---|
| 22 | n/a | |
|---|
| 23 | n/a | |
|---|
| 24 | n/a | # Between fork() and exec(), only async-safe functions are allowed (issues |
|---|
| 25 | n/a | # #12316 and #11870), and fork() from a worker thread is known to trigger |
|---|
| 26 | n/a | # problems with some operating systems (issue #3863): skip problematic tests |
|---|
| 27 | n/a | # on platforms known to behave badly. |
|---|
| 28 | n/a | platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', |
|---|
| 29 | n/a | 'hp-ux11') |
|---|
| 30 | n/a | |
|---|
| 31 | n/a | |
|---|
| 32 | n/a | # A trivial mutable counter. |
|---|
| 33 | n/a | class Counter(object): |
|---|
| 34 | n/a | def __init__(self): |
|---|
| 35 | n/a | self.value = 0 |
|---|
| 36 | n/a | def inc(self): |
|---|
| 37 | n/a | self.value += 1 |
|---|
| 38 | n/a | def dec(self): |
|---|
| 39 | n/a | self.value -= 1 |
|---|
| 40 | n/a | def get(self): |
|---|
| 41 | n/a | return self.value |
|---|
| 42 | n/a | |
|---|
| 43 | n/a | class TestThread(threading.Thread): |
|---|
| 44 | n/a | def __init__(self, name, testcase, sema, mutex, nrunning): |
|---|
| 45 | n/a | threading.Thread.__init__(self, name=name) |
|---|
| 46 | n/a | self.testcase = testcase |
|---|
| 47 | n/a | self.sema = sema |
|---|
| 48 | n/a | self.mutex = mutex |
|---|
| 49 | n/a | self.nrunning = nrunning |
|---|
| 50 | n/a | |
|---|
| 51 | n/a | def run(self): |
|---|
| 52 | n/a | delay = random.random() / 10000.0 |
|---|
| 53 | n/a | if verbose: |
|---|
| 54 | n/a | print('task %s will run for %.1f usec' % |
|---|
| 55 | n/a | (self.name, delay * 1e6)) |
|---|
| 56 | n/a | |
|---|
| 57 | n/a | with self.sema: |
|---|
| 58 | n/a | with self.mutex: |
|---|
| 59 | n/a | self.nrunning.inc() |
|---|
| 60 | n/a | if verbose: |
|---|
| 61 | n/a | print(self.nrunning.get(), 'tasks are running') |
|---|
| 62 | n/a | self.testcase.assertLessEqual(self.nrunning.get(), 3) |
|---|
| 63 | n/a | |
|---|
| 64 | n/a | time.sleep(delay) |
|---|
| 65 | n/a | if verbose: |
|---|
| 66 | n/a | print('task', self.name, 'done') |
|---|
| 67 | n/a | |
|---|
| 68 | n/a | with self.mutex: |
|---|
| 69 | n/a | self.nrunning.dec() |
|---|
| 70 | n/a | self.testcase.assertGreaterEqual(self.nrunning.get(), 0) |
|---|
| 71 | n/a | if verbose: |
|---|
| 72 | n/a | print('%s is finished. %d tasks are running' % |
|---|
| 73 | n/a | (self.name, self.nrunning.get())) |
|---|
| 74 | n/a | |
|---|
| 75 | n/a | |
|---|
| 76 | n/a | class BaseTestCase(unittest.TestCase): |
|---|
| 77 | n/a | def setUp(self): |
|---|
| 78 | n/a | self._threads = test.support.threading_setup() |
|---|
| 79 | n/a | |
|---|
| 80 | n/a | def tearDown(self): |
|---|
| 81 | n/a | test.support.threading_cleanup(*self._threads) |
|---|
| 82 | n/a | test.support.reap_children() |
|---|
| 83 | n/a | |
|---|
| 84 | n/a | |
|---|
| 85 | n/a | class ThreadTests(BaseTestCase): |
|---|
| 86 | n/a | |
|---|
| 87 | n/a | # Create a bunch of threads, let each do some work, wait until all are |
|---|
| 88 | n/a | # done. |
|---|
| 89 | n/a | def test_various_ops(self): |
|---|
| 90 | n/a | # This takes about n/3 seconds to run (about n/3 clumps of tasks, |
|---|
| 91 | n/a | # times about 1 second per clump). |
|---|
| 92 | n/a | NUMTASKS = 10 |
|---|
| 93 | n/a | |
|---|
| 94 | n/a | # no more than 3 of the 10 can run at once |
|---|
| 95 | n/a | sema = threading.BoundedSemaphore(value=3) |
|---|
| 96 | n/a | mutex = threading.RLock() |
|---|
| 97 | n/a | numrunning = Counter() |
|---|
| 98 | n/a | |
|---|
| 99 | n/a | threads = [] |
|---|
| 100 | n/a | |
|---|
| 101 | n/a | for i in range(NUMTASKS): |
|---|
| 102 | n/a | t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) |
|---|
| 103 | n/a | threads.append(t) |
|---|
| 104 | n/a | self.assertIsNone(t.ident) |
|---|
| 105 | n/a | self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$') |
|---|
| 106 | n/a | t.start() |
|---|
| 107 | n/a | |
|---|
| 108 | n/a | if verbose: |
|---|
| 109 | n/a | print('waiting for all tasks to complete') |
|---|
| 110 | n/a | for t in threads: |
|---|
| 111 | n/a | t.join() |
|---|
| 112 | n/a | self.assertFalse(t.is_alive()) |
|---|
| 113 | n/a | self.assertNotEqual(t.ident, 0) |
|---|
| 114 | n/a | self.assertIsNotNone(t.ident) |
|---|
| 115 | n/a | self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$') |
|---|
| 116 | n/a | if verbose: |
|---|
| 117 | n/a | print('all tasks done') |
|---|
| 118 | n/a | self.assertEqual(numrunning.get(), 0) |
|---|
| 119 | n/a | |
|---|
| 120 | n/a | def test_ident_of_no_threading_threads(self): |
|---|
| 121 | n/a | # The ident still must work for the main thread and dummy threads. |
|---|
| 122 | n/a | self.assertIsNotNone(threading.currentThread().ident) |
|---|
| 123 | n/a | def f(): |
|---|
| 124 | n/a | ident.append(threading.currentThread().ident) |
|---|
| 125 | n/a | done.set() |
|---|
| 126 | n/a | done = threading.Event() |
|---|
| 127 | n/a | ident = [] |
|---|
| 128 | n/a | _thread.start_new_thread(f, ()) |
|---|
| 129 | n/a | done.wait() |
|---|
| 130 | n/a | self.assertIsNotNone(ident[0]) |
|---|
| 131 | n/a | # Kill the "immortal" _DummyThread |
|---|
| 132 | n/a | del threading._active[ident[0]] |
|---|
| 133 | n/a | |
|---|
| 134 | n/a | # run with a small(ish) thread stack size (256kB) |
|---|
| 135 | n/a | def test_various_ops_small_stack(self): |
|---|
| 136 | n/a | if verbose: |
|---|
| 137 | n/a | print('with 256kB thread stack size...') |
|---|
| 138 | n/a | try: |
|---|
| 139 | n/a | threading.stack_size(262144) |
|---|
| 140 | n/a | except _thread.error: |
|---|
| 141 | n/a | raise unittest.SkipTest( |
|---|
| 142 | n/a | 'platform does not support changing thread stack size') |
|---|
| 143 | n/a | self.test_various_ops() |
|---|
| 144 | n/a | threading.stack_size(0) |
|---|
| 145 | n/a | |
|---|
| 146 | n/a | # run with a large thread stack size (1MB) |
|---|
| 147 | n/a | def test_various_ops_large_stack(self): |
|---|
| 148 | n/a | if verbose: |
|---|
| 149 | n/a | print('with 1MB thread stack size...') |
|---|
| 150 | n/a | try: |
|---|
| 151 | n/a | threading.stack_size(0x100000) |
|---|
| 152 | n/a | except _thread.error: |
|---|
| 153 | n/a | raise unittest.SkipTest( |
|---|
| 154 | n/a | 'platform does not support changing thread stack size') |
|---|
| 155 | n/a | self.test_various_ops() |
|---|
| 156 | n/a | threading.stack_size(0) |
|---|
| 157 | n/a | |
|---|
| 158 | n/a | def test_foreign_thread(self): |
|---|
| 159 | n/a | # Check that a "foreign" thread can use the threading module. |
|---|
| 160 | n/a | def f(mutex): |
|---|
| 161 | n/a | # Calling current_thread() forces an entry for the foreign |
|---|
| 162 | n/a | # thread to get made in the threading._active map. |
|---|
| 163 | n/a | threading.current_thread() |
|---|
| 164 | n/a | mutex.release() |
|---|
| 165 | n/a | |
|---|
| 166 | n/a | mutex = threading.Lock() |
|---|
| 167 | n/a | mutex.acquire() |
|---|
| 168 | n/a | tid = _thread.start_new_thread(f, (mutex,)) |
|---|
| 169 | n/a | # Wait for the thread to finish. |
|---|
| 170 | n/a | mutex.acquire() |
|---|
| 171 | n/a | self.assertIn(tid, threading._active) |
|---|
| 172 | n/a | self.assertIsInstance(threading._active[tid], threading._DummyThread) |
|---|
| 173 | n/a | del threading._active[tid] |
|---|
| 174 | n/a | |
|---|
| 175 | n/a | # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) |
|---|
| 176 | n/a | # exposed at the Python level. This test relies on ctypes to get at it. |
|---|
| 177 | n/a | def test_PyThreadState_SetAsyncExc(self): |
|---|
| 178 | n/a | ctypes = import_module("ctypes") |
|---|
| 179 | n/a | |
|---|
| 180 | n/a | set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc |
|---|
| 181 | n/a | |
|---|
| 182 | n/a | class AsyncExc(Exception): |
|---|
| 183 | n/a | pass |
|---|
| 184 | n/a | |
|---|
| 185 | n/a | exception = ctypes.py_object(AsyncExc) |
|---|
| 186 | n/a | |
|---|
| 187 | n/a | # First check it works when setting the exception from the same thread. |
|---|
| 188 | n/a | tid = threading.get_ident() |
|---|
| 189 | n/a | |
|---|
| 190 | n/a | try: |
|---|
| 191 | n/a | result = set_async_exc(ctypes.c_long(tid), exception) |
|---|
| 192 | n/a | # The exception is async, so we might have to keep the VM busy until |
|---|
| 193 | n/a | # it notices. |
|---|
| 194 | n/a | while True: |
|---|
| 195 | n/a | pass |
|---|
| 196 | n/a | except AsyncExc: |
|---|
| 197 | n/a | pass |
|---|
| 198 | n/a | else: |
|---|
| 199 | n/a | # This code is unreachable but it reflects the intent. If we wanted |
|---|
| 200 | n/a | # to be smarter the above loop wouldn't be infinite. |
|---|
| 201 | n/a | self.fail("AsyncExc not raised") |
|---|
| 202 | n/a | try: |
|---|
| 203 | n/a | self.assertEqual(result, 1) # one thread state modified |
|---|
| 204 | n/a | except UnboundLocalError: |
|---|
| 205 | n/a | # The exception was raised too quickly for us to get the result. |
|---|
| 206 | n/a | pass |
|---|
| 207 | n/a | |
|---|
| 208 | n/a | # `worker_started` is set by the thread when it's inside a try/except |
|---|
| 209 | n/a | # block waiting to catch the asynchronously set AsyncExc exception. |
|---|
| 210 | n/a | # `worker_saw_exception` is set by the thread upon catching that |
|---|
| 211 | n/a | # exception. |
|---|
| 212 | n/a | worker_started = threading.Event() |
|---|
| 213 | n/a | worker_saw_exception = threading.Event() |
|---|
| 214 | n/a | |
|---|
| 215 | n/a | class Worker(threading.Thread): |
|---|
| 216 | n/a | def run(self): |
|---|
| 217 | n/a | self.id = threading.get_ident() |
|---|
| 218 | n/a | self.finished = False |
|---|
| 219 | n/a | |
|---|
| 220 | n/a | try: |
|---|
| 221 | n/a | while True: |
|---|
| 222 | n/a | worker_started.set() |
|---|
| 223 | n/a | time.sleep(0.1) |
|---|
| 224 | n/a | except AsyncExc: |
|---|
| 225 | n/a | self.finished = True |
|---|
| 226 | n/a | worker_saw_exception.set() |
|---|
| 227 | n/a | |
|---|
| 228 | n/a | t = Worker() |
|---|
| 229 | n/a | t.daemon = True # so if this fails, we don't hang Python at shutdown |
|---|
| 230 | n/a | t.start() |
|---|
| 231 | n/a | if verbose: |
|---|
| 232 | n/a | print(" started worker thread") |
|---|
| 233 | n/a | |
|---|
| 234 | n/a | # Try a thread id that doesn't make sense. |
|---|
| 235 | n/a | if verbose: |
|---|
| 236 | n/a | print(" trying nonsensical thread id") |
|---|
| 237 | n/a | result = set_async_exc(ctypes.c_long(-1), exception) |
|---|
| 238 | n/a | self.assertEqual(result, 0) # no thread states modified |
|---|
| 239 | n/a | |
|---|
| 240 | n/a | # Now raise an exception in the worker thread. |
|---|
| 241 | n/a | if verbose: |
|---|
| 242 | n/a | print(" waiting for worker thread to get started") |
|---|
| 243 | n/a | ret = worker_started.wait() |
|---|
| 244 | n/a | self.assertTrue(ret) |
|---|
| 245 | n/a | if verbose: |
|---|
| 246 | n/a | print(" verifying worker hasn't exited") |
|---|
| 247 | n/a | self.assertFalse(t.finished) |
|---|
| 248 | n/a | if verbose: |
|---|
| 249 | n/a | print(" attempting to raise asynch exception in worker") |
|---|
| 250 | n/a | result = set_async_exc(ctypes.c_long(t.id), exception) |
|---|
| 251 | n/a | self.assertEqual(result, 1) # one thread state modified |
|---|
| 252 | n/a | if verbose: |
|---|
| 253 | n/a | print(" waiting for worker to say it caught the exception") |
|---|
| 254 | n/a | worker_saw_exception.wait(timeout=10) |
|---|
| 255 | n/a | self.assertTrue(t.finished) |
|---|
| 256 | n/a | if verbose: |
|---|
| 257 | n/a | print(" all OK -- joining worker") |
|---|
| 258 | n/a | if t.finished: |
|---|
| 259 | n/a | t.join() |
|---|
| 260 | n/a | # else the thread is still running, and we have no way to kill it |
|---|
| 261 | n/a | |
|---|
| 262 | n/a | def test_limbo_cleanup(self): |
|---|
| 263 | n/a | # Issue 7481: Failure to start thread should cleanup the limbo map. |
|---|
| 264 | n/a | def fail_new_thread(*args): |
|---|
| 265 | n/a | raise threading.ThreadError() |
|---|
| 266 | n/a | _start_new_thread = threading._start_new_thread |
|---|
| 267 | n/a | threading._start_new_thread = fail_new_thread |
|---|
| 268 | n/a | try: |
|---|
| 269 | n/a | t = threading.Thread(target=lambda: None) |
|---|
| 270 | n/a | self.assertRaises(threading.ThreadError, t.start) |
|---|
| 271 | n/a | self.assertFalse( |
|---|
| 272 | n/a | t in threading._limbo, |
|---|
| 273 | n/a | "Failed to cleanup _limbo map on failure of Thread.start().") |
|---|
| 274 | n/a | finally: |
|---|
| 275 | n/a | threading._start_new_thread = _start_new_thread |
|---|
| 276 | n/a | |
|---|
| 277 | n/a | def test_finalize_runnning_thread(self): |
|---|
| 278 | n/a | # Issue 1402: the PyGILState_Ensure / _Release functions may be called |
|---|
| 279 | n/a | # very late on python exit: on deallocation of a running thread for |
|---|
| 280 | n/a | # example. |
|---|
| 281 | n/a | import_module("ctypes") |
|---|
| 282 | n/a | |
|---|
| 283 | n/a | rc, out, err = assert_python_failure("-c", """if 1: |
|---|
| 284 | n/a | import ctypes, sys, time, _thread |
|---|
| 285 | n/a | |
|---|
| 286 | n/a | # This lock is used as a simple event variable. |
|---|
| 287 | n/a | ready = _thread.allocate_lock() |
|---|
| 288 | n/a | ready.acquire() |
|---|
| 289 | n/a | |
|---|
| 290 | n/a | # Module globals are cleared before __del__ is run |
|---|
| 291 | n/a | # So we save the functions in class dict |
|---|
| 292 | n/a | class C: |
|---|
| 293 | n/a | ensure = ctypes.pythonapi.PyGILState_Ensure |
|---|
| 294 | n/a | release = ctypes.pythonapi.PyGILState_Release |
|---|
| 295 | n/a | def __del__(self): |
|---|
| 296 | n/a | state = self.ensure() |
|---|
| 297 | n/a | self.release(state) |
|---|
| 298 | n/a | |
|---|
| 299 | n/a | def waitingThread(): |
|---|
| 300 | n/a | x = C() |
|---|
| 301 | n/a | ready.release() |
|---|
| 302 | n/a | time.sleep(100) |
|---|
| 303 | n/a | |
|---|
| 304 | n/a | _thread.start_new_thread(waitingThread, ()) |
|---|
| 305 | n/a | ready.acquire() # Be sure the other thread is waiting. |
|---|
| 306 | n/a | sys.exit(42) |
|---|
| 307 | n/a | """) |
|---|
| 308 | n/a | self.assertEqual(rc, 42) |
|---|
| 309 | n/a | |
|---|
| 310 | n/a | def test_finalize_with_trace(self): |
|---|
| 311 | n/a | # Issue1733757 |
|---|
| 312 | n/a | # Avoid a deadlock when sys.settrace steps into threading._shutdown |
|---|
| 313 | n/a | assert_python_ok("-c", """if 1: |
|---|
| 314 | n/a | import sys, threading |
|---|
| 315 | n/a | |
|---|
| 316 | n/a | # A deadlock-killer, to prevent the |
|---|
| 317 | n/a | # testsuite to hang forever |
|---|
| 318 | n/a | def killer(): |
|---|
| 319 | n/a | import os, time |
|---|
| 320 | n/a | time.sleep(2) |
|---|
| 321 | n/a | print('program blocked; aborting') |
|---|
| 322 | n/a | os._exit(2) |
|---|
| 323 | n/a | t = threading.Thread(target=killer) |
|---|
| 324 | n/a | t.daemon = True |
|---|
| 325 | n/a | t.start() |
|---|
| 326 | n/a | |
|---|
| 327 | n/a | # This is the trace function |
|---|
| 328 | n/a | def func(frame, event, arg): |
|---|
| 329 | n/a | threading.current_thread() |
|---|
| 330 | n/a | return func |
|---|
| 331 | n/a | |
|---|
| 332 | n/a | sys.settrace(func) |
|---|
| 333 | n/a | """) |
|---|
| 334 | n/a | |
|---|
| 335 | n/a | def test_join_nondaemon_on_shutdown(self): |
|---|
| 336 | n/a | # Issue 1722344 |
|---|
| 337 | n/a | # Raising SystemExit skipped threading._shutdown |
|---|
| 338 | n/a | rc, out, err = assert_python_ok("-c", """if 1: |
|---|
| 339 | n/a | import threading |
|---|
| 340 | n/a | from time import sleep |
|---|
| 341 | n/a | |
|---|
| 342 | n/a | def child(): |
|---|
| 343 | n/a | sleep(1) |
|---|
| 344 | n/a | # As a non-daemon thread we SHOULD wake up and nothing |
|---|
| 345 | n/a | # should be torn down yet |
|---|
| 346 | n/a | print("Woke up, sleep function is:", sleep) |
|---|
| 347 | n/a | |
|---|
| 348 | n/a | threading.Thread(target=child).start() |
|---|
| 349 | n/a | raise SystemExit |
|---|
| 350 | n/a | """) |
|---|
| 351 | n/a | self.assertEqual(out.strip(), |
|---|
| 352 | n/a | b"Woke up, sleep function is: <built-in function sleep>") |
|---|
| 353 | n/a | self.assertEqual(err, b"") |
|---|
| 354 | n/a | |
|---|
| 355 | n/a | def test_enumerate_after_join(self): |
|---|
| 356 | n/a | # Try hard to trigger #1703448: a thread is still returned in |
|---|
| 357 | n/a | # threading.enumerate() after it has been join()ed. |
|---|
| 358 | n/a | enum = threading.enumerate |
|---|
| 359 | n/a | old_interval = sys.getswitchinterval() |
|---|
| 360 | n/a | try: |
|---|
| 361 | n/a | for i in range(1, 100): |
|---|
| 362 | n/a | sys.setswitchinterval(i * 0.0002) |
|---|
| 363 | n/a | t = threading.Thread(target=lambda: None) |
|---|
| 364 | n/a | t.start() |
|---|
| 365 | n/a | t.join() |
|---|
| 366 | n/a | l = enum() |
|---|
| 367 | n/a | self.assertNotIn(t, l, |
|---|
| 368 | n/a | "#1703448 triggered after %d trials: %s" % (i, l)) |
|---|
| 369 | n/a | finally: |
|---|
| 370 | n/a | sys.setswitchinterval(old_interval) |
|---|
| 371 | n/a | |
|---|
| 372 | n/a | def test_no_refcycle_through_target(self): |
|---|
| 373 | n/a | class RunSelfFunction(object): |
|---|
| 374 | n/a | def __init__(self, should_raise): |
|---|
| 375 | n/a | # The links in this refcycle from Thread back to self |
|---|
| 376 | n/a | # should be cleaned up when the thread completes. |
|---|
| 377 | n/a | self.should_raise = should_raise |
|---|
| 378 | n/a | self.thread = threading.Thread(target=self._run, |
|---|
| 379 | n/a | args=(self,), |
|---|
| 380 | n/a | kwargs={'yet_another':self}) |
|---|
| 381 | n/a | self.thread.start() |
|---|
| 382 | n/a | |
|---|
| 383 | n/a | def _run(self, other_ref, yet_another): |
|---|
| 384 | n/a | if self.should_raise: |
|---|
| 385 | n/a | raise SystemExit |
|---|
| 386 | n/a | |
|---|
| 387 | n/a | cyclic_object = RunSelfFunction(should_raise=False) |
|---|
| 388 | n/a | weak_cyclic_object = weakref.ref(cyclic_object) |
|---|
| 389 | n/a | cyclic_object.thread.join() |
|---|
| 390 | n/a | del cyclic_object |
|---|
| 391 | n/a | self.assertIsNone(weak_cyclic_object(), |
|---|
| 392 | n/a | msg=('%d references still around' % |
|---|
| 393 | n/a | sys.getrefcount(weak_cyclic_object()))) |
|---|
| 394 | n/a | |
|---|
| 395 | n/a | raising_cyclic_object = RunSelfFunction(should_raise=True) |
|---|
| 396 | n/a | weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) |
|---|
| 397 | n/a | raising_cyclic_object.thread.join() |
|---|
| 398 | n/a | del raising_cyclic_object |
|---|
| 399 | n/a | self.assertIsNone(weak_raising_cyclic_object(), |
|---|
| 400 | n/a | msg=('%d references still around' % |
|---|
| 401 | n/a | sys.getrefcount(weak_raising_cyclic_object()))) |
|---|
| 402 | n/a | |
|---|
| 403 | n/a | def test_old_threading_api(self): |
|---|
| 404 | n/a | # Just a quick sanity check to make sure the old method names are |
|---|
| 405 | n/a | # still present |
|---|
| 406 | n/a | t = threading.Thread() |
|---|
| 407 | n/a | t.isDaemon() |
|---|
| 408 | n/a | t.setDaemon(True) |
|---|
| 409 | n/a | t.getName() |
|---|
| 410 | n/a | t.setName("name") |
|---|
| 411 | n/a | t.isAlive() |
|---|
| 412 | n/a | e = threading.Event() |
|---|
| 413 | n/a | e.isSet() |
|---|
| 414 | n/a | threading.activeCount() |
|---|
| 415 | n/a | |
|---|
| 416 | n/a | def test_repr_daemon(self): |
|---|
| 417 | n/a | t = threading.Thread() |
|---|
| 418 | n/a | self.assertNotIn('daemon', repr(t)) |
|---|
| 419 | n/a | t.daemon = True |
|---|
| 420 | n/a | self.assertIn('daemon', repr(t)) |
|---|
| 421 | n/a | |
|---|
| 422 | n/a | def test_deamon_param(self): |
|---|
| 423 | n/a | t = threading.Thread() |
|---|
| 424 | n/a | self.assertFalse(t.daemon) |
|---|
| 425 | n/a | t = threading.Thread(daemon=False) |
|---|
| 426 | n/a | self.assertFalse(t.daemon) |
|---|
| 427 | n/a | t = threading.Thread(daemon=True) |
|---|
| 428 | n/a | self.assertTrue(t.daemon) |
|---|
| 429 | n/a | |
|---|
| 430 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()') |
|---|
| 431 | n/a | def test_dummy_thread_after_fork(self): |
|---|
| 432 | n/a | # Issue #14308: a dummy thread in the active list doesn't mess up |
|---|
| 433 | n/a | # the after-fork mechanism. |
|---|
| 434 | n/a | code = """if 1: |
|---|
| 435 | n/a | import _thread, threading, os, time |
|---|
| 436 | n/a | |
|---|
| 437 | n/a | def background_thread(evt): |
|---|
| 438 | n/a | # Creates and registers the _DummyThread instance |
|---|
| 439 | n/a | threading.current_thread() |
|---|
| 440 | n/a | evt.set() |
|---|
| 441 | n/a | time.sleep(10) |
|---|
| 442 | n/a | |
|---|
| 443 | n/a | evt = threading.Event() |
|---|
| 444 | n/a | _thread.start_new_thread(background_thread, (evt,)) |
|---|
| 445 | n/a | evt.wait() |
|---|
| 446 | n/a | assert threading.active_count() == 2, threading.active_count() |
|---|
| 447 | n/a | if os.fork() == 0: |
|---|
| 448 | n/a | assert threading.active_count() == 1, threading.active_count() |
|---|
| 449 | n/a | os._exit(0) |
|---|
| 450 | n/a | else: |
|---|
| 451 | n/a | os.wait() |
|---|
| 452 | n/a | """ |
|---|
| 453 | n/a | _, out, err = assert_python_ok("-c", code) |
|---|
| 454 | n/a | self.assertEqual(out, b'') |
|---|
| 455 | n/a | self.assertEqual(err, b'') |
|---|
| 456 | n/a | |
|---|
| 457 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
|---|
| 458 | n/a | def test_is_alive_after_fork(self): |
|---|
| 459 | n/a | # Try hard to trigger #18418: is_alive() could sometimes be True on |
|---|
| 460 | n/a | # threads that vanished after a fork. |
|---|
| 461 | n/a | old_interval = sys.getswitchinterval() |
|---|
| 462 | n/a | self.addCleanup(sys.setswitchinterval, old_interval) |
|---|
| 463 | n/a | |
|---|
| 464 | n/a | # Make the bug more likely to manifest. |
|---|
| 465 | n/a | test.support.setswitchinterval(1e-6) |
|---|
| 466 | n/a | |
|---|
| 467 | n/a | for i in range(20): |
|---|
| 468 | n/a | t = threading.Thread(target=lambda: None) |
|---|
| 469 | n/a | t.start() |
|---|
| 470 | n/a | self.addCleanup(t.join) |
|---|
| 471 | n/a | pid = os.fork() |
|---|
| 472 | n/a | if pid == 0: |
|---|
| 473 | n/a | os._exit(1 if t.is_alive() else 0) |
|---|
| 474 | n/a | else: |
|---|
| 475 | n/a | pid, status = os.waitpid(pid, 0) |
|---|
| 476 | n/a | self.assertEqual(0, status) |
|---|
| 477 | n/a | |
|---|
| 478 | n/a | def test_main_thread(self): |
|---|
| 479 | n/a | main = threading.main_thread() |
|---|
| 480 | n/a | self.assertEqual(main.name, 'MainThread') |
|---|
| 481 | n/a | self.assertEqual(main.ident, threading.current_thread().ident) |
|---|
| 482 | n/a | self.assertEqual(main.ident, threading.get_ident()) |
|---|
| 483 | n/a | |
|---|
| 484 | n/a | def f(): |
|---|
| 485 | n/a | self.assertNotEqual(threading.main_thread().ident, |
|---|
| 486 | n/a | threading.current_thread().ident) |
|---|
| 487 | n/a | th = threading.Thread(target=f) |
|---|
| 488 | n/a | th.start() |
|---|
| 489 | n/a | th.join() |
|---|
| 490 | n/a | |
|---|
| 491 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") |
|---|
| 492 | n/a | @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()") |
|---|
| 493 | n/a | def test_main_thread_after_fork(self): |
|---|
| 494 | n/a | code = """if 1: |
|---|
| 495 | n/a | import os, threading |
|---|
| 496 | n/a | |
|---|
| 497 | n/a | pid = os.fork() |
|---|
| 498 | n/a | if pid == 0: |
|---|
| 499 | n/a | main = threading.main_thread() |
|---|
| 500 | n/a | print(main.name) |
|---|
| 501 | n/a | print(main.ident == threading.current_thread().ident) |
|---|
| 502 | n/a | print(main.ident == threading.get_ident()) |
|---|
| 503 | n/a | else: |
|---|
| 504 | n/a | os.waitpid(pid, 0) |
|---|
| 505 | n/a | """ |
|---|
| 506 | n/a | _, out, err = assert_python_ok("-c", code) |
|---|
| 507 | n/a | data = out.decode().replace('\r', '') |
|---|
| 508 | n/a | self.assertEqual(err, b"") |
|---|
| 509 | n/a | self.assertEqual(data, "MainThread\nTrue\nTrue\n") |
|---|
| 510 | n/a | |
|---|
| 511 | n/a | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
|---|
| 512 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") |
|---|
| 513 | n/a | @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()") |
|---|
| 514 | n/a | def test_main_thread_after_fork_from_nonmain_thread(self): |
|---|
| 515 | n/a | code = """if 1: |
|---|
| 516 | n/a | import os, threading, sys |
|---|
| 517 | n/a | |
|---|
| 518 | n/a | def f(): |
|---|
| 519 | n/a | pid = os.fork() |
|---|
| 520 | n/a | if pid == 0: |
|---|
| 521 | n/a | main = threading.main_thread() |
|---|
| 522 | n/a | print(main.name) |
|---|
| 523 | n/a | print(main.ident == threading.current_thread().ident) |
|---|
| 524 | n/a | print(main.ident == threading.get_ident()) |
|---|
| 525 | n/a | # stdout is fully buffered because not a tty, |
|---|
| 526 | n/a | # we have to flush before exit. |
|---|
| 527 | n/a | sys.stdout.flush() |
|---|
| 528 | n/a | else: |
|---|
| 529 | n/a | os.waitpid(pid, 0) |
|---|
| 530 | n/a | |
|---|
| 531 | n/a | th = threading.Thread(target=f) |
|---|
| 532 | n/a | th.start() |
|---|
| 533 | n/a | th.join() |
|---|
| 534 | n/a | """ |
|---|
| 535 | n/a | _, out, err = assert_python_ok("-c", code) |
|---|
| 536 | n/a | data = out.decode().replace('\r', '') |
|---|
| 537 | n/a | self.assertEqual(err, b"") |
|---|
| 538 | n/a | self.assertEqual(data, "Thread-1\nTrue\nTrue\n") |
|---|
| 539 | n/a | |
|---|
| 540 | n/a | def test_tstate_lock(self): |
|---|
| 541 | n/a | # Test an implementation detail of Thread objects. |
|---|
| 542 | n/a | started = _thread.allocate_lock() |
|---|
| 543 | n/a | finish = _thread.allocate_lock() |
|---|
| 544 | n/a | started.acquire() |
|---|
| 545 | n/a | finish.acquire() |
|---|
| 546 | n/a | def f(): |
|---|
| 547 | n/a | started.release() |
|---|
| 548 | n/a | finish.acquire() |
|---|
| 549 | n/a | time.sleep(0.01) |
|---|
| 550 | n/a | # The tstate lock is None until the thread is started |
|---|
| 551 | n/a | t = threading.Thread(target=f) |
|---|
| 552 | n/a | self.assertIs(t._tstate_lock, None) |
|---|
| 553 | n/a | t.start() |
|---|
| 554 | n/a | started.acquire() |
|---|
| 555 | n/a | self.assertTrue(t.is_alive()) |
|---|
| 556 | n/a | # The tstate lock can't be acquired when the thread is running |
|---|
| 557 | n/a | # (or suspended). |
|---|
| 558 | n/a | tstate_lock = t._tstate_lock |
|---|
| 559 | n/a | self.assertFalse(tstate_lock.acquire(timeout=0), False) |
|---|
| 560 | n/a | finish.release() |
|---|
| 561 | n/a | # When the thread ends, the state_lock can be successfully |
|---|
| 562 | n/a | # acquired. |
|---|
| 563 | n/a | self.assertTrue(tstate_lock.acquire(timeout=5), False) |
|---|
| 564 | n/a | # But is_alive() is still True: we hold _tstate_lock now, which |
|---|
| 565 | n/a | # prevents is_alive() from knowing the thread's end-of-life C code |
|---|
| 566 | n/a | # is done. |
|---|
| 567 | n/a | self.assertTrue(t.is_alive()) |
|---|
| 568 | n/a | # Let is_alive() find out the C code is done. |
|---|
| 569 | n/a | tstate_lock.release() |
|---|
| 570 | n/a | self.assertFalse(t.is_alive()) |
|---|
| 571 | n/a | # And verify the thread disposed of _tstate_lock. |
|---|
| 572 | n/a | self.assertIsNone(t._tstate_lock) |
|---|
| 573 | n/a | |
|---|
| 574 | n/a | def test_repr_stopped(self): |
|---|
| 575 | n/a | # Verify that "stopped" shows up in repr(Thread) appropriately. |
|---|
| 576 | n/a | started = _thread.allocate_lock() |
|---|
| 577 | n/a | finish = _thread.allocate_lock() |
|---|
| 578 | n/a | started.acquire() |
|---|
| 579 | n/a | finish.acquire() |
|---|
| 580 | n/a | def f(): |
|---|
| 581 | n/a | started.release() |
|---|
| 582 | n/a | finish.acquire() |
|---|
| 583 | n/a | t = threading.Thread(target=f) |
|---|
| 584 | n/a | t.start() |
|---|
| 585 | n/a | started.acquire() |
|---|
| 586 | n/a | self.assertIn("started", repr(t)) |
|---|
| 587 | n/a | finish.release() |
|---|
| 588 | n/a | # "stopped" should appear in the repr in a reasonable amount of time. |
|---|
| 589 | n/a | # Implementation detail: as of this writing, that's trivially true |
|---|
| 590 | n/a | # if .join() is called, and almost trivially true if .is_alive() is |
|---|
| 591 | n/a | # called. The detail we're testing here is that "stopped" shows up |
|---|
| 592 | n/a | # "all on its own". |
|---|
| 593 | n/a | LOOKING_FOR = "stopped" |
|---|
| 594 | n/a | for i in range(500): |
|---|
| 595 | n/a | if LOOKING_FOR in repr(t): |
|---|
| 596 | n/a | break |
|---|
| 597 | n/a | time.sleep(0.01) |
|---|
| 598 | n/a | self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds |
|---|
| 599 | n/a | |
|---|
| 600 | n/a | def test_BoundedSemaphore_limit(self): |
|---|
| 601 | n/a | # BoundedSemaphore should raise ValueError if released too often. |
|---|
| 602 | n/a | for limit in range(1, 10): |
|---|
| 603 | n/a | bs = threading.BoundedSemaphore(limit) |
|---|
| 604 | n/a | threads = [threading.Thread(target=bs.acquire) |
|---|
| 605 | n/a | for _ in range(limit)] |
|---|
| 606 | n/a | for t in threads: |
|---|
| 607 | n/a | t.start() |
|---|
| 608 | n/a | for t in threads: |
|---|
| 609 | n/a | t.join() |
|---|
| 610 | n/a | threads = [threading.Thread(target=bs.release) |
|---|
| 611 | n/a | for _ in range(limit)] |
|---|
| 612 | n/a | for t in threads: |
|---|
| 613 | n/a | t.start() |
|---|
| 614 | n/a | for t in threads: |
|---|
| 615 | n/a | t.join() |
|---|
| 616 | n/a | self.assertRaises(ValueError, bs.release) |
|---|
| 617 | n/a | |
|---|
| 618 | n/a | @cpython_only |
|---|
| 619 | n/a | def test_frame_tstate_tracing(self): |
|---|
| 620 | n/a | # Issue #14432: Crash when a generator is created in a C thread that is |
|---|
| 621 | n/a | # destroyed while the generator is still used. The issue was that a |
|---|
| 622 | n/a | # generator contains a frame, and the frame kept a reference to the |
|---|
| 623 | n/a | # Python state of the destroyed C thread. The crash occurs when a trace |
|---|
| 624 | n/a | # function is setup. |
|---|
| 625 | n/a | |
|---|
| 626 | n/a | def noop_trace(frame, event, arg): |
|---|
| 627 | n/a | # no operation |
|---|
| 628 | n/a | return noop_trace |
|---|
| 629 | n/a | |
|---|
| 630 | n/a | def generator(): |
|---|
| 631 | n/a | while 1: |
|---|
| 632 | n/a | yield "generator" |
|---|
| 633 | n/a | |
|---|
| 634 | n/a | def callback(): |
|---|
| 635 | n/a | if callback.gen is None: |
|---|
| 636 | n/a | callback.gen = generator() |
|---|
| 637 | n/a | return next(callback.gen) |
|---|
| 638 | n/a | callback.gen = None |
|---|
| 639 | n/a | |
|---|
| 640 | n/a | old_trace = sys.gettrace() |
|---|
| 641 | n/a | sys.settrace(noop_trace) |
|---|
| 642 | n/a | try: |
|---|
| 643 | n/a | # Install a trace function |
|---|
| 644 | n/a | threading.settrace(noop_trace) |
|---|
| 645 | n/a | |
|---|
| 646 | n/a | # Create a generator in a C thread which exits after the call |
|---|
| 647 | n/a | import _testcapi |
|---|
| 648 | n/a | _testcapi.call_in_temporary_c_thread(callback) |
|---|
| 649 | n/a | |
|---|
| 650 | n/a | # Call the generator in a different Python thread, check that the |
|---|
| 651 | n/a | # generator didn't keep a reference to the destroyed thread state |
|---|
| 652 | n/a | for test in range(3): |
|---|
| 653 | n/a | # The trace function is still called here |
|---|
| 654 | n/a | callback() |
|---|
| 655 | n/a | finally: |
|---|
| 656 | n/a | sys.settrace(old_trace) |
|---|
| 657 | n/a | |
|---|
| 658 | n/a | |
|---|
| 659 | n/a | class ThreadJoinOnShutdown(BaseTestCase): |
|---|
| 660 | n/a | |
|---|
| 661 | n/a | def _run_and_join(self, script): |
|---|
| 662 | n/a | script = """if 1: |
|---|
| 663 | n/a | import sys, os, time, threading |
|---|
| 664 | n/a | |
|---|
| 665 | n/a | # a thread, which waits for the main program to terminate |
|---|
| 666 | n/a | def joiningfunc(mainthread): |
|---|
| 667 | n/a | mainthread.join() |
|---|
| 668 | n/a | print('end of thread') |
|---|
| 669 | n/a | # stdout is fully buffered because not a tty, we have to flush |
|---|
| 670 | n/a | # before exit. |
|---|
| 671 | n/a | sys.stdout.flush() |
|---|
| 672 | n/a | \n""" + script |
|---|
| 673 | n/a | |
|---|
| 674 | n/a | rc, out, err = assert_python_ok("-c", script) |
|---|
| 675 | n/a | data = out.decode().replace('\r', '') |
|---|
| 676 | n/a | self.assertEqual(data, "end of main\nend of thread\n") |
|---|
| 677 | n/a | |
|---|
| 678 | n/a | def test_1_join_on_shutdown(self): |
|---|
| 679 | n/a | # The usual case: on exit, wait for a non-daemon thread |
|---|
| 680 | n/a | script = """if 1: |
|---|
| 681 | n/a | import os |
|---|
| 682 | n/a | t = threading.Thread(target=joiningfunc, |
|---|
| 683 | n/a | args=(threading.current_thread(),)) |
|---|
| 684 | n/a | t.start() |
|---|
| 685 | n/a | time.sleep(0.1) |
|---|
| 686 | n/a | print('end of main') |
|---|
| 687 | n/a | """ |
|---|
| 688 | n/a | self._run_and_join(script) |
|---|
| 689 | n/a | |
|---|
| 690 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
|---|
| 691 | n/a | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
|---|
| 692 | n/a | def test_2_join_in_forked_process(self): |
|---|
| 693 | n/a | # Like the test above, but from a forked interpreter |
|---|
| 694 | n/a | script = """if 1: |
|---|
| 695 | n/a | childpid = os.fork() |
|---|
| 696 | n/a | if childpid != 0: |
|---|
| 697 | n/a | os.waitpid(childpid, 0) |
|---|
| 698 | n/a | sys.exit(0) |
|---|
| 699 | n/a | |
|---|
| 700 | n/a | t = threading.Thread(target=joiningfunc, |
|---|
| 701 | n/a | args=(threading.current_thread(),)) |
|---|
| 702 | n/a | t.start() |
|---|
| 703 | n/a | print('end of main') |
|---|
| 704 | n/a | """ |
|---|
| 705 | n/a | self._run_and_join(script) |
|---|
| 706 | n/a | |
|---|
| 707 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
|---|
| 708 | n/a | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
|---|
| 709 | n/a | def test_3_join_in_forked_from_thread(self): |
|---|
| 710 | n/a | # Like the test above, but fork() was called from a worker thread |
|---|
| 711 | n/a | # In the forked process, the main Thread object must be marked as stopped. |
|---|
| 712 | n/a | |
|---|
| 713 | n/a | script = """if 1: |
|---|
| 714 | n/a | main_thread = threading.current_thread() |
|---|
| 715 | n/a | def worker(): |
|---|
| 716 | n/a | childpid = os.fork() |
|---|
| 717 | n/a | if childpid != 0: |
|---|
| 718 | n/a | os.waitpid(childpid, 0) |
|---|
| 719 | n/a | sys.exit(0) |
|---|
| 720 | n/a | |
|---|
| 721 | n/a | t = threading.Thread(target=joiningfunc, |
|---|
| 722 | n/a | args=(main_thread,)) |
|---|
| 723 | n/a | print('end of main') |
|---|
| 724 | n/a | t.start() |
|---|
| 725 | n/a | t.join() # Should not block: main_thread is already stopped |
|---|
| 726 | n/a | |
|---|
| 727 | n/a | w = threading.Thread(target=worker) |
|---|
| 728 | n/a | w.start() |
|---|
| 729 | n/a | """ |
|---|
| 730 | n/a | self._run_and_join(script) |
|---|
| 731 | n/a | |
|---|
| 732 | n/a | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
|---|
| 733 | n/a | def test_4_daemon_threads(self): |
|---|
| 734 | n/a | # Check that a daemon thread cannot crash the interpreter on shutdown |
|---|
| 735 | n/a | # by manipulating internal structures that are being disposed of in |
|---|
| 736 | n/a | # the main thread. |
|---|
| 737 | n/a | script = """if True: |
|---|
| 738 | n/a | import os |
|---|
| 739 | n/a | import random |
|---|
| 740 | n/a | import sys |
|---|
| 741 | n/a | import time |
|---|
| 742 | n/a | import threading |
|---|
| 743 | n/a | |
|---|
| 744 | n/a | thread_has_run = set() |
|---|
| 745 | n/a | |
|---|
| 746 | n/a | def random_io(): |
|---|
| 747 | n/a | '''Loop for a while sleeping random tiny amounts and doing some I/O.''' |
|---|
| 748 | n/a | while True: |
|---|
| 749 | n/a | in_f = open(os.__file__, 'rb') |
|---|
| 750 | n/a | stuff = in_f.read(200) |
|---|
| 751 | n/a | null_f = open(os.devnull, 'wb') |
|---|
| 752 | n/a | null_f.write(stuff) |
|---|
| 753 | n/a | time.sleep(random.random() / 1995) |
|---|
| 754 | n/a | null_f.close() |
|---|
| 755 | n/a | in_f.close() |
|---|
| 756 | n/a | thread_has_run.add(threading.current_thread()) |
|---|
| 757 | n/a | |
|---|
| 758 | n/a | def main(): |
|---|
| 759 | n/a | count = 0 |
|---|
| 760 | n/a | for _ in range(40): |
|---|
| 761 | n/a | new_thread = threading.Thread(target=random_io) |
|---|
| 762 | n/a | new_thread.daemon = True |
|---|
| 763 | n/a | new_thread.start() |
|---|
| 764 | n/a | count += 1 |
|---|
| 765 | n/a | while len(thread_has_run) < count: |
|---|
| 766 | n/a | time.sleep(0.001) |
|---|
| 767 | n/a | # Trigger process shutdown |
|---|
| 768 | n/a | sys.exit(0) |
|---|
| 769 | n/a | |
|---|
| 770 | n/a | main() |
|---|
| 771 | n/a | """ |
|---|
| 772 | n/a | rc, out, err = assert_python_ok('-c', script) |
|---|
| 773 | n/a | self.assertFalse(err) |
|---|
| 774 | n/a | |
|---|
| 775 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
|---|
| 776 | n/a | @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") |
|---|
| 777 | n/a | def test_reinit_tls_after_fork(self): |
|---|
| 778 | n/a | # Issue #13817: fork() would deadlock in a multithreaded program with |
|---|
| 779 | n/a | # the ad-hoc TLS implementation. |
|---|
| 780 | n/a | |
|---|
| 781 | n/a | def do_fork_and_wait(): |
|---|
| 782 | n/a | # just fork a child process and wait it |
|---|
| 783 | n/a | pid = os.fork() |
|---|
| 784 | n/a | if pid > 0: |
|---|
| 785 | n/a | os.waitpid(pid, 0) |
|---|
| 786 | n/a | else: |
|---|
| 787 | n/a | os._exit(0) |
|---|
| 788 | n/a | |
|---|
| 789 | n/a | # start a bunch of threads that will fork() child processes |
|---|
| 790 | n/a | threads = [] |
|---|
| 791 | n/a | for i in range(16): |
|---|
| 792 | n/a | t = threading.Thread(target=do_fork_and_wait) |
|---|
| 793 | n/a | threads.append(t) |
|---|
| 794 | n/a | t.start() |
|---|
| 795 | n/a | |
|---|
| 796 | n/a | for t in threads: |
|---|
| 797 | n/a | t.join() |
|---|
| 798 | n/a | |
|---|
| 799 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") |
|---|
| 800 | n/a | def test_clear_threads_states_after_fork(self): |
|---|
| 801 | n/a | # Issue #17094: check that threads states are cleared after fork() |
|---|
| 802 | n/a | |
|---|
| 803 | n/a | # start a bunch of threads |
|---|
| 804 | n/a | threads = [] |
|---|
| 805 | n/a | for i in range(16): |
|---|
| 806 | n/a | t = threading.Thread(target=lambda : time.sleep(0.3)) |
|---|
| 807 | n/a | threads.append(t) |
|---|
| 808 | n/a | t.start() |
|---|
| 809 | n/a | |
|---|
| 810 | n/a | pid = os.fork() |
|---|
| 811 | n/a | if pid == 0: |
|---|
| 812 | n/a | # check that threads states have been cleared |
|---|
| 813 | n/a | if len(sys._current_frames()) == 1: |
|---|
| 814 | n/a | os._exit(0) |
|---|
| 815 | n/a | else: |
|---|
| 816 | n/a | os._exit(1) |
|---|
| 817 | n/a | else: |
|---|
| 818 | n/a | _, status = os.waitpid(pid, 0) |
|---|
| 819 | n/a | self.assertEqual(0, status) |
|---|
| 820 | n/a | |
|---|
| 821 | n/a | for t in threads: |
|---|
| 822 | n/a | t.join() |
|---|
| 823 | n/a | |
|---|
| 824 | n/a | |
|---|
| 825 | n/a | class SubinterpThreadingTests(BaseTestCase): |
|---|
| 826 | n/a | |
|---|
| 827 | n/a | def test_threads_join(self): |
|---|
| 828 | n/a | # Non-daemon threads should be joined at subinterpreter shutdown |
|---|
| 829 | n/a | # (issue #18808) |
|---|
| 830 | n/a | r, w = os.pipe() |
|---|
| 831 | n/a | self.addCleanup(os.close, r) |
|---|
| 832 | n/a | self.addCleanup(os.close, w) |
|---|
| 833 | n/a | code = r"""if 1: |
|---|
| 834 | n/a | import os |
|---|
| 835 | n/a | import threading |
|---|
| 836 | n/a | import time |
|---|
| 837 | n/a | |
|---|
| 838 | n/a | def f(): |
|---|
| 839 | n/a | # Sleep a bit so that the thread is still running when |
|---|
| 840 | n/a | # Py_EndInterpreter is called. |
|---|
| 841 | n/a | time.sleep(0.05) |
|---|
| 842 | n/a | os.write(%d, b"x") |
|---|
| 843 | n/a | threading.Thread(target=f).start() |
|---|
| 844 | n/a | """ % (w,) |
|---|
| 845 | n/a | ret = test.support.run_in_subinterp(code) |
|---|
| 846 | n/a | self.assertEqual(ret, 0) |
|---|
| 847 | n/a | # The thread was joined properly. |
|---|
| 848 | n/a | self.assertEqual(os.read(r, 1), b"x") |
|---|
| 849 | n/a | |
|---|
| 850 | n/a | def test_threads_join_2(self): |
|---|
| 851 | n/a | # Same as above, but a delay gets introduced after the thread's |
|---|
| 852 | n/a | # Python code returned but before the thread state is deleted. |
|---|
| 853 | n/a | # To achieve this, we register a thread-local object which sleeps |
|---|
| 854 | n/a | # a bit when deallocated. |
|---|
| 855 | n/a | r, w = os.pipe() |
|---|
| 856 | n/a | self.addCleanup(os.close, r) |
|---|
| 857 | n/a | self.addCleanup(os.close, w) |
|---|
| 858 | n/a | code = r"""if 1: |
|---|
| 859 | n/a | import os |
|---|
| 860 | n/a | import threading |
|---|
| 861 | n/a | import time |
|---|
| 862 | n/a | |
|---|
| 863 | n/a | class Sleeper: |
|---|
| 864 | n/a | def __del__(self): |
|---|
| 865 | n/a | time.sleep(0.05) |
|---|
| 866 | n/a | |
|---|
| 867 | n/a | tls = threading.local() |
|---|
| 868 | n/a | |
|---|
| 869 | n/a | def f(): |
|---|
| 870 | n/a | # Sleep a bit so that the thread is still running when |
|---|
| 871 | n/a | # Py_EndInterpreter is called. |
|---|
| 872 | n/a | time.sleep(0.05) |
|---|
| 873 | n/a | tls.x = Sleeper() |
|---|
| 874 | n/a | os.write(%d, b"x") |
|---|
| 875 | n/a | threading.Thread(target=f).start() |
|---|
| 876 | n/a | """ % (w,) |
|---|
| 877 | n/a | ret = test.support.run_in_subinterp(code) |
|---|
| 878 | n/a | self.assertEqual(ret, 0) |
|---|
| 879 | n/a | # The thread was joined properly. |
|---|
| 880 | n/a | self.assertEqual(os.read(r, 1), b"x") |
|---|
| 881 | n/a | |
|---|
| 882 | n/a | @cpython_only |
|---|
| 883 | n/a | def test_daemon_threads_fatal_error(self): |
|---|
| 884 | n/a | subinterp_code = r"""if 1: |
|---|
| 885 | n/a | import os |
|---|
| 886 | n/a | import threading |
|---|
| 887 | n/a | import time |
|---|
| 888 | n/a | |
|---|
| 889 | n/a | def f(): |
|---|
| 890 | n/a | # Make sure the daemon thread is still running when |
|---|
| 891 | n/a | # Py_EndInterpreter is called. |
|---|
| 892 | n/a | time.sleep(10) |
|---|
| 893 | n/a | threading.Thread(target=f, daemon=True).start() |
|---|
| 894 | n/a | """ |
|---|
| 895 | n/a | script = r"""if 1: |
|---|
| 896 | n/a | import _testcapi |
|---|
| 897 | n/a | |
|---|
| 898 | n/a | _testcapi.run_in_subinterp(%r) |
|---|
| 899 | n/a | """ % (subinterp_code,) |
|---|
| 900 | n/a | with test.support.SuppressCrashReport(): |
|---|
| 901 | n/a | rc, out, err = assert_python_failure("-c", script) |
|---|
| 902 | n/a | self.assertIn("Fatal Python error: Py_EndInterpreter: " |
|---|
| 903 | n/a | "not the last thread", err.decode()) |
|---|
| 904 | n/a | |
|---|
| 905 | n/a | |
|---|
| 906 | n/a | class ThreadingExceptionTests(BaseTestCase): |
|---|
| 907 | n/a | # A RuntimeError should be raised if Thread.start() is called |
|---|
| 908 | n/a | # multiple times. |
|---|
| 909 | n/a | def test_start_thread_again(self): |
|---|
| 910 | n/a | thread = threading.Thread() |
|---|
| 911 | n/a | thread.start() |
|---|
| 912 | n/a | self.assertRaises(RuntimeError, thread.start) |
|---|
| 913 | n/a | |
|---|
| 914 | n/a | def test_joining_current_thread(self): |
|---|
| 915 | n/a | current_thread = threading.current_thread() |
|---|
| 916 | n/a | self.assertRaises(RuntimeError, current_thread.join); |
|---|
| 917 | n/a | |
|---|
| 918 | n/a | def test_joining_inactive_thread(self): |
|---|
| 919 | n/a | thread = threading.Thread() |
|---|
| 920 | n/a | self.assertRaises(RuntimeError, thread.join) |
|---|
| 921 | n/a | |
|---|
| 922 | n/a | def test_daemonize_active_thread(self): |
|---|
| 923 | n/a | thread = threading.Thread() |
|---|
| 924 | n/a | thread.start() |
|---|
| 925 | n/a | self.assertRaises(RuntimeError, setattr, thread, "daemon", True) |
|---|
| 926 | n/a | |
|---|
| 927 | n/a | def test_releasing_unacquired_lock(self): |
|---|
| 928 | n/a | lock = threading.Lock() |
|---|
| 929 | n/a | self.assertRaises(RuntimeError, lock.release) |
|---|
| 930 | n/a | |
|---|
| 931 | n/a | @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(), |
|---|
| 932 | n/a | 'test macosx problem') |
|---|
| 933 | n/a | def test_recursion_limit(self): |
|---|
| 934 | n/a | # Issue 9670 |
|---|
| 935 | n/a | # test that excessive recursion within a non-main thread causes |
|---|
| 936 | n/a | # an exception rather than crashing the interpreter on platforms |
|---|
| 937 | n/a | # like Mac OS X or FreeBSD which have small default stack sizes |
|---|
| 938 | n/a | # for threads |
|---|
| 939 | n/a | script = """if True: |
|---|
| 940 | n/a | import threading |
|---|
| 941 | n/a | |
|---|
| 942 | n/a | def recurse(): |
|---|
| 943 | n/a | return recurse() |
|---|
| 944 | n/a | |
|---|
| 945 | n/a | def outer(): |
|---|
| 946 | n/a | try: |
|---|
| 947 | n/a | recurse() |
|---|
| 948 | n/a | except RecursionError: |
|---|
| 949 | n/a | pass |
|---|
| 950 | n/a | |
|---|
| 951 | n/a | w = threading.Thread(target=outer) |
|---|
| 952 | n/a | w.start() |
|---|
| 953 | n/a | w.join() |
|---|
| 954 | n/a | print('end of main thread') |
|---|
| 955 | n/a | """ |
|---|
| 956 | n/a | expected_output = "end of main thread\n" |
|---|
| 957 | n/a | p = subprocess.Popen([sys.executable, "-c", script], |
|---|
| 958 | n/a | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
|---|
| 959 | n/a | stdout, stderr = p.communicate() |
|---|
| 960 | n/a | data = stdout.decode().replace('\r', '') |
|---|
| 961 | n/a | self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode()) |
|---|
| 962 | n/a | self.assertEqual(data, expected_output) |
|---|
| 963 | n/a | |
|---|
| 964 | n/a | def test_print_exception(self): |
|---|
| 965 | n/a | script = r"""if True: |
|---|
| 966 | n/a | import threading |
|---|
| 967 | n/a | import time |
|---|
| 968 | n/a | |
|---|
| 969 | n/a | running = False |
|---|
| 970 | n/a | def run(): |
|---|
| 971 | n/a | global running |
|---|
| 972 | n/a | running = True |
|---|
| 973 | n/a | while running: |
|---|
| 974 | n/a | time.sleep(0.01) |
|---|
| 975 | n/a | 1/0 |
|---|
| 976 | n/a | t = threading.Thread(target=run) |
|---|
| 977 | n/a | t.start() |
|---|
| 978 | n/a | while not running: |
|---|
| 979 | n/a | time.sleep(0.01) |
|---|
| 980 | n/a | running = False |
|---|
| 981 | n/a | t.join() |
|---|
| 982 | n/a | """ |
|---|
| 983 | n/a | rc, out, err = assert_python_ok("-c", script) |
|---|
| 984 | n/a | self.assertEqual(out, b'') |
|---|
| 985 | n/a | err = err.decode() |
|---|
| 986 | n/a | self.assertIn("Exception in thread", err) |
|---|
| 987 | n/a | self.assertIn("Traceback (most recent call last):", err) |
|---|
| 988 | n/a | self.assertIn("ZeroDivisionError", err) |
|---|
| 989 | n/a | self.assertNotIn("Unhandled exception", err) |
|---|
| 990 | n/a | |
|---|
| 991 | n/a | @requires_type_collecting |
|---|
| 992 | n/a | def test_print_exception_stderr_is_none_1(self): |
|---|
| 993 | n/a | script = r"""if True: |
|---|
| 994 | n/a | import sys |
|---|
| 995 | n/a | import threading |
|---|
| 996 | n/a | import time |
|---|
| 997 | n/a | |
|---|
| 998 | n/a | running = False |
|---|
| 999 | n/a | def run(): |
|---|
| 1000 | n/a | global running |
|---|
| 1001 | n/a | running = True |
|---|
| 1002 | n/a | while running: |
|---|
| 1003 | n/a | time.sleep(0.01) |
|---|
| 1004 | n/a | 1/0 |
|---|
| 1005 | n/a | t = threading.Thread(target=run) |
|---|
| 1006 | n/a | t.start() |
|---|
| 1007 | n/a | while not running: |
|---|
| 1008 | n/a | time.sleep(0.01) |
|---|
| 1009 | n/a | sys.stderr = None |
|---|
| 1010 | n/a | running = False |
|---|
| 1011 | n/a | t.join() |
|---|
| 1012 | n/a | """ |
|---|
| 1013 | n/a | rc, out, err = assert_python_ok("-c", script) |
|---|
| 1014 | n/a | self.assertEqual(out, b'') |
|---|
| 1015 | n/a | err = err.decode() |
|---|
| 1016 | n/a | self.assertIn("Exception in thread", err) |
|---|
| 1017 | n/a | self.assertIn("Traceback (most recent call last):", err) |
|---|
| 1018 | n/a | self.assertIn("ZeroDivisionError", err) |
|---|
| 1019 | n/a | self.assertNotIn("Unhandled exception", err) |
|---|
| 1020 | n/a | |
|---|
| 1021 | n/a | def test_print_exception_stderr_is_none_2(self): |
|---|
| 1022 | n/a | script = r"""if True: |
|---|
| 1023 | n/a | import sys |
|---|
| 1024 | n/a | import threading |
|---|
| 1025 | n/a | import time |
|---|
| 1026 | n/a | |
|---|
| 1027 | n/a | running = False |
|---|
| 1028 | n/a | def run(): |
|---|
| 1029 | n/a | global running |
|---|
| 1030 | n/a | running = True |
|---|
| 1031 | n/a | while running: |
|---|
| 1032 | n/a | time.sleep(0.01) |
|---|
| 1033 | n/a | 1/0 |
|---|
| 1034 | n/a | sys.stderr = None |
|---|
| 1035 | n/a | t = threading.Thread(target=run) |
|---|
| 1036 | n/a | t.start() |
|---|
| 1037 | n/a | while not running: |
|---|
| 1038 | n/a | time.sleep(0.01) |
|---|
| 1039 | n/a | running = False |
|---|
| 1040 | n/a | t.join() |
|---|
| 1041 | n/a | """ |
|---|
| 1042 | n/a | rc, out, err = assert_python_ok("-c", script) |
|---|
| 1043 | n/a | self.assertEqual(out, b'') |
|---|
| 1044 | n/a | self.assertNotIn("Unhandled exception", err.decode()) |
|---|
| 1045 | n/a | |
|---|
| 1046 | n/a | def test_bare_raise_in_brand_new_thread(self): |
|---|
| 1047 | n/a | def bare_raise(): |
|---|
| 1048 | n/a | raise |
|---|
| 1049 | n/a | |
|---|
| 1050 | n/a | class Issue27558(threading.Thread): |
|---|
| 1051 | n/a | exc = None |
|---|
| 1052 | n/a | |
|---|
| 1053 | n/a | def run(self): |
|---|
| 1054 | n/a | try: |
|---|
| 1055 | n/a | bare_raise() |
|---|
| 1056 | n/a | except Exception as exc: |
|---|
| 1057 | n/a | self.exc = exc |
|---|
| 1058 | n/a | |
|---|
| 1059 | n/a | thread = Issue27558() |
|---|
| 1060 | n/a | thread.start() |
|---|
| 1061 | n/a | thread.join() |
|---|
| 1062 | n/a | self.assertIsNotNone(thread.exc) |
|---|
| 1063 | n/a | self.assertIsInstance(thread.exc, RuntimeError) |
|---|
| 1064 | n/a | |
|---|
| 1065 | n/a | class TimerTests(BaseTestCase): |
|---|
| 1066 | n/a | |
|---|
| 1067 | n/a | def setUp(self): |
|---|
| 1068 | n/a | BaseTestCase.setUp(self) |
|---|
| 1069 | n/a | self.callback_args = [] |
|---|
| 1070 | n/a | self.callback_event = threading.Event() |
|---|
| 1071 | n/a | |
|---|
| 1072 | n/a | def test_init_immutable_default_args(self): |
|---|
| 1073 | n/a | # Issue 17435: constructor defaults were mutable objects, they could be |
|---|
| 1074 | n/a | # mutated via the object attributes and affect other Timer objects. |
|---|
| 1075 | n/a | timer1 = threading.Timer(0.01, self._callback_spy) |
|---|
| 1076 | n/a | timer1.start() |
|---|
| 1077 | n/a | self.callback_event.wait() |
|---|
| 1078 | n/a | timer1.args.append("blah") |
|---|
| 1079 | n/a | timer1.kwargs["foo"] = "bar" |
|---|
| 1080 | n/a | self.callback_event.clear() |
|---|
| 1081 | n/a | timer2 = threading.Timer(0.01, self._callback_spy) |
|---|
| 1082 | n/a | timer2.start() |
|---|
| 1083 | n/a | self.callback_event.wait() |
|---|
| 1084 | n/a | self.assertEqual(len(self.callback_args), 2) |
|---|
| 1085 | n/a | self.assertEqual(self.callback_args, [((), {}), ((), {})]) |
|---|
| 1086 | n/a | |
|---|
| 1087 | n/a | def _callback_spy(self, *args, **kwargs): |
|---|
| 1088 | n/a | self.callback_args.append((args[:], kwargs.copy())) |
|---|
| 1089 | n/a | self.callback_event.set() |
|---|
| 1090 | n/a | |
|---|
| 1091 | n/a | class LockTests(lock_tests.LockTests): |
|---|
| 1092 | n/a | locktype = staticmethod(threading.Lock) |
|---|
| 1093 | n/a | |
|---|
| 1094 | n/a | class PyRLockTests(lock_tests.RLockTests): |
|---|
| 1095 | n/a | locktype = staticmethod(threading._PyRLock) |
|---|
| 1096 | n/a | |
|---|
| 1097 | n/a | @unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C') |
|---|
| 1098 | n/a | class CRLockTests(lock_tests.RLockTests): |
|---|
| 1099 | n/a | locktype = staticmethod(threading._CRLock) |
|---|
| 1100 | n/a | |
|---|
| 1101 | n/a | class EventTests(lock_tests.EventTests): |
|---|
| 1102 | n/a | eventtype = staticmethod(threading.Event) |
|---|
| 1103 | n/a | |
|---|
| 1104 | n/a | class ConditionAsRLockTests(lock_tests.RLockTests): |
|---|
| 1105 | n/a | # Condition uses an RLock by default and exports its API. |
|---|
| 1106 | n/a | locktype = staticmethod(threading.Condition) |
|---|
| 1107 | n/a | |
|---|
| 1108 | n/a | class ConditionTests(lock_tests.ConditionTests): |
|---|
| 1109 | n/a | condtype = staticmethod(threading.Condition) |
|---|
| 1110 | n/a | |
|---|
| 1111 | n/a | class SemaphoreTests(lock_tests.SemaphoreTests): |
|---|
| 1112 | n/a | semtype = staticmethod(threading.Semaphore) |
|---|
| 1113 | n/a | |
|---|
| 1114 | n/a | class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): |
|---|
| 1115 | n/a | semtype = staticmethod(threading.BoundedSemaphore) |
|---|
| 1116 | n/a | |
|---|
| 1117 | n/a | class BarrierTests(lock_tests.BarrierTests): |
|---|
| 1118 | n/a | barriertype = staticmethod(threading.Barrier) |
|---|
| 1119 | n/a | |
|---|
| 1120 | n/a | class MiscTestCase(unittest.TestCase): |
|---|
| 1121 | n/a | def test__all__(self): |
|---|
| 1122 | n/a | extra = {"ThreadError"} |
|---|
| 1123 | n/a | blacklist = {'currentThread', 'activeCount'} |
|---|
| 1124 | n/a | support.check__all__(self, threading, ('threading', '_thread'), |
|---|
| 1125 | n/a | extra=extra, blacklist=blacklist) |
|---|
| 1126 | n/a | |
|---|
| 1127 | n/a | if __name__ == "__main__": |
|---|
| 1128 | n/a | unittest.main() |
|---|