我试图找到一个函数,告诉我当前线程是否具有全局解释器锁.
Python / C-API文档似乎不包含这样的函数.
我目前的解决方案是在使用PyEval_SaveThread释放它之前使用PyGILState_Ensure()获取锁,而不是尝试释放当前线程未获取的锁.
(顺便说一下,“发出致命错误”是什么意思?)
这个问题的背景:我有一个嵌入Python的多线程应用程序.如果线程在没有释放锁定的情况下关闭(可能由于崩溃而发生),则其他线程将无法再运行.因此,当清理/关闭线程时,我想检查该线程是否保持锁定并在这种情况下释放它.
提前谢谢你的答案!
解决方法:
如果你正在使用(或可以使用)Python 3.4,那么有一个新函数用于完全相同的目的:
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.
在python 2中,您可以尝试以下内容:
int PyGILState_Check2(void) {
PyThreadState * tstate = _PyThreadState_Current;
return tstate && (tstate == PyGILState_GetThisThreadState());
}
在我尝试过的案例中似乎运作良好.
https://github.com/pankajp/pygilstate_check/blob/master/_pygilstate_check.c#L9