Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 25f85d4

Browse files
committed
Issue #23309: Avoid a deadlock at shutdown if a daemon thread is aborted
while it is holding a lock to a buffered I/O object, and the main thread tries to use the same I/O object (typically stdout or stderr). A fatal error is emitted instead.
1 parent f3b990e commit 25f85d4

5 files changed

Lines changed: 94 additions & 15 deletions

File tree

Lib/test/script_helper.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Common utility functions used by various script execution tests
22
# e.g. test_cmd_line, test_cmd_line_script and test_runpy
33

4+
import collections
45
import importlib
56
import sys
67
import os
@@ -50,8 +51,12 @@ def _interpreter_requires_environment():
5051
return __cached_interp_requires_environment
5152

5253

54+
_PythonRunResult = collections.namedtuple("_PythonRunResult",
55+
("rc", "out", "err"))
56+
57+
5358
# Executing the interpreter in a subprocess
54-
def _assert_python(expected_success, *args, **env_vars):
59+
def run_python_until_end(*args, **env_vars):
5560
env_required = _interpreter_requires_environment()
5661
if '__isolated' in env_vars:
5762
isolated = env_vars.pop('__isolated')
@@ -85,12 +90,16 @@ def _assert_python(expected_success, *args, **env_vars):
8590
p.stderr.close()
8691
rc = p.returncode
8792
err = strip_python_stderr(err)
88-
if (rc and expected_success) or (not rc and not expected_success):
93+
return _PythonRunResult(rc, out, err), cmd_line
94+
95+
def _assert_python(expected_success, *args, **env_vars):
96+
res, cmd_line = run_python_until_end(*args, **env_vars)
97+
if (res.rc and expected_success) or (not res.rc and not expected_success):
8998
raise AssertionError(
9099
"Process return code is %d, command line was: %r, "
91-
"stderr follows:\n%s" % (rc, cmd_line,
92-
err.decode('ascii', 'ignore')))
93-
return rc, out, err
100+
"stderr follows:\n%s" % (res.rc, cmd_line,
101+
res.err.decode('ascii', 'ignore')))
102+
return res
94103

