gpt4 book ai didi

python - 如何检查线程当前是否持有 GIL?

转载 作者:太空狗 更新时间:2023-10-29 18:03:15 24 4
gpt4 key购买 nike

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

Python/C-API 文档似乎没有包含这样的函数。

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

(顺便说一下,“发出 fatal error ”是什么意思?)

这个问题的背景:我有一个嵌入 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

关于python - 如何检查线程当前是否持有 GIL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11366556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com