@@ -1966,8 +1966,14 @@ resolve_final_tstate(_PyRuntimeState *runtime, struct pyfinalize_args *args)
1966
1966
/* Then we decide the thread state we should use for finalization. */
1967
1967
1968
1968
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 ) {
1971
1977
/* This implies that Py_Finalize() was called while
1972
1978
a non-main interpreter was active or while the main
1973
1979
tstate was temporarily swapped out with another.
@@ -1982,18 +1988,22 @@ resolve_final_tstate(_PyRuntimeState *runtime, struct pyfinalize_args *args)
1982
1988
over to the main thread. At the least, however, we can make
1983
1989
sure the main interpreter is active. */
1984
1990
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 );
1994
2005
}
1995
2006
}
1996
- assert (final_tstate != NULL );
1997
2007
1998
2008
/* We might want to warn if final_tstate->current_frame != NULL. */
1999
2009
0 commit comments