diff --git a/Include/pystate.h b/Include/pystate.h --- a/Include/pystate.h +++ b/Include/pystate.h @@ -212,6 +212,11 @@ */ PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void); +/* Helper/diagnostic function - return 1 if the current thread + * currently holds the GIL, 0 otherwise + */ +PyAPI_FUNC(int) PyGILState_Check(void); + #endif /* #ifdef WITH_THREAD */ /* The implementation of sys._current_frames() Returns a dict mapping diff --git a/Python/pystate.c b/Python/pystate.c --- a/Python/pystate.c +++ b/Python/pystate.c @@ -697,6 +697,15 @@ return (PyThreadState *)PyThread_get_key_value(autoTLSkey); } +int +PyGILState_Check(void) +{ + /* can't use PyThreadState_Get() since it will assert that it has the GIL */ + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + return tstate && (tstate == PyGILState_GetThisThreadState()); +} + PyGILState_STATE PyGILState_Ensure(void) {