diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-08-19-06-51-17.gh-issue-96071.mVgPAo.rst b/Misc/NEWS.d/next/Core and Builtins/2022-08-19-06-51-17.gh-issue-96071.mVgPAo.rst new file mode 100644 index 00000000000000..37653ffac12418 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2022-08-19-06-51-17.gh-issue-96071.mVgPAo.rst @@ -0,0 +1 @@ +Fix a deadlock in :c:func:`PyGILState_Ensure` when allocating new thread state. Patch by Kumar Aditya. diff --git a/Python/pystate.c b/Python/pystate.c index 642d680ba20b1f..4ada6054109fec 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -829,11 +829,16 @@ new_threadstate(PyInterpreterState *interp) // Every valid interpreter must have at least one thread. assert(id > 1); assert(old_head->prev == NULL); - + // Unlock before allocating memory. + HEAD_UNLOCK(runtime); tstate = alloc_threadstate(); + HEAD_LOCK(runtime); if (tstate == NULL) { goto error; } + // Read interp->threads.head again as another thread could + // have created a thread state while we were allocating memory. + old_head = interp->threads.head; // Set to _PyThreadState_INIT. memcpy(tstate, &initial._main_interpreter._initial_thread,