How can I check whether a thread currently holds the GIL? How can I check whether a thread currently holds the GIL? multithreading multithreading

How can I check whether a thread currently holds the GIL?


If you are using (or can use) Python 3.4, there's a new function for the exact same purpose:

if (PyGILState_Check()) {    /* I have the GIL */}

https://docs.python.org/3/c-api/init.html?highlight=pygilstate_check#c.PyGILState_Check

Return 1 if the current thread is holding the GIL and 0 otherwise. This function can be called from any thread at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return 1. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or otherwise behave differently.

In python 2, you can try something like the following:

int PyGILState_Check2(void) {    PyThreadState * tstate = _PyThreadState_Current;    return tstate && (tstate == PyGILState_GetThisThreadState());}

It seems to work well in the cases i have tried.https://github.com/pankajp/pygilstate_check/blob/master/_pygilstate_check.c#L9


I dont know what you are looking for ... but just you should consider the use of the both macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS, with this macros you can make sure that the code between them doesn't have the GIL locked and random crashes inside them will be sure.