aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKumar Aditya <59607654+kumaraditya303@users.noreply.github.com>2023-03-03 18:44:30 +0530
committerMichał Górny <mgorny@gentoo.org>2024-09-07 08:35:32 +0200
commit5b62ca635937889cd65e1b1f3efcc475a9c0ff4f (patch)
tree19433f155ea826a3cd4275bfa39b6fe1cd68c0ec
parentgh-99418: Make urllib.parse.urlparse enforce that a scheme must begin with an... (diff)
downloadcpython-5b62ca635937889cd65e1b1f3efcc475a9c0ff4f.tar.gz
cpython-5b62ca635937889cd65e1b1f3efcc475a9c0ff4f.tar.bz2
cpython-5b62ca635937889cd65e1b1f3efcc475a9c0ff4f.zip
[3.10] GH-102126: fix deadlock at shutdown when clearing thread state… (#102235)
[3.10] GH-102126: fix deadlock at shutdown when clearing thread states (GH-102222). (cherry picked from commit 5f11478ce7fda826d399530af4c5ca96c592f144)
-rw-r--r--Misc/NEWS.d/next/Core and Builtins/2023-02-24-17-59-39.gh-issue-102126.HTT8Vc.rst1
-rw-r--r--Python/pystate.c12
2 files changed, 11 insertions, 2 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 00000000000..68c43688c3d
--- /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 56c184e43ae..300b4005f01 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -258,11 +258,19 @@ _PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
PyErr_Clear();
}
+ // 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);