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

Skip to content

Commit 6d0d24e

Browse files
author
Charles-François Natali
committed
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.
1 parent 03c29f9 commit 6d0d24e

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

Lib/test/test_threading.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,29 @@ def main():
666666
rc, out, err = assert_python_ok('-c', script)
667667
self.assertFalse(err)
668668

669+
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
670+
def test_reinit_tls_after_fork(self):
671+
# Issue #13817: fork() would deadlock in a multithreaded program with
672+
# the ad-hoc TLS implementation.
673+
674+
def do_fork_and_wait():
675+
# just fork a child process and wait it
676+
pid = os.fork()
677+
if pid > 0:
678+
os.waitpid(pid, 0)
679+
else:
680+
os._exit(0)
681+
682+
# start a bunch of threads that will fork() child processes
683+
threads = []
684+
for i in range(16):
685+
t = threading.Thread(target=do_fork_and_wait)
686+
threads.append(t)
687+
t.start()
688+
689+
for t in threads:
690+
t.join()
691+
669692

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

Modules/signalmodule.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -991,11 +991,13 @@ void
991991
PyOS_AfterFork(void)
992992
{
993993
#ifdef WITH_THREAD
994+
/* PyThread_ReInitTLS() must be called early, to make sure that the TLS API
995+
* can be called safely. */
996+
PyThread_ReInitTLS();
994997
_PyGILState_Reinit();
995998
PyEval_ReInitThreads();
996999
main_thread = PyThread_get_thread_ident();
9971000
main_pid = getpid();
9981001
_PyImport_ReInitLock();
999-
PyThread_ReInitTLS();
10001002
#endif
10011003
}

0 commit comments

Comments
 (0)