@@ -815,9 +815,14 @@ common_constants_clear(PyInterpreterState *interp)
815815static void
816816move_asyncio_tasks_to_interpreter (PyThreadState * tstate )
817817{
818+ _PyThreadStateImpl * tstate_impl = (_PyThreadStateImpl * )tstate ;
819+ if (llist_empty (& tstate_impl -> asyncio_tasks_head )) {
820+ return ;
821+ }
822+
818823 PyMutex_Lock (& tstate -> interp -> asyncio_tasks_lock );
819824 llist_concat (& tstate -> interp -> asyncio_tasks_head ,
820- & (( _PyThreadStateImpl * ) tstate ) -> asyncio_tasks_head );
825+ & tstate_impl -> asyncio_tasks_head );
821826 PyMutex_Unlock (& tstate -> interp -> asyncio_tasks_lock );
822827}
823828
@@ -961,12 +966,11 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
961966#endif
962967
963968 if (tstate -> interp == interp ) {
969+ // gh-159041: Finalizers above may have registered new asyncio tasks.
970+ move_asyncio_tasks_to_interpreter (tstate );
971+
964972 /* We are now safe to fix tstate->_status.cleared. */
965973 // XXX Do this (much) earlier?
966- // Finalizers above may have registered new asyncio tasks.
967- move_asyncio_tasks_to_interpreter (tstate );
968- assert (llist_empty (
969- & ((_PyThreadStateImpl * )tstate )-> asyncio_tasks_head ));
970974 tstate -> _status .cleared = 1 ;
971975 }
972976
@@ -1936,6 +1940,8 @@ static void
19361940tstate_delete_common (PyThreadState * tstate , int release_gil )
19371941{
19381942 assert (tstate -> _status .cleared && !tstate -> _status .finalized );
1943+ assert (llist_empty (
1944+ & ((_PyThreadStateImpl * )tstate )-> asyncio_tasks_head ));
19391945 tstate_verify_not_active (tstate );
19401946 assert (!_PyThreadState_IsRunningMain (tstate ));
19411947
0 commit comments