Cython 并行 prange - 线程局部性?

mac*_*low 4 parallel-processing multithreading 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 ...
Run Code Online (Sandbox Code Playgroud)

我期望这样的输出:

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
Run Code Online (Sandbox Code Playgroud)

但我得到:

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
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*idW 5

看起来 Cython 故意选择cdef class从线程局部变量列表中排除任何 Python 变量(包括 Cython 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()
Run Code Online (Sandbox Code Playgroud)