Skip to content

Commit a19bbd4

Browse files
Exit threads when interpreter is finalizing rather than runtime.
1 parent 2950073 commit a19bbd4

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

Python/ceval.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,11 @@ _PyEval_FiniThreads(void)
207207
static inline void
208208
exit_thread_if_finalizing(PyThreadState *tstate)
209209
{
210+
/* Get interpreter pointer */
211+
PyInterpreterState *interp = tstate->interp;
212+
210213
/* _Py_Finalizing is protected by the GIL */
211-
if (_Py_IsFinalizing() && !_Py_CURRENTLY_FINALIZING(tstate)) {
214+
if (interp->finalizing && !_Py_CURRENTLY_FINALIZING(tstate)) {
212215
drop_gil(tstate);
213216
PyThread_exit_thread();
214217
}

Python/pylifecycle.c

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1131,16 +1131,18 @@ Py_FinalizeEx(void)
11311131
return status;
11321132
}
11331133

1134+
/* Get current thread state and interpreter pointer */
1135+
PyThreadState *tstate = _PyThreadState_GET();
1136+
PyInterpreterState *interp = tstate->interp;
1137+
11341138
// Wrap up existing "threading"-module-created, non-daemon threads.
11351139
wait_for_thread_shutdown();
1140+
interp->finalizing = 1;
1141+
11361142

11371143
// Make any remaining pending calls.
11381144
_Py_FinishPendingCalls();
11391145

1140-
/* Get current thread state and interpreter pointer */
1141-
PyThreadState *tstate = _PyThreadState_GET();
1142-
PyInterpreterState *interp = tstate->interp;
1143-
11441146
/* The interpreter is still entirely intact at this point, and the
11451147
* exit funcs may be relying on that. In particular, if some thread
11461148
* or exit func is still waiting to do an import, the import machinery
@@ -1546,10 +1548,10 @@ Py_EndInterpreter(PyThreadState *tstate)
15461548
Py_FatalError("Py_EndInterpreter: thread is not current");
15471549
if (tstate->frame != NULL)
15481550
Py_FatalError("Py_EndInterpreter: thread still has a frame");
1549-
interp->finalizing = 1;
15501551

15511552
// Wrap up existing "threading"-module-created, non-daemon threads.
15521553
wait_for_thread_shutdown();
1554+
interp->finalizing = 1;
15531555

15541556
call_py_exitfuncs(interp);
15551557

0 commit comments

Comments
 (0)