首页 > 解决方案 > Cython 的 OpenMP 减少问题

问题描述

在编译期望执行缩减的 OpenMP 并行代码时,我面临 Cython (v. 0.29.13) 的意外行为:

import cython
from cython.parallel import prange, parallel

cpdef omp_test1(n):
    cdef int sum = 0, i, imax
    imax = <int>n
    for i in prange(imax, nogil=True):
        sum += 1
    return sum


cpdef omp_test2(n):
    cdef int sum = 0, i, imax
    imax = <int>n
    with nogil, parallel():
        for i in prange(imax):
            sum += 1
    return sum

当调用这两个函数时,我希望输入参数作为返回值n。相反,返回值为n * num_threads. 令人惊讶的是,在我的 Mac 上,这种意外行为仅在 GCC (v. 9.2.0_2) 中观察到;clang (v. 11.0.0) 返回期望值n

我做错了什么还是生成的 Cython 代码或 GCC 编译器有问题?

标签: gccclangopenmpcythonreduction

解决方案


你的代码很好。我也成功地运行了它,就像 DavidW 一样。

我正在多个操作系统和不同的 Python 版本上以自动方式测试 OpenMP 并行化 Cython 代码。偶尔,我们在 MacOS 上会遇到问题,但会发出叮当声。

这不会解决您的问题,但作为提示,您应该查看编译器或您的 OpenMP 版本。


推荐阅读