I want to call some c function from python to be able to improve performance of my code. But I cannot find online whether when I call a C function using the ctypes libraries the GIL is released. As a simple example:
from ctypes import * fun = cdll.LoadLibrary("libc.so.6") fun.sleep.argtypes = [c_uint] fun.sleep(c_uint(5))
Is the GIL released during the call to fun.sleep
?
Advertisement
Answer
According to [Python.Docs]: ctypes.CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) (emphasis is mine):
The returned function prototype creates functions that use the standard C calling convention. The function will release the GIL during the call.
Also (in order to link *FUNCTYPE and *DLL), [Python.Docs]: class ctypes.PyDLL(name, mode=DEFAULT_MODE, handle=None) (emphasis still mine):
Instances of this class behave like CDLL instances, except that the Python GIL is not released during the function call
Therefore, the answer to your question is: YES.
As a side note, if fun.sleep is called many times (like in a loop or something), there’s time “lost” in marshalling data between Python and C for every call, and in that case you might want to consider writing the whole loop in C.