Issue #10517: After fork(), reinitialize the TLS used by the PyGILState_*
APIs, to avoid a crash with the pthread implementation in RHEL 5.  Patch
by Charles-François Natali.
diff --git a/Include/pystate.h b/Include/pystate.h
index b9fe61e..729342c 100644
--- a/Include/pystate.h
+++ b/Include/pystate.h
@@ -111,6 +111,7 @@
 PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *);
 #ifdef WITH_THREAD
 PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
+PyAPI_FUNC(void) _PyGILState_Reinit(void);
 #endif
 
 PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void);
diff --git a/Misc/NEWS b/Misc/NEWS
index 4c57348..3850505 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -61,6 +61,10 @@
 Library
 -------
 
+- Issue #10517: After fork(), reinitialize the TLS used by the PyGILState_*
+  APIs, to avoid a crash with the pthread implementation in RHEL 5.  Patch
+  by Charles-François Natali.
+
 - Issue #11763: don't use difflib in TestCase.assertMultiLineEqual if the
   strings are too long.
 
diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c
index f306bba..6f021e7 100644
--- a/Modules/signalmodule.c
+++ b/Modules/signalmodule.c
@@ -976,6 +976,7 @@
 PyOS_AfterFork(void)
 {
 #ifdef WITH_THREAD
+    _PyGILState_Reinit();
     PyEval_ReInitThreads();
     main_thread = PyThread_get_thread_ident();
     main_pid = getpid();
diff --git a/Python/pystate.c b/Python/pystate.c
index ddb7d42..3eefa36 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -537,6 +537,23 @@
     autoInterpreterState = NULL;
 }
 
+/* Reset the TLS key - called by PyOS_AfterFork.
+ * This should not be necessary, but some - buggy - pthread implementations
+ * don't flush TLS on fork, see issue #10517.
+ */
+void
+_PyGILState_Reinit(void)
+{
+    PyThreadState *tstate = PyGILState_GetThisThreadState();
+    PyThread_delete_key(autoTLSkey);
+    if ((autoTLSkey = PyThread_create_key()) == -1)
+        Py_FatalError("Could not allocate TLS entry");
+
+    /* re-associate the current thread state with the new key */
+    if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
+        Py_FatalError("Couldn't create autoTLSkey mapping");
+}
+
 /* When a thread state is created for a thread by some mechanism other than
    PyGILState_Ensure, it's important that the GILState machinery knows about
    it so it doesn't try to create another thread state for the thread (this is