在C ++代码中发布Python GIL [英] Releasing Python GIL while in C++ code

查看:135
本文介绍了在C ++代码中发布Python GIL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用C ++编写的库,我使用SWIG包装并在python中使用。通常有一个类有很少的方法。问题是调用这些方法可能很耗时 - 它们可能挂起我的应用程序(调用这些方法时GIL不会释放)。所以我的问题是:



为这些方法调用释放GIL的最简单的方法是什么?



(我明白,如果我使用C库,我可以用一些额外的C代码包装,但这里我使用C ++和类)

$ b $真正的问题是SWIG没有记录良好(我看到使用changelog进行搜索的提示);)



好的,我发现我可以在SWIG中使用内联函数,并使用宏释放/获取GIL,它看起来像这样:

 %inline%{
void wrappedFunction(OriginalObject * o,< parameters>){
Py_BEGIN_ALLOW_THREADS
o-> originalFunction(< parameters>);
Py_END_ALLOW_THREADS
}
%}

此功能不存在在原来的C ++,但可用在python模块。这是(几乎)正是我想要的。 (我想要的是像python装饰器包装原始方法)


I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is:

What is the simplest way to release GIL for these method calls?

(I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes)

解决方案

The real problem is that SWIG is not documented well (I saw hints to use changelog for searching ;) ).

Ok, I found out that I can do inline functions in SWIG and use macros to release/acquire GIL, it looks like this:

%inline %{
    void wrappedFunction(OriginalObject *o, <parameters>) {
    Py_BEGIN_ALLOW_THREADS
    o->originalFunction(<parameters>);
    Py_END_ALLOW_THREADS
}
%}

This function is not present in original C++, but available in python module. This is (almost) exactly what I wanted. (what I would like is to wrap original method like python decorator does)

这篇关于在C ++代码中发布Python GIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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