Skip to content

Commit fe12f40

Browse files
More tweaking resolve_final_tstate().
1 parent d78f655 commit fe12f40

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

Python/pylifecycle.c

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1966,8 +1966,14 @@ resolve_final_tstate(_PyRuntimeState *runtime, struct pyfinalize_args *args)
19661966
/* Then we decide the thread state we should use for finalization. */
19671967

19681968
PyThreadState *final_tstate = tstate;
1969-
if (_Py_IsMainThread() && main_tstate != NULL) {
1970-
if (tstate != main_tstate) {
1969+
if (_Py_IsMainThread()) {
1970+
if (main_tstate == NULL) {
1971+
if (tstate->interp != main_interp) {
1972+
/* We will swap in a tstate for the main interpreter. */
1973+
final_tstate = NULL;
1974+
}
1975+
}
1976+
else if (tstate != main_tstate) {
19711977
/* This implies that Py_Finalize() was called while
19721978
a non-main interpreter was active or while the main
19731979
tstate was temporarily swapped out with another.
@@ -1982,18 +1988,22 @@ resolve_final_tstate(_PyRuntimeState *runtime, struct pyfinalize_args *args)
19821988
over to the main thread. At the least, however, we can make
19831989
sure the main interpreter is active. */
19841990
if (tstate->interp != main_interp) {
1985-
/* We don't go to the trouble of updating runtime->main_tstate
1986-
since it will be dead soon anyway. */
1987-
final_tstate =
1988-
_PyThreadState_New(main_interp, _PyThreadState_WHENCE_FINI);
1989-
if (final_tstate != NULL) {
1990-
_PyThreadState_Bind(final_tstate);
1991-
}
1992-
/* Otherwise we fall back to the current tstate.
1993-
It's better than nothing. */
1991+
final_tstate = NULL;
1992+
}
1993+
}
1994+
if (final_tstate == NULL) {
1995+
/* We don't go to the trouble of updating runtime->main_tstate
1996+
since it will be dead soon anyway. */
1997+
final_tstate =
1998+
_PyThreadState_New(main_interp, _PyThreadState_WHENCE_FINI);
1999+
if (final_tstate == NULL) {
2000+
/* Fall back to the current tstate. It's better than nothing. */
2001+
final_tstate = tstate;
2002+
}
2003+
else {
2004+
_PyThreadState_Bind(final_tstate);
19942005
}
19952006
}
1996-
assert(final_tstate != NULL);
19972007

19982008
/* We might want to warn if final_tstate->current_frame != NULL. */
19992009

0 commit comments

Comments
 (0)