Cython 平行范围 - 线程位置



我正在迭代使用prange这样的列表:

from cython.parallel import  prange, threadid
cdef int tid
cdef CythonElement tEl
cdef int a, b, c
# elList: python list of CythonElement instances is passed via function call
for n in prange(nElements, schedule='dynamic', nogil=True):
    with gil:
        tEl = elList[n]
        tid =  threadid()
        a = tEl.a
        b = tEl.b
        c = tEl.c 
        print("thread {:} elnumber {:}".format(tid, tEl.elNumber))
   #nothing is done here
    with gil:
        print("thread {:} elnumber {:}".format(tid, tEl.elNumber))
    # some other computations based on a, b and c here ...

我期望这样的输出:

thread 0 elnumber 1
thread 1 elnumber 2
thread 2 elnumber 3
thread 3 elnumber 4
thread 0 elnumber 1
thread 1 elnumber 2
thread 2 elnumber 3
thread 3 elnumber 4

但我得到:

thread 1 elnumber 1
thread 0 elnumber 3
thread 3 elnumber 2
thread 2 elnumber 4
thread 3 elnumber 4
thread 1 elnumber 2
thread 0 elnumber 4
thread 2 elnumber 4

那么,线程局部变量 tEl 以某种方式被覆盖在线程中?我做错了什么?谢谢!

看起来Cython

故意选择从线程局部变量列表中排除任何Python变量(包括Cython cdef class es(。法典

我怀疑这是故意避免引用计数问题 - 他们需要在循环结束时删除所有线程局部变量的引用计数(这不是一个无法克服的问题,但可能是一个很大的变化(。因此,我认为它不太可能被修复,但文档更新可能会有所帮助。

解决方案是将循环体重构为一个函数,其中每个变量最终都有效地"局部"到函数,这样它就不是问题:

cdef f(CythonElement tEl):
    cdef int tid
    with nogil:
        tid = threadid()
        with gil:
            print("thread {:} elnumber {:}".format(tid, tEl.elNumber))
        with gil:
            print("thread {:} elnumber {:}".format(tid, tEl.elNumber))
   # I've trimmed the function a bit for the sake of being testable
# then for the loop:
for n in prange(nElements, schedule='dynamic', nogil=True):
    with gil:
        f()

Cython提供基于线程的并行性。线程的执行顺序无法保证,因此 thread 的值无序。

如果希望tEl线程专用,则不应全局定义它。尝试在范围内移动cdef CythonElement tEl。请参阅 http://cython-devel.python.narkive.com/atEB3yrQ/openmp-thread-private-variable-not-recognized-bug-report-discussion(私有变量部分(。

最新更新