Skip to content

Commit 3104796

Browse files
Make sure the GIL is held by the current thread in _PyEval_InitGIL().
1 parent 3cc9dc3 commit 3104796

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

Python/ceval_gil.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,15 @@ PyEval_ThreadsInitialized(void)
499499
return _PyEval_ThreadsInitialized();
500500
}
501501

502+
static inline int
503+
current_thread_holds_gil(struct _gil_runtime_state *gil, PyThreadState *tstate)
504+
{
505+
if (((PyThreadState*)_Py_atomic_load_relaxed(&gil->last_holder)) != tstate) {
506+
return 0;
507+
}
508+
return _Py_atomic_load_relaxed(&gil->locked);
509+
}
510+
502511
static void
503512
init_shared_gil(PyInterpreterState *interp, struct _gil_runtime_state *gil)
504513
{
@@ -525,8 +534,9 @@ _PyEval_InitGIL(PyThreadState *tstate, int own_gil)
525534
if (!own_gil) {
526535
PyInterpreterState *main_interp = _PyInterpreterState_Main();
527536
assert(tstate->interp != main_interp);
528-
init_shared_gil(tstate->interp, main_interp->ceval.gil);
529-
locked = _Py_atomic_load_relaxed(&main_interp->ceval.gil->locked);
537+
struct _gil_runtime_state *gil = main_interp->ceval.gil;
538+
init_shared_gil(tstate->interp, gil);
539+
locked = current_thread_holds_gil(gil, tstate);
530540
}
531541
/* XXX per-interpreter GIL */
532542
else if (!_Py_IsMainInterpreter(tstate->interp)) {
@@ -537,7 +547,7 @@ _PyEval_InitGIL(PyThreadState *tstate, int own_gil)
537547
init_shared_gil(tstate->interp, main_gil);
538548
// XXX For now we lie.
539549
tstate->interp->ceval.own_gil = 1;
540-
locked = _Py_atomic_load_relaxed(&main_gil->locked);
550+
locked = current_thread_holds_gil(main_gil, tstate);
541551
}
542552
else {
543553
PyThread_init_thread();

0 commit comments

Comments
 (0)