在Cython的这个malloc'ed数组中会发生什么?

时间:2014-02-14 08:44:02

标签: python c malloc cython

%%cython -f -c=-O3 -c=-fopenmp --link-args=-fopenmp
from cython.parallel import parallel, prange
from libc.stdlib cimport abort, malloc, free

cdef int idx, i, n = 100
cdef int k
cdef int * local_buf
cdef int size = 10

cdef void func(int* lb) nogil:
    cdef int j
    for j in xrange(size):
        lb[j] += -1*j

local_buf = <int *> malloc(sizeof(int) * size)
with nogil, parallel():

    if local_buf == NULL:
        abort()

    # populate our local buffer in a sequential loop
    for i in xrange(size):
        local_buf[i] = i * 2

    # share the work using the thread-local buffer(s)
    for k in prange(n, schedule='guided'):
        func(local_buf)

for i in xrange(size):
    print local_buf[i]

free(local_buf)

0
-98
-196
-294
-392
-490
-588
-686
-784
-882

编辑: 上面的块显示了一次运行后的输出,但local_buf中的内容似乎每次都重新运行。发生了什么事?

1 个答案:

答案 0 :(得分:3)

对于给出的代码,结果似乎合理,你实际上每次运行得到不同的结果吗?

这应该是常规的python等价物:

size = 10
n = 100

lst = [i*2 for i in range(size)]

for i in range(n):
    for j in range(size):
        lst[j] += -1*j
print lst
#[0, -98, -196, -294, -392, -490, -588, -686, -784, -882]