nogil is an optional Cython function qualifier marking code that can execute without holding CPython’s global interpreter lock. Cython permits it only after Python objects, calls, and return interactions have been removed; otherwise compilation fails. section 5.4.2 section 5.5
Use nogil after eliminating the remaining Python execution paths:
- Declare low-level Cython functions with cdef and typed returns. section 5.4.2
- Operate through typed memoryviews or C-level pointers rather than Python-facing arrays and objects. section 5.4.2 section 5.5
- Pair the qualifier with a parallel executor when real parallel execution is needed; the annotation alone provides no benefit for the single-threaded stage described here. section 5.4.2 section 5.5
Darkening an image
A Cython image-darkening function using typed memoryviews and nogil reduced runtime to 0.04 seconds, compared with 35 seconds for native Python and 18 seconds for naive Cython. The qualifier enabled future parallelism but did not explain this single-threaded speedup. section 5.4.2
@cython.boundscheck(False) #1
cdef void darken_annotated_mv( #2
cnp.uint8_t[:,:,:] image_mv,
cnp.uint8_t[:,:] darken_filter_mv,
cnp.uint8_t[:,:] dark_image_mv) nogil: #3
The compact definition shows nogil attached to a cdef function after typed memoryview parameters, alongside disabled bounds checking. section 5.4.2
