You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在调用嵌入式C函数前释放Python的GIL?

问题:Cython调用C函数时释放GIL报错的解决

我编写了如下Cython代码:

cdef public int CythonfunC():
    with nogil:
        embeddedCFunction()

cdef extern from *:
r"""
#include <wchar.h>
#include <Python.h>
#include "cfunctions.h";
#include <tchar.h>
#include <windows.h>

int embeddedCFunction(){
    //do stuff that don't require GIL
    return 0;
}
PyObject *OtherFunctions(){

    return PyObjectX;
}
"""
int embeddedCFunction()

运行时出现错误:Calling gil-requiring function not allowed without gil。尝试过with nogil except:等方法,但未解决问题。请问如何在调用embeddedCFunction前释放全局解释器锁(GIL)?


解决方法

错误核心原因是:Cython默认假设所有外部声明的C函数可能需要GIL,即便你在nogil块中调用它,Cython仍会判定该函数需要持有GIL,从而抛出错误。解决步骤如下:

  • 明确声明C函数无需GIL
    在外部函数声明时,给embeddedCFunction加上nogil修饰符,告知Cython这个纯C函数不依赖GIL即可运行。修改后的extern声明部分如下:

    cdef extern from *:
    r"""
    #include <wchar.h>
    #include <Python.h>
    #include "cfunctions.h";
    #include <tchar.h>
    #include <windows.h>
    
    int embeddedCFunction(){
        //do stuff that don't require GIL
        return 0;
    }
    PyObject *OtherFunctions(){
    
        return PyObjectX;
    }
    """
    int embeddedCFunction() nogil  # 添加nogil修饰符
    
  • 确认C函数无Python依赖
    确保embeddedCFunction内部确实没有任何调用Python API的代码(比如操作PyObject、调用Python相关函数等)。如果函数内有隐含的Python操作,必须持有GIL,此时不能使用nogil块。

  • 检查nogil块范围
    确保with nogil:块内只包含无需GIL的纯C操作,不要在块内处理Python对象、调用Python函数等需要GIL的逻辑。

修改后的完整代码示例:

cdef public int CythonfunC():
    with nogil:
        embeddedCFunction()

cdef extern from *:
r"""
#include <wchar.h>
#include <Python.h>
#include "cfunctions.h";
#include <tchar.h>
#include <windows.h>

int embeddedCFunction(){
    //do stuff that don't require GIL
    return 0;
}
PyObject *OtherFunctions(){

    return PyObjectX;
}
"""
int embeddedCFunction() nogil

内容的提问来源于stack exchange,提问作者Abdul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:15:18