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

Skip to content

Commit c0bc4ef

Browse files
committed
avoid crashes and lockups from daemon threads during interpreter shutdown (python#1856)
1 parent 1a6561e commit c0bc4ef

6 files changed

Lines changed: 65 additions & 3 deletions

File tree

Include/pythonrun.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,8 @@ PyAPI_FUNC(void) PyFloat_Fini(void);
146146
PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
147147
PyAPI_FUNC(void) PyByteArray_Fini(void);
148148

149+
PyAPI_DATA(PyThreadState *) _Py_Finalizing;
150+
149151
/* Stuff with no proper home (yet) */
150152
PyAPI_FUNC(char *) PyOS_Readline(FILE *, FILE *, char *);
151153
PyAPI_DATA(int) (*PyOS_InputHook)(void);

Lib/test/test_threading.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,49 @@ def my_release_save():
700700
output = "end of worker thread\nend of main thread\n"
701701
self.assertScriptHasOutput(script, output)
702702

703+
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
704+
def test_6_daemon_threads(self):
705+
# Check that a daemon thread cannot crash the interpreter on shutdown
706+
# by manipulating internal structures that are being disposed of in
707+
# the main thread.
708+
script = """if True:
709+
import os
710+
import random
711+
import sys
712+
import time
713+
import threading
714+
715+
thread_has_run = set()
716+
717+
def random_io():
718+
'''Loop for a while sleeping random tiny amounts and doing some I/O.'''
719+
while True:
720+
in_f = open(os.__file__, 'rb')
721+
stuff = in_f.read(200)
722+
null_f = open(os.devnull, 'wb')
723+
null_f.write(stuff)
724+
time.sleep(random.random() / 1995)
725+
null_f.close()
726+
in_f.close()
727+
thread_has_run.add(threading.current_thread())
728+
729+
def main():
730+
count = 0
731+
for _ in range(40):
732+
new_thread = threading.Thread(target=random_io)
733+
new_thread.daemon = True
734+
new_thread.start()
735+
count += 1
736+
while len(thread_has_run) < count:
737+
time.sleep(0.001)
738+
# Trigger process shutdown
739+
sys.exit(0)
740+
741+
main()
742+
"""
743+
rc, out, err = assert_python_ok('-c', script)
744+
self.assertFalse(err)
745+
703746
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
704747
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
705748
def test_reinit_tls_after_fork(self):

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 2.7.8?
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 they
15+
try to take the GIL.
16+
1317
- Issue #19656: Running Python with the -3 option now also warns about
1418
non-ascii bytes literals.
1519

Python/ceval.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,12 @@ PyEval_RestoreThread(PyThreadState *tstate)
355355
if (interpreter_lock) {
356356
int err = errno;
357357
PyThread_acquire_lock(interpreter_lock, 1);
358+
/* _Py_Finalizing is protected by the GIL */
359+
if (_Py_Finalizing && tstate != _Py_Finalizing) {
360+
PyThread_release_lock(interpreter_lock);
361+
PyThread_exit_thread();
362+
assert(0); /* unreachable */
363+
}
358364
errno = err;
359365
}
360366
#endif

Python/pythonrun.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ int _Py_QnewFlag = 0;
9191
int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
9292
int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
9393

94+
PyThreadState *_Py_Finalizing = NULL;
95+
9496

9597
/* Hack to force loading of object files */
9698
int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
@@ -163,6 +165,7 @@ Py_InitializeEx(int install_sigs)
163165
if (initialized)
164166
return;
165167
initialized = 1;
168+
_Py_Finalizing = NULL;
166169

167170
if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
168171
Py_DebugFlag = add_flag(Py_DebugFlag, p);
@@ -422,12 +425,16 @@ Py_Finalize(void)
422425
* the threads created via Threading.
423426
*/
424427
call_sys_exitfunc();
425-
initialized = 0;
426428

427429
/* Get current thread state and interpreter pointer */
428430
tstate = PyThreadState_GET();
429431
interp = tstate->interp;
430432

433+
/* Remaining threads (e.g. daemon threads) will automatically exit
434+
after taking the GIL (in PyEval_RestoreThread()). */
435+
_Py_Finalizing = tstate;
436+
initialized = 0;
437+
431438
/* Disable signal handling */
432439
PyOS_FiniInterrupts();
433440

Python/thread_pthread.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,9 +242,9 @@ void
242242
PyThread_exit_thread(void)
243243
{
244244
dprintf(("PyThread_exit_thread called\n"));
245-
if (!initialized) {
245+
if (!initialized)
246246
exit(0);
247-
}
247+
pthread_exit(0);
248248
}
249249

250250
#ifdef USE_SEMAPHORES

0 commit comments

Comments
 (0)