首页 > 解决方案 > 一些标准 C 库数学运算不能与 noGIL 配合使用

问题描述

我有一个包含以下代码的 pyx 文件:

cimport cython
from libc.math cimport sqrt, abs
from libc.stdio cimport printf
from cython.parallel import prange

cdef double my_abs(double a):
    return sqrt(a*a)

cpdef loop(int a):
    cdef int i
    cdef int sum = 0
    for i in prange(a, nogil=True):
        printf("%s %i %s %f\n", "The square root of ", i, " is ", sqrt(i))
        #printf("%s %i %s %f\n", "The absolute value of ", i, " is ", abs(i))
        #printf("%s %i %s %f\n", "The absolute value of ", i, " is ", my_abs(i))
    return

当我取消注释循环中的两行中的任何一行时,它无法编译。

  1. 为什么当 sqrt、pow 等其他函数似乎与 nogil 一起使用时,libc.math abs 函数不能很好地发挥作用?
  2. 我必须向我的函数(和 .pxd 文件)添加什么才能使其成为 nog​​il?我已尝试在此页面https://lbolla.info/python-threads-cython-gil之后添加,但它仍然无法编译。

这个问题类似于:

提前致谢!

标签: cythongil

解决方案


abs不在 C 标准库 math.h 中

这些便利的 abs 重载不包括 C++。在 C 中,abs 仅在 in 中声明(并对 int 值进行操作)。

我有点惊讶 Cython 没有抱怨你cimport不存在的东西,但它将使用 Pythonabs内置(或可能稍微优化的 Cython 等效项)。

你想要fabs


推荐阅读