Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing Python GIL while in C++ code

Tags:

c++

python

gil

swig

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)

like image 636
uhz Avatar asked Oct 16 '09 08:10

uhz


1 Answers

Not having any idea what SWIG is I'll attempt an answer anyway :)

Use something like this to release/acquire the GIL:

class GILReleaser {
    GILReleaser() : save(PyEval_SaveThread()) {}

    ~GILReleaser() {
        PyEval_RestoreThread(save);
    }

    PyThreadState* save;
};

And in the code-block of your choosing, utilize RAII to release/acquire GIL:

{
    GILReleaser releaser;
    // ... Do stuff ...
}
like image 74
Henrik Gustafsson Avatar answered Nov 10 '22 14:11

Henrik Gustafsson