I have some Cython code that I'd like to run as quickly as possible. Do I need to release the GIL in order to do this?
Let's suppose my code is similar to this:
import numpy as np
# trivial definition just for illustration!
cdef double some_complicated_function(double x) nogil:
return x
cdef void func(double[:] input) nogil:
cdef double[:] array = np.zeros_like(input)
for i in range(array.shape[0]):
array[i] = some_complicated_function(input[i])
I get a whole load of error messages from the np.zeros_like
line similar to:
nogilcode.pyx:7:40: Calling gil-requiring function not allowed without gil
nogilcode.pyx:7:29: Accessing Python attribute not allowed without gil
nogilcode.pyx:7:27: Accessing Python global or builtin not allowed without gil
nogilcode.pyx:7:40: Constructing Python tuple not allowed without gil
nogilcode.pyx:7:41: Converting to Python object not allowed without gil
Do I need to find a way of calling np.zeros_like
without the GIL? Or find some other way of allocating an array that doesn't require the GIL?
Note: this is a self-answered question designed to clear up some common misunderstanding about Cython and the GIL (although you're welcome to answer it too, of course!).
Second note: I've contributed enough to Cython that I should note it here (given that I'm bringing the topic up)