cdef function without python object doesn't allow nogil

437 views
Skip to first unread message

Noon Chen

unread,
May 19, 2021, 10:24:46 AM5/19/21
to cython-users
Hi again,

Here is a function that only uses c type variables.
```
from libc.stdint cimport uint32_t

cdef int testGil() nogil:
    cdef uint32_t FAIL_CNT = 2**32-1
    # cdef uint32_t FAIL_CNT = -1 + 1<<32

    if FAIL_CNT != (0xFFFFFFFF):
        return 1
    return 0

testGil()
```
nogil should be working since it doesn't access any python objects, but an error is thrown when compiling the code above:
Truth-testing Python object not allowed without gil
Operation not allowed without gil
Converting to Python object not allowed without gil

I've googled it but still no clue at all. The example in cython/nogil.pyx is not helping either, what am I missing here?

Thanks in advance!

Stefan Behnel

unread,
May 19, 2021, 10:31:16 AM5/19/21
to Cython-users
Noon Chen schrieb am 19.05.21 um 16:18:
> Hi again,
>
> Here is a function that only uses c type variables.
> ```
> from libc.stdint cimport uint32_t
>
> cdef int testGil() nogil:
> cdef uint32_t FAIL_CNT = 2**32-1
> # cdef uint32_t FAIL_CNT = -1 + 1<<32
>
> if FAIL_CNT != (0xFFFFFFFF):
> return 1
> return 0
>
> testGil()
> ```
> nogil should be working since it doesn't access any python objects, but an
> error is thrown when compiling the code above:
> *Truth-testing Python object not allowed without gil*
> *Operation not allowed without gil*
> *Converting to Python object not allowed without gil*

Cython probably considers 0xFFFFFFFF a constant here that is too large for
a (signed) C int (the default integer value type in C), and makes it a
Python integer instead, just to be on the safe side.

Try 0xFFFFFFFFUL, with a "UL" suffix for "unsigned long".

Or add an explicit cast:
<uint32_t> 0xFFFFFFFF

Stefan

Noon Chen

unread,
May 19, 2021, 10:40:10 AM5/19/21
to cython-users
Wow!

Thanks Stefan! You're correct, Never expected cython would implicitly convert numeric constant to <int>.

Best Regards,
NC😊

Reply all
Reply to author
Forward
0 new messages