如何检查线程当前是否持有GIL? [英] How can I check whether a thread currently holds the GIL?

查看:99
本文介绍了如何检查线程当前是否持有GIL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个告诉我当前线程是否具有全局解释器锁的函数.

I tried to find a function that tells me whether the current thread has the global interpreter lock or not.

Python/C-API文档似乎不包含此类功能.

The Python/C-API documentation does not seem to contain such a function.

我当前的解决方案是仅使用PyGILState_Ensure()获取锁,然后使用PyEval_SaveThread释放该锁,而不尝试释放当前线程未获取的锁.

My current solution is to just acquire the lock using PyGILState_Ensure() before releasing it using PyEval_SaveThread to not try releasing a lock that wasn't acquired by the current thread.

(顺便说一句,发出致命错误"是什么意思?)

(btw. what does "issues a fatal error" mean?)

这个问题的背景:我有一个嵌入Python的多线程应用程序.如果一个线程在没有释放锁的情况下被关闭(可能由于崩溃而发生),则其他线程将无法再运行.因此,在清理/关闭线程时,我想检查该线程是否持有该锁,并在这种情况下将其释放.

Background of this question: I have a multithreaded application which embeds Python. If a thread is closed without releasing the lock (which might occur due to crashes), other threads are not able to run any more. Thus, when cleaning up/closing the thread, I would like to check whether the lock is held by this thread and release it in this case.

提前感谢您的回答!

推荐答案

如果您正在使用(或可以使用)Python 3.4,则有一个完全相同目的的新函数:

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

如果当前线程持有GIL,则返回1,否则返回0.可以随时从任何线程调用此函数.仅当其Python线程状态已初始化且当前正在保存GIL时,它才会返回1.这主要是一个辅助功能/诊断功能.例如,在知道GIL已锁定可以允许调用者执行敏感操作或以其他方式表现不同时,它在回调上下文或内存分配函数中很有用.

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中,您可以尝试执行以下操作:

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

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

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

这篇关于如何检查线程当前是否持有GIL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