Skip to content

Commit 5b62ca6

Browse files
kumaraditya303mgorny
authored andcommitted
[3.10] pythonGH-102126: fix deadlock at shutdown when clearing thread state… (python#102235)
[3.10] pythonGH-102126: fix deadlock at shutdown when clearing thread states (pythonGH-102222). (cherry picked from commit 5f11478)
1 parent 64a1112 commit 5b62ca6

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix deadlock at shutdown when clearing thread states if any finalizer tries to acquire the runtime head lock. Patch by Kumar Aditya.

Python/pystate.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,11 +258,19 @@ _PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
258258
PyErr_Clear();
259259
}
260260

261+
// Clear the current/main thread state last.
261262
HEAD_LOCK(runtime);
262-
for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
263+
PyThreadState *p = interp->tstate_head;
264+
HEAD_UNLOCK(runtime);
265+
while (p != NULL) {
266+
// See https://github.com/python/cpython/issues/102126
267+
// Must be called without HEAD_LOCK held as it can deadlock
268+
// if any finalizer tries to acquire that lock.
263269
PyThreadState_Clear(p);
270+
HEAD_LOCK(runtime);
271+
p = p->next;
272+
HEAD_UNLOCK(runtime);
264273
}
265-
HEAD_UNLOCK(runtime);
266274

267275
Py_CLEAR(interp->audit_hooks);
268276

0 commit comments

Comments
 (0)