95104
def assert_python_ok(*args, **env_vars):
96105
"""

Lib/test/test_io.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from collections import deque, UserList
3636
from itertools import cycle, count
3737
from test import support
38-
from test.script_helper import assert_python_ok
38+
from test.script_helper import assert_python_ok, run_python_until_end
3939

4040
import codecs
4141
import io # C implementation of io
@@ -3350,6 +3350,49 @@ def read(self, n=-1):
33503350
b = bytearray(2)
33513351
self.assertRaises(ValueError, bufio.readinto, b)
33523352

3353+
@unittest.skipUnless(threading, 'Threading required for this test.')
3354+
def check_daemon_threads_shutdown_deadlock(self, stream_name):
3355+
# Issue #23309: deadlocks at shutdown should be avoided when a
3356+
# daemon thread and the main thread both write to a file.
3357+
code = """if 1:
3358+
import sys
3359+
import time
3360+
import threading
3361+
3362+
file = sys.{stream_name}
3363+
3364+
def run():
3365+
while True:
3366+
file.write('.')
3367+
file.flush()
3368+
3369+
thread = threading.Thread(target=run)
3370+
thread.daemon = True
3371+
thread.start()
3372+
3373+
time.sleep(0.5)
3374+
file.write('!')
3375+
file.flush()
3376+
""".format_map(locals())
3377+
res, _ = run_python_until_end("-c", code)
3378+
err = res.err.decode()
3379+
if res.rc != 0:
3380+
# Failure: should be a fatal error
3381+
self.assertIn("Fatal Python error: could not acquire lock "
3382+
"for <_io.BufferedWriter name='<{stream_name}>'> "
3383+
"at interpreter shutdown, possibly due to "
3384+
"daemon threads".format_map(locals()),
3385+
err)
3386+
else:
3387+
self.assertFalse(err.strip('.!'))
3388+
3389+
def test_daemon_threads_shutdown_stdout_deadlock(self):
3390+
self.check_daemon_threads_shutdown_deadlock('stdout')
3391+
3392+
def test_daemon_threads_shutdown_stderr_deadlock(self):
3393+
self.check_daemon_threads_shutdown_deadlock('stderr')
3394+
3395+
33533396
class PyMiscIOTest(MiscIOTest):
33543397
io = pyio
33553398

Lib/test/test_script_helper.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,27 @@
88

99

1010
class TestScriptHelper(unittest.TestCase):
11-
def test_assert_python_expect_success(self):
12-
t = script_helper._assert_python(True, '-c', 'import sys; sys.exit(0)')
11+
12+
def test_assert_python_ok(self):
13+
t = script_helper.assert_python_ok('-c', 'import sys; sys.exit(0)')
1314
self.assertEqual(0, t[0], 'return code was not 0')
1415

15-
def test_assert_python_expect_failure(self):
16+
def test_assert_python_failure(self):
1617
# I didn't import the sys module so this child will fail.
17-
rc, out, err = script_helper._assert_python(False, '-c', 'sys.exit(0)')
18+
rc, out, err = script_helper.assert_python_failure('-c', 'sys.exit(0)')
1819
self.assertNotEqual(0, rc, 'return code should not be 0')
1920

20-
def test_assert_python_raises_expect_success(self):
21+
def test_assert_python_ok_raises(self):
2122
# I didn't import the sys module so this child will fail.
2223
with self.assertRaises(AssertionError) as error_context:
23-
script_helper._assert_python(True, '-c', 'sys.exit(0)')
24+
script_helper.assert_python_ok('-c', 'sys.exit(0)')
2425
error_msg = str(error_context.exception)
2526
self.assertIn('command line was:', error_msg)
2627
self.assertIn('sys.exit(0)', error_msg, msg='unexpected command line')
2728

28-
def test_assert_python_raises_expect_failure(self):
29+
def test_assert_python_failure_raises(self):
2930
with self.assertRaises(AssertionError) as error_context:
30-
script_helper._assert_python(False, '-c', 'import sys; sys.exit(0)')
31+
script_helper.assert_python_failure('-c', 'import sys; sys.exit(0)')
3132
error_msg = str(error_context.exception)
3233
self.assertIn('Process return code is 0,', error_msg)
3334
self.assertIn('import sys; sys.exit(0)', error_msg,

Misc/NEWS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ Release date: tba
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #23309: Avoid a deadlock at shutdown if a daemon thread is aborted
14+
while it is holding a lock to a buffered I/O object, and the main thread
15+
tries to use the same I/O object (typically stdout or stderr). A fatal
16+
error is emitted instead.
17+
1318
- Issue #22977: Fixed formatting Windows error messages on Wine.
1419
Patch by Martin Panter.
1520

Modules/_io/bufferedio.c

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,14 +300,35 @@ typedef struct {
300300
static int
301301
_enter_buffered_busy(buffered *self)
302302
{
303+
int relax_locking;
304+
PyLockStatus st;
303305
if (self->owner == PyThread_get_thread_ident()) {
304306
PyErr_Format(PyExc_RuntimeError,
305307
"reentrant call inside %R", self);
306308
return 0;
307309
}
310+
relax_locking = (_Py_Finalizing != NULL);
308311
Py_BEGIN_ALLOW_THREADS
309-
PyThread_acquire_lock(self->lock, 1);
312+
if (!relax_locking)
313+
st = PyThread_acquire_lock(self->lock, 1);
314+
else {
315+
/* When finalizing, we don't want a deadlock to happen with daemon
316+
* threads abruptly shut down while they owned the lock.
317+
* Therefore, only wait for a grace period (1 s.).
318+
* Note that non-daemon threads have already exited here, so this
319+
* shouldn't affect carefully written threaded I/O code.
320+
*/
321+
st = PyThread_acquire_lock_timed(self->lock, 1e6, 0);
322+
}
310323
Py_END_ALLOW_THREADS
324+
if (relax_locking && st != PY_LOCK_ACQUIRED) {
325+
PyObject *msgobj = PyUnicode_FromFormat(
326+
"could not acquire lock for %A at interpreter "
327+
"shutdown, possibly due to daemon threads",
328+
(PyObject *) self);
329+
char *msg = PyUnicode_AsUTF8(msgobj);
330+
Py_FatalError(msg);
331+
}
311332
return 1;
312333
}
313334

0 commit comments

Comments
 (0)