RAII vs gc (was fortran lib which provide python like data type)

Chris Angelico rosuav at gmail.com
Sat Jan 31 22:21:22 EST 2015


On Sun, Feb 1, 2015 at 2:00 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>> A C++ statement with RAII like
>>
>> {
>>    Foo bar();
>>    // suite
>> }
>>
>> is not equivalent to
>>
>>     bar = Foo()
>>
>> in Python. It actually corresponds to
>>
>> with Foo() as bar:
>>     <suite>
>
>
> Nice answer! I'm not qualified to tell whether you are right or not, but
> what you say has the ring of truth about it.

I would say that this is indeed correct, with the caveat that RAII is
most often used for memory allocation, in which case the correct
transformation into Python _would_ be a constructor call. But when you
use this kind of thing to set up state and clean up afterwards, then
yes, Python's equivalent would be a context manager.

So a C++ way to release and reacquire the GIL might look like this
(borrowing from https://docs.python.org/3.5/c-api/init.html):

class ReleaseGIL
{
    //Internal state
    PyThreadState *_save;
public:
    //Constructor
    ReleaseGIL() {_save = PyEval_SaveThread();}
    //Destructor
    ~ReleaseGIL() {PyEval_RestoreThread(_save);}
};

//Usage example:
int do_work()
{
    while (1)
    {
        //use the Python C API to figure out what we need to do
        ReleaseGIL heavy_processing_coming;
        //do the heavy computational work
    } //GIL is reacquired here
}


The Python equivalent would be something like:

@contextlib.contextmanager
def release_gil():
    """Why the <bleep> are we manipulating the
    GIL from Python code anyway???"""
    _save = PyEval_SaveThread()
    yield
    PyEval_RestoreThread(_save)

def do_work()
    while True:
        # get some work
        with release_gil() as heavy_processing_coming:
            # do the heavy computational work
        # GIL is reacquired here

In each case, you have a guarantee that code following the suite will
not be executed without first performing the appropriate cleanup.

ChrisA



More information about the Python-list mailing list