我正在使用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在多个线程之间被覆盖了?我做错了什么吗?谢谢!
tEl
设为线程本地变量(查看生成的C文件,并搜索“lastprivate”以进行检查)。如果您将其更改为基本类型(如“double”),则可以正常工作,但是似乎无法使用Cython对象类型。我不知道明显的解决方案,但在GitHub上提交错误可能值得一试。 - DavidW