Skip to content

Commit fc20b0c

Browse files
committed
Issue python#1856: Avoid crashes and lockups when daemon threads run while the
interpreter is shutting down; instead, these threads are now killed when they try to take the GIL.
2 parents c17c6d9 + 0d5e52d commit fc20b0c

File tree

6 files changed

+69
-7
lines changed

6 files changed

+69
-7
lines changed

Include/pythonrun.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,8 @@ PyAPI_FUNC(void) PyByteArray_Fini(void);
211211
PyAPI_FUNC(void) PyFloat_Fini(void);
212212
PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
213213
PyAPI_FUNC(void) _PyGC_Fini(void);
214+
215+
PyAPI_DATA(PyThreadState *) _Py_Finalizing;
214216
#endif
215217

216218
/* Stuff with no proper home (yet) */

Lib/test/test_threading.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import weakref
1313
import os
1414
import subprocess
15+
from test.script_helper import assert_python_ok
1516

1617
from test import lock_tests
1718

@@ -471,7 +472,6 @@ def test_1_join_on_shutdown(self):
471472
"""
472473
self._run_and_join(script)
473474

474-
475475
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
476476
def test_2_join_in_forked_process(self):
477477
# Like the test above, but from a forked interpreter
@@ -663,6 +663,49 @@ def my_release_save():
663663
output = "end of worker thread\nend of main thread\n"
664664
self.assertScriptHasOutput(script, output)
665665

666+
def test_6_daemon_threads(self):
667+
# Check that a daemon thread cannot crash the interpreter on shutdown
668+
# by manipulating internal structures that are being disposed of in
669+
# the main thread.
670+
script = """if True:
671+
import os
672+
import random
673+
import sys
674+
import time
675+
import threading
676+
677+
thread_has_run = set()
678+
679+
def random_io():
680+
'''Loop for a while sleeping random tiny amounts and doing some I/O.'''
681+
blank = b'x' * 200
682+
while True:
683+
in_f = open(os.__file__, 'r')
684+
stuff = in_f.read(200)
685+
null_f = open(os.devnull, 'w')
686+
null_f.write(stuff)
687+
time.sleep(random.random() / 1995)
688+
null_f.close()
689+
in_f.close()
690+
thread_has_run.add(threading.current_thread())
691+
692+
def main():
693+
count = 0
694+
for _ in range(40):
695+
new_thread = threading.Thread(target=random_io)
696+
new_thread.daemon = True
697+
new_thread.start()
698+
count += 1
699+
while len(thread_has_run) < count:
700+
time.sleep(0.001)
701+
# Trigger process shutdown
702+
sys.exit(0)
703+
704+
main()
705+
"""
706+
rc, out, err = assert_python_ok('-c', script)
707+
self.assertFalse(err)
708+
666709

667710
class ThreadingExceptionTests(BaseTestCase):
668711
# A RuntimeError should be raised if Thread.start() is called

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ What's New in Python 3.3 Alpha 1?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #1856: Avoid crashes and lockups when daemon threads run while the
14+
interpreter is shutting down; instead, these threads are now killed when
15+
they try to take the GIL.
16+
1317
- Issue #11849: Make it more likely for the system allocator to release
1418
free()d memory arenas on glibc-based systems. Patch by Charles-François
1519
Natali.

Python/ceval.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,12 @@ PyEval_RestoreThread(PyThreadState *tstate)
440440
if (gil_created()) {
441441
int err = errno;
442442
take_gil(tstate);
443+
/* _Py_Finalizing is protected by the GIL */
444+
if (_Py_Finalizing && tstate != _Py_Finalizing) {
445+
drop_gil(tstate);
446+
PyThread_exit_thread();
447+
assert(0); /* unreachable */
448+
}
443449
errno = err;
444450
}
445451
#endif

Python/pythonrun.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
9393
int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
9494
int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
9595

96+
PyThreadState *_Py_Finalizing = NULL;
97+
9698
/* PyModule_GetWarningsModule is no longer necessary as of 2.6
9799
since _warnings is builtin. This API should not be used. */
98100
PyObject *
@@ -191,6 +193,7 @@ Py_InitializeEx(int install_sigs)
191193
if (initialized)
192194
return;
193195
initialized = 1;
196+
_Py_Finalizing = NULL;
194197

195198
#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
196199
/* Set up the LC_CTYPE locale, so we can obtain
@@ -395,15 +398,19 @@ Py_Finalize(void)
395398
* the threads created via Threading.
396399
*/
397400
call_py_exitfuncs();
398-
initialized = 0;
399-
400-
/* Flush stdout+stderr */
401-
flush_std_files();
402401

403402
/* Get current thread state and interpreter pointer */
404403
tstate = PyThreadState_GET();
405404
interp = tstate->interp;
406405

406+
/* Remaining threads (e.g. daemon threads) will automatically exit
407+
after taking the GIL (in PyEval_RestoreThread()). */
408+
_Py_Finalizing = tstate;
409+
initialized = 0;
410+
411+
/* Flush stdout+stderr */
412+
flush_std_files();
413+
407414
/* Disable signal handling */
408415
PyOS_FiniInterrupts();
409416

Python/thread_pthread.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,9 @@ void
244244
PyThread_exit_thread(void)
245245
{
246246
dprintf(("PyThread_exit_thread called\n"));
247-
if (!initialized) {
247+
if (!initialized)
248248
exit(0);
249-
}
249+
pthread_exit(0);
250250
}
251251

252252
#ifdef USE_SEMAPHORES

0 commit comments

Comments
 (0)