Skip to content

Commit b833fd6

Browse files
address review: fix deadlock between HEAD_LOCK and brc bucket mutex
bind_tstate() held HEAD_LOCK while _Py_brc_init_thread() acquired a biased reference counting bucket mutex. That mutex can be handed off to a thread which is then suspended by a stop-the-world pause before it re-attaches, while stopping and starting the world need HEAD_LOCK. Initialize the brc state after the thread state is published and HEAD_LOCK is released.
1 parent 0516a31 commit b833fd6

2 files changed

Lines changed: 12 additions & 9 deletions

File tree

‎Python/brc.c‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,9 @@ _Py_brc_remove_thread(PyThreadState *tstate)
197197
{
198198
struct _brc_thread_state *brc = &((_PyThreadStateImpl *)tstate)->brc;
199199
if (brc->tid == 0) {
200-
// The thread state may have been created, but never bound to a native
201-
// thread and therefore never added to the hashtable.
202-
assert(tstate->_status.bound == 0);
200+
// The thread state was never added to the hashtable: either it was
201+
// never bound to a native thread, or it is deleted on behalf of a
202+
// thread that was still binding it (e.g. in the child after fork).
203203
return;
204204
}
205205

‎Python/pystate.c‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,12 +198,6 @@ bind_tstate(PyThreadState *tstate)
198198
tstate->native_thread_id = PyThread_get_thread_native_id();
199199
#endif
200200

201-
#ifdef Py_GIL_DISABLED
202-
// Initialize biased reference counting inter-thread queue. Note that this
203-
// needs to be initialized from the active thread.
204-
_Py_brc_init_thread(tstate);
205-
#endif
206-
207201
// mimalloc state needs to be initialized from the active thread.
208202
tstate_mimalloc_bind(tstate);
209203

@@ -220,6 +214,15 @@ bind_tstate(PyThreadState *tstate)
220214
unlink_threadstate(&interp->threads.pending, tstate);
221215
add_threadstate(interp, tstate, interp->threads.head);
222216
HEAD_UNLOCK(&_PyRuntime);
217+
218+
#ifdef Py_GIL_DISABLED
219+
// Initialize biased reference counting inter-thread queue. Note that this
220+
// needs to be initialized from the active thread. HEAD_LOCK must not be
221+
// held here: the bucket mutex can be handed off to a thread that is
222+
// suspended by a stop-the-world pause before it re-attaches, and
223+
// stopping or starting the world requires HEAD_LOCK.
224+
_Py_brc_init_thread(tstate);
225+
#endif
223226
return 1;
224227
}
225228

0 commit comments

Comments
 (0)