【发布时间】:2011-12-15 05:44:02
【问题描述】:
我想在共享内存中使用一个 numpy 数组来与多处理模块一起使用。困难在于像使用 numpy 数组一样使用它,而不仅仅是作为 ctypes 数组。
from multiprocessing import Process, Array
import scipy
def f(a):
a[0] = -a[0]
if __name__ == '__main__':
# Create the array
N = int(10)
unshared_arr = scipy.rand(N)
arr = Array('d', unshared_arr)
print "Originally, the first two elements of arr = %s"%(arr[:2])
# Create, start, and finish the child processes
p = Process(target=f, args=(arr,))
p.start()
p.join()
# Printing out the changed values
print "Now, the first two elements of arr = %s"%arr[:2]
这会产生如下输出:
Originally, the first two elements of arr = [0.3518653236697369, 0.517794725524976]
Now, the first two elements of arr = [-0.3518653236697369, 0.517794725524976]
可以以 ctypes 方式访问数组,例如arr[i] 有道理。但是,它不是一个numpy数组,我无法执行-1*arr或arr.sum()之类的操作。我想一个解决方案是将 ctypes 数组转换为 numpy 数组。但是(除了无法完成这项工作),我不相信它会再被分享。
对于必须成为常见问题的问题,似乎会有一个标准解决方案。
【问题讨论】:
-
这不是同一个问题。链接的问题是询问
subprocess而不是multiprocessing。
标签: python numpy multiprocessing shared