Skip to content

Commit 7cb3a44

Browse files
[3.9] GH-102126: fix deadlock at shutdown when clearing thread states (GH-102222) (#102236)
(cherry picked from commit 5f11478)
1 parent b5a9430 commit 7cb3a44

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
@@ -288,11 +288,19 @@ PyInterpreterState_Clear(PyInterpreterState *interp)
288288
_PyErr_Clear(tstate);
289289
}
290290

291+
// Clear the current/main thread state last.
291292
HEAD_LOCK(runtime);
292-
for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
293+
PyThreadState *p = interp->tstate_head;
294+
HEAD_UNLOCK(runtime);
295+
while (p != NULL) {
296+
// See https://github.com/python/cpython/issues/102126
297+
// Must be called without HEAD_LOCK held as it can deadlock
298+
// if any finalizer tries to acquire that lock.
293299
PyThreadState_Clear(p);
300+
HEAD_LOCK(runtime);
301+
p = p->next;
302+
HEAD_UNLOCK(runtime);
294303
}
295-
HEAD_UNLOCK(runtime);
296304

297305
Py_CLEAR(interp->audit_hooks);
298306

0 commit comments

Comments
 (0)