From 6c2e052ee07f10a6336bb4de1cef71dbe7d30ee6 Mon Sep 17 00:00:00 2001 From: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com> Date: Fri, 3 Mar 2023 18:44:30 +0530 Subject: =?UTF-8?q?[3.10]=20GH-102126:=20fix=20deadlock=20at=20shutdown=20?= =?UTF-8?q?when=20clearing=20thread=20state=E2=80=A6=20(#102235)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [3.10] GH-102126: fix deadlock at shutdown when clearing thread states (GH-102222). (cherry picked from commit 5f11478ce7fda826d399530af4c5ca96c592f144) --- Python/pystate.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'Python/pystate.c') diff --git a/Python/pystate.c b/Python/pystate.c index df98eb11bb..c7a6af5da8 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -293,11 +293,19 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate) _PyErr_Clear(tstate); } + // Clear the current/main thread state last. HEAD_LOCK(runtime); - for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) { + PyThreadState *p = interp->tstate_head; + HEAD_UNLOCK(runtime); + while (p != NULL) { + // See https://github.com/python/cpython/issues/102126 + // Must be called without HEAD_LOCK held as it can deadlock + // if any finalizer tries to acquire that lock. PyThreadState_Clear(p); + HEAD_LOCK(runtime); + p = p->next; + HEAD_UNLOCK(runtime); } - HEAD_UNLOCK(runtime); Py_CLEAR(interp->audit_hooks); -- cgit v1.2.1