Issue #1856: Avoid crashes and lockups when daemon threads run while the
authorAntoine Pitrou <solipsis@pitrou.net>
Wed, 4 May 2011 18:02:30 +0000 (20:02 +0200)
committerAntoine Pitrou <solipsis@pitrou.net>
Wed, 4 May 2011 18:02:30 +0000 (20:02 +0200)
interpreter is shutting down; instead, these threads are now killed when
they try to take the GIL.

Include/pythonrun.h
Lib/test/test_threading.py
Misc/NEWS
Python/ceval.c
Python/pythonrun.c
Python/thread_pthread.h

index bbcae73d2182574a557ad2e77a5da48dfa9f82ad..00b4972c8c1d3550c4750bfdd8f25895c9602945 100644 (file)
@@ -214,6 +214,8 @@ PyAPI_FUNC(void) PyByteArray_Fini(void);
 PyAPI_FUNC(void) PyFloat_Fini(void);
 PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
 PyAPI_FUNC(void) _PyGC_Fini(void);
+
+PyAPI_DATA(PyThreadState *) _Py_Finalizing;
 #endif
 
 /* Stuff with no proper home (yet) */
index 5f99b2ea9f5917ddbc2ece5a5bcf0674760bf572..1c946dab127f276855c85a685264e773c0fe4d18 100644 (file)
@@ -12,6 +12,7 @@ import unittest
 import weakref
 import os
 import subprocess
+from test.script_helper import assert_python_ok
 
 from test import lock_tests
 
@@ -463,7 +464,6 @@ class ThreadJoinOnShutdown(BaseTestCase):
             """
         self._run_and_join(script)
 
-
     @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
     def test_2_join_in_forked_process(self):
         # Like the test above, but from a forked interpreter
@@ -655,6 +655,49 @@ class ThreadJoinOnShutdown(BaseTestCase):
         output = "end of worker thread\nend of main thread\n"
         self.assertScriptHasOutput(script, output)
 
+    def test_6_daemon_threads(self):
+        # Check that a daemon thread cannot crash the interpreter on shutdown
+        # by manipulating internal structures that are being disposed of in
+        # the main thread.
+        script = """if True:
+            import os
+            import random
+            import sys
+            import time
+            import threading
+
+            thread_has_run = set()
+
+            def random_io():
+                '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
+                blank = b'x' * 200
+                while True:
+                    in_f = open(os.__file__, 'r')
+                    stuff = in_f.read(200)
+                    null_f = open(os.devnull, 'w')
+                    null_f.write(stuff)
+                    time.sleep(random.random() / 1995)
+                    null_f.close()
+                    in_f.close()
+                    thread_has_run.add(threading.current_thread())
+
+            def main():
+                count = 0
+                for _ in range(40):
+                    new_thread = threading.Thread(target=random_io)
+                    new_thread.daemon = True
+                    new_thread.start()
+                    count += 1
+                while len(thread_has_run) < count:
+                    time.sleep(0.001)
+                # Trigger process shutdown
+                sys.exit(0)
+
+            main()
+            """
+        rc, out, err = assert_python_ok('-c', script)
+        self.assertFalse(err)
+
 
 class ThreadingExceptionTests(BaseTestCase):
     # A RuntimeError should be raised if Thread.start() is called
index f77befd332e746584685b4a89ef3a2ac33171a5a..ca22acf2abd0a6cfefa7da54f3ef9a2e391d73c1 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,10 @@ What's New in Python 3.2.1?
 Core and Builtins
 -----------------
 
+- Issue #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.
+
 - Issue #9756: When calling a method descriptor or a slot wrapper descriptor,
   the check of the object type doesn't read the __class__ attribute anymore.
   Fix a crash if a class override its __class__ attribute (e.g. a proxy of the
index 43a5c904d1b8dacefe95015a15b294904b3009a6..705ed415a9ce36421ed9a77e4d732bd8a10d3d48 100644 (file)
@@ -440,6 +440,12 @@ PyEval_RestoreThread(PyThreadState *tstate)
     if (gil_created()) {
         int err = errno;
         take_gil(tstate);
+        /* _Py_Finalizing is protected by the GIL */
+        if (_Py_Finalizing && tstate != _Py_Finalizing) {
+            drop_gil(tstate);
+            PyThread_exit_thread();
+            assert(0);  /* unreachable */
+        }
         errno = err;
     }
 #endif
index faaf54a0a67626d0cdaa4ee7b9028c5fae74be3e..1e2dd586b471a231068acc7cbae21a634668e1a4 100644 (file)
@@ -90,6 +90,8 @@ int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
 int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
 int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
 
+PyThreadState *_Py_Finalizing = NULL;
+
 /* PyModule_GetWarningsModule is no longer necessary as of 2.6
 since _warnings is builtin.  This API should not be used. */
 PyObject *
@@ -188,6 +190,7 @@ Py_InitializeEx(int install_sigs)
     if (initialized)
         return;
     initialized = 1;
+    _Py_Finalizing = NULL;
 
 #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
     /* Set up the LC_CTYPE locale, so we can obtain
@@ -388,15 +391,19 @@ Py_Finalize(void)
      * the threads created via Threading.
      */
     call_py_exitfuncs();
-    initialized = 0;
-
-    /* Flush stdout+stderr */
-    flush_std_files();
 
     /* Get current thread state and interpreter pointer */
     tstate = PyThreadState_GET();
     interp = tstate->interp;
 
+    /* Remaining threads (e.g. daemon threads) will automatically exit
+       after taking the GIL (in PyEval_RestoreThread()). */
+    _Py_Finalizing = tstate;
+    initialized = 0;
+
+    /* Flush stdout+stderr */
+    flush_std_files();
+
     /* Disable signal handling */
     PyOS_FiniInterrupts();
 
index ffc791c578ec69575447b4509b4f91b725cd3572..6bc9d55781b3058501b6220a0b63c52430c04e9c 100644 (file)
@@ -250,9 +250,9 @@ void
 PyThread_exit_thread(void)
 {
     dprintf(("PyThread_exit_thread called\n"));
-    if (!initialized) {
+    if (!initialized)
         exit(0);
-    }
+    pthread_exit(0);
 }
 
 #ifdef USE_SEMAPHORES