Search code examples
pythonnumpyfortrangilf2py

f2py function release GIL


Does the Global Interpretter Lock (GIL) get released when I call an f2py wrapped function?

(I'm happy to try to discover on my own, but I'm not familiar enough with the numpy source to know where to start looking)...

To clarify, a good answer to this question would either help me to know where in the numpy source to look for a Py_BEGIN_ALLOW_THREADS or it would simply let me know if the GIL is released (preferably with some evidence).


Solution

  • No, f2py defaults to leaving the GIL in place. However, you can release the GIL by adding the threadsafe directive.

    example:

    subroutine foo(a)
    !f2py threadsafe
    !f2py intent(out) :: a
    integer a
    a = 5
    end subroutine foo
    

    Now compile it:

    f2py -c -m foo --build-dir test_build foo.f90
    

    And we can check the source code:

    grep THREAD test_build/src.*/*.c
    build/src.linux-x86_64-2.7/testmodule.c:      Py_BEGIN_ALLOW_THREADS
    build/src.linux-x86_64-2.7/testmodule.c:      Py_END_ALLOW_THREADS
    

    However, if we repeat the process removing the !f2py threadsafe line, then the macros to release the GIL aren't included.