diff options
author | Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com> | 2023-02-25 06:51:36 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-02-25 06:51:36 (GMT) |
commit | 5f11478ce7fda826d399530af4c5ca96c592f144 (patch) | |
tree | ea2d7b42a7a95a8b7734ccc2a7e8db5bfabe7dc5 | |
parent | 56e93c8020e89e1712aa238574bca2076a225028 (diff) | |
download | cpython-5f11478ce7fda826d399530af4c5ca96c592f144.zip cpython-5f11478ce7fda826d399530af4c5ca96c592f144.tar.gz cpython-5f11478ce7fda826d399530af4c5ca96c592f144.tar.bz2 |
GH-102126: fix deadlock at shutdown when clearing thread states (#102222)
-rw-r--r-- | Misc/NEWS.d/next/Core and Builtins/2023-02-24-17-59-39.gh-issue-102126.HTT8Vc.rst | 1 | ||||
-rw-r--r-- | Python/pystate.c | 13 |
2 files changed, 11 insertions, 3 deletions
diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-02-24-17-59-39.gh-issue-102126.HTT8Vc.rst b/Misc/NEWS.d/next/Core and Builtins/2023-02-24-17-59-39.gh-issue-102126.HTT8Vc.rst new file mode 100644 index 0000000..68c4368 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-02-24-17-59-39.gh-issue-102126.HTT8Vc.rst @@ -0,0 +1 @@ +Fix deadlock at shutdown when clearing thread states if any finalizer tries to acquire the runtime head lock. Patch by Kumar Aditya. diff --git a/Python/pystate.c b/Python/pystate.c index 32b17fd..3c655bf 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -754,12 +754,19 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate) _PyErr_Clear(tstate); } + // Clear the current/main thread state last. HEAD_LOCK(runtime); - // XXX Clear the current/main thread state last. - for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) { + PyThreadState *p = interp->threads.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); /* It is possible that any of the objects below have a finalizer that runs Python code or otherwise relies on a thread state |