]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.10] GH-102126: fix deadlock at shutdown when clearing thread state… (#102235)
authorKumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
Fri, 3 Mar 2023 13:14:30 +0000 (18:44 +0530)
committerGitHub <noreply@github.com>
Fri, 3 Mar 2023 13:14:30 +0000 (18:44 +0530)
[3.10] GH-102126: fix deadlock at shutdown when clearing thread states (GH-102222).
(cherry picked from commit 5f11478ce7fda826d399530af4c5ca96c592f144)

Misc/NEWS.d/next/Core and Builtins/2023-02-24-17-59-39.gh-issue-102126.HTT8Vc.rst [new file with mode: 0644]
Python/pystate.c

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 (file)
index 0000000..68c4368
--- /dev/null
@@ -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.
index df98eb11bb0a49d72ecbae7b3fd6e2e2b2c429e0..c7a6af5da893d525e968adae1a7efbe1463304ac 100644 (file)
@@ -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);