首页 > 解决方案 > cython openmp 单,屏障

问题描述

我正在尝试在 cython 中使用 openmp。我需要在 cython 中做两件事:

i)#pragma omp single{}在我的 cython 代码中使用范围。

ii) 使用#pragma omp barrier{}

有谁知道如何在cython中做到这一点?

这里有更多细节。我有一个 nogil cdef 函数my_fun(),我在 omp for 循环中调用它:

from cython.parallel cimport prange
cimport openmp

cdef int i

with nogil:
    for i in prange(10,schedule='static', num_threads=10):
        my_func(i)

在里面my_func我需要放置一个屏障来等待所有线程赶上,然后只在其中一个线程中执行一个耗时的操作并获得 gil,然后释放屏障以便所有线程同时恢复。

cdef int my_func(...) nogil:

    ...

    # put a barrier until all threads catch up, e.g. #pragma omp barrier

    with gil:
        # execute time consuming operation in one thread only, e.g. pragma omp single{}

    # remove barrier after the above single thread has finished and continue the operation over all threads in parallel, e.g. #pragma omp barrier

    ...


标签: openmpcython

解决方案


Cython 对 openmp 有一些支持,但如果广泛使用 openmp-pragmas,用 C 编写代码并用 Cython 包装生成的代码可能更容易。


作为替代方案,您可以使用带有定义的逐字 C 代码和技巧来为 Cython 带来一些功能,但是在定义中使用编译指示并不直接(_PragmaC99 解决方案,MSVC 一如既往地做自己的事情)__pragma),有一些例子可以作为 Linux/gcc 的概念证明:

cdef extern from *:
    """
    #define START_OMP_PARALLEL_PRAGMA() _Pragma("omp parallel") {
    #define END_OMP_PRAGMA() }
    #define START_OMP_SINGLE_PRAGMA() _Pragma("omp single") {
    #define START_OMP_CRITICAL_PRAGMA() _Pragma("omp critical") {   
    """
    void START_OMP_PARALLEL_PRAGMA() nogil
    void END_OMP_PRAGMA() nogil
    void START_OMP_SINGLE_PRAGMA() nogil
    void START_OMP_CRITICAL_PRAGMA() nogil

我们让 Cython 相信,that START_OMP_PARALLEL_PRAGMA()and Co. 是 nogil 函数,所以它将它们放入 C 代码中,因此它们被预处理器拾取。

我们必须使用语法

#pragma omp single{
   //do_something
}

并不是

#pragma omp single
do_something

因为 Cython 生成 C 代码的方式。

用法可能如下所示(我在这里避免,from cython.parallel.parallel因为它对这个简单的例子有太多的魔力):

%%cython -c=-fopenmp --link-args=-fopenmp
cdef extern from *:# as listed above
    ...

def test_omp():
    cdef int a=0
    cdef int b=0  
    with nogil:
        START_OMP_PARALLEL_PRAGMA()
        START_OMP_SINGLE_PRAGMA()
        a+=1
        END_OMP_PRAGMA()
        START_OMP_CRITICAL_PRAGMA()
        b+=1
        END_OMP_PRAGMA() # CRITICAL
        END_OMP_PRAGMA() # PARALLEL
    print(a,b)

正如预期的那样,在我的机器上使用 2 个线程调用test_omp打印“1 2”(可以使用 更改线程数openmp.omp_set_num_threads(10))。

但是,上面的内容仍然很脆弱——Cython 的一些错误检查会导致代码无效(Cython 使用 goto 进行控制流,无法跳出 openmp-block)。在您的示例中发生了这样的事情:

cimport numpy as np
import numpy as np
def test_omp2():
    cdef np.int_t[:] a=np.zeros(1,dtype=int)

    START_OMP_SINGLE_PRAGMA()
    a[0]+=1
    END_OMP_PRAGMA()

    print(a)

由于边界检查,Cython 将产生:

START_OMP_SINGLE_PRAGMA();
...
//check bounds:
if (unlikely(__pyx_t_6 != -1)) {
    __Pyx_RaiseBufferIndexError(__pyx_t_6);
    __PYX_ERR(0, 30, __pyx_L1_error)  // HERE WE GO A GOTO!
}
...
END_OMP_PRAGMA();

在这种特殊情况下,将 boundcheck 设置为 false,即

cimport cython
@cython.boundscheck(False) 
def test_omp2():
   ...

可以解决上述示例的问题,但一般情况下可能不会。

再一次:在 C 中使用 openmp(并用 Cython 包装功能)是一种更愉快的体验。


附带说明:Python 线程(由 GIL 管理的线程)和 openmp 线程是不同的,彼此一无所知。上面的示例也可以在不释放 GIL 的情况下正确工作(编译和运行)——openmp-threads 不关心 GIL,但由于不涉及 Python 对象,因此不会出错。因此我已经添加nogil到包装的“函数”中,所以它也可以在 nogil 块中使用。

然而,当代码变得更复杂时,它变得不那么明显了,不同 Python 线程之间共享的变量不会被访问(以上都是因为这些访问可能发生在生成的 C 代码中,而这在 Cython 中并不清楚-代码),在使用 openmp 时不释放 gil 可能更明智。


推荐阅读