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