[Python-checkins] cpython (2.7): Issue #13817: After fork(), reinit the ad-hoc TLS implementation earlier to fix

charles-francois.natali python-checkins at python.org
Thu Feb 2 20:39:17 CET 2012


http://hg.python.org/cpython/rev/c3649173d093
changeset:   74729:c3649173d093
branch:      2.7
parent:      74724:0b8917fc6db5
user:        Charles-François Natali <neologix at free.fr>
date:        Thu Feb 02 19:57:19 2012 +0100
summary:
  Issue #13817: After fork(), reinit the ad-hoc TLS implementation earlier to fix
a random deadlock when fork() is called in a multithreaded process in debug
mode, and make PyOS_AfterFork() more robust.

files:
  Lib/test/test_threading.py |  23 +++++++++++++++++++++++
  Modules/signalmodule.c     |   4 +++-
  2 files changed, 26 insertions(+), 1 deletions(-)


diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -635,6 +635,29 @@
         output = "end of worker thread\nend of main thread\n"
         self.assertScriptHasOutput(script, output)
 
+    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+    def test_reinit_tls_after_fork(self):
+        # Issue #13817: fork() would deadlock in a multithreaded program with
+        # the ad-hoc TLS implementation.
+
+        def do_fork_and_wait():
+            # just fork a child process and wait it
+            pid = os.fork()
+            if pid > 0:
+                os.waitpid(pid, 0)
+            else:
+                os._exit(0)
+
+        # start a bunch of threads that will fork() child processes
+        threads = []
+        for i in range(16):
+            t = threading.Thread(target=do_fork_and_wait)
+            threads.append(t)
+            t.start()
+
+        for t in threads:
+            t.join()
+
 
 class ThreadingExceptionTests(BaseTestCase):
     # A RuntimeError should be raised if Thread.start() is called
diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c
--- a/Modules/signalmodule.c
+++ b/Modules/signalmodule.c
@@ -976,10 +976,12 @@
 PyOS_AfterFork(void)
 {
 #ifdef WITH_THREAD
+    /* PyThread_ReInitTLS() must be called early, to make sure that the TLS API
+     * can be called safely. */
+    PyThread_ReInitTLS();
     PyEval_ReInitThreads();
     main_thread = PyThread_get_thread_ident();
     main_pid = getpid();
     _PyImport_ReInitLock();
-    PyThread_ReInitTLS();
 #endif
 }

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list