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

穿精又带淫゛_ 提交于 2019-11-30 12:14:20

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!