diff --git a/Include/pythonrun.h b/Include/pythonrun.h
--- a/Include/pythonrun.h
+++ b/Include/pythonrun.h
@@ -211,6 +211,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(int) _Py_Finalizing;
#endif
/* Stuff with no proper home (yet) */
diff --git a/Python/ceval.c b/Python/ceval.c
--- a/Python/ceval.c
+++ b/Python/ceval.c
@@ -440,6 +440,13 @@ PyEval_RestoreThread(PyThreadState *tsta
if (gil_created()) {
int err = errno;
take_gil(tstate);
+ /* _Py_Finalizing is protected by the GIL */
+ assert(main_thread);
+ if (_Py_Finalizing && PyThread_get_thread_ident() != main_thread) {
+ drop_gil(tstate);
+ PyThread_exit_thread();
+ assert(0); /* should never be reached */
+ }
errno = err;
}
#endif
diff --git a/Python/pythonrun.c b/Python/pythonrun.c
--- a/Python/pythonrun.c
+++ b/Python/pythonrun.c
@@ -93,6 +93,8 @@ int Py_IgnoreEnvironmentFlag; /* e.g. PY
int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
+int _Py_Finalizing = 0;
+
/* PyModule_GetWarningsModule is no longer necessary as of 2.6
since _warnings is builtin. This API should not be used. */
PyObject *
@@ -191,6 +193,7 @@ Py_InitializeEx(int install_sigs)
if (initialized)
return;
initialized = 1;
+ _Py_Finalizing = 0;
#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
/* Set up the LC_CTYPE locale, so we can obtain
@@ -395,6 +398,10 @@ Py_Finalize(void)
* the threads created via Threading.
*/
call_py_exitfuncs();
+
+ /* Now all non-main threads will automatically exit when trying to take
+ the GIL. */
+ _Py_Finalizing = 1;
initialized = 0;
/* Flush stdout+stderr */
diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h
--- a/Python/thread_pthread.h
+++ b/Python/thread_pthread.h
@@ -244,9 +244,9 @@ void
PyThread_exit_thread(void)
{
dprintf(("PyThread_exit_thread called\n"));
- if (!initialized) {
+ if (!initialized)
exit(0);
- }
+ pthread_exit(0);
}
#ifdef USE_SEMAPHORES