gh-116522: Refactor `_PyThreadState_DeleteExcept` by colesbury · Pull Request #117131 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Include/internal/pycore_pystate.h
8 changes: 8 additions & 0 deletions Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,14 @@ PyOS_AfterFork_Child(void)
goto fatal_error;
}

// Remove the dead thread states. We "start the world" once we are the only
// thread state left to undo the stop the world call in `PyOS_BeforeFork`.
// That needs to happen before `_PyThreadState_DeleteList`, because that
// may call destructors.
PyThreadState *list = _PyThreadState_RemoveExcept(tstate);
_PyEval_StartTheWorldAll(&_PyRuntime);
_PyThreadState_DeleteList(list);

status = _PyImport_ReInitLock(tstate->interp);
if (_PyStatus_EXCEPTION(status)) {
goto fatal_error;
Expand Down
7 changes: 2 additions & 5 deletions Python/ceval_gil.c
Original file line number Diff line number Diff line change
Expand Up @@ -579,9 +579,8 @@ PyEval_ReleaseThread(PyThreadState *tstate)
}

#ifdef HAVE_FORK
/* This function is called from PyOS_AfterFork_Child to destroy all threads
which are not running in the child process, and clear internal locks
which might be held by those threads. */
/* This function is called from PyOS_AfterFork_Child to re-initialize the
GIL and pending calls lock. */
PyStatus
_PyEval_ReInitThreads(PyThreadState *tstate)
{
Expand All @@ -598,8 +597,6 @@ _PyEval_ReInitThreads(PyThreadState *tstate)
struct _pending_calls *pending = &tstate->interp->ceval.pending;
_PyMutex_at_fork_reinit(&pending->mutex);

/* Destroy all threads except the current one */
_PyThreadState_DeleteExcept(tstate);
return _PyStatus_OK();
}
#endif
Expand Down
7 changes: 5 additions & 2 deletions Python/pylifecycle.c
Original file line number Diff line number Diff line change
Expand Up @@ -1930,8 +1930,11 @@ Py_FinalizeEx(void)
will be called in the current Python thread. Since
_PyRuntimeState_SetFinalizing() has been called, no other Python thread
can take the GIL at this point: if they try, they will exit
immediately. */
_PyThreadState_DeleteExcept(tstate);
immediately. We start the world once we are the only thread state left,
before we call destructors. */
PyThreadState *list = _PyThreadState_RemoveExcept(tstate);
_PyEval_StartTheWorldAll(runtime);
_PyThreadState_DeleteList(list);

/* At this point no Python code should be running at all.
The only thread state left should be the main thread of the main
Expand Down
39 changes: 24 additions & 15 deletions Python/pystate.c