There isn't a single best practice because most combinations have their uses
cdef void some_func() nogil:
... # code goes here
This is useful when you don't really care whether the caller has
the GIL. You might do that if you've got a short function that you
call from a lot of places. However, you definitely don't want to
pay the cost of releasing and re-acquiring the GIL .
cdef void some_func() nogil:
with nogil:
... # code goes here
This is useful when the contents are long-running enough that it's
definitely worth releasing the GIL.
cdef void some_func() nogil:
... # code
with gil:
... # python code
... # code
This is a useful thing to do if some of the code requires the GIL. However, if most of the code requires the GIL then your callers may think it's misleading.
> Is it okay to always add nogil in the function definition and use `with gil` to acquire the GIL when necessary?
No - functions taking or returning Python objects do require the
GIL so it isn't always OK.
> It seems that there is no additional overhead because nogil doesn't release the GIL
There's always a cost to releasing, reacquiring, or working out
if you have the GIL. So it's probably worth minimizing the number
of times you do it.
For the two Ray functions, labeling them as nogil looks slightly
pointless to me. However, if they're being passed around in
external code as C callbacks then it might make sense.
--
---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/cython-users/082d02bc-3557-44ed-9a7c-8513ab13f675n%40googlegroups.com.