在 python 多处理中共享和编辑 numpy 数组

Sharing and editing numpy array in python multiprocessing

我在 python 中使用多处理对 numpy 进行了试验我已经阅读了大量教程和 Whosebug 答案。 我写了一个代码:

from multiprocessing import Process, Array
import numpy as np

def main():
    im_arr = np.array([[1,2,3],[4,6,7]])
    print('Array in main before process:',im_arr)

    shape = im_arr.shape
    size = im_arr.size
    im_arr.shape = size
    arr = Array('B', im_arr)   
    p = Process(target=fun, args=(arr,shape))
    p.start()
    p.join()

    arr = np.frombuffer(arr.get_obj(), dtype=np.uint8)
    arr.shape = shape
    print('Array in main after process:',arr)

def fun(a, shape):
    a = np.frombuffer(a.get_obj(), dtype=np.uint8)
    a.shape = shape

    a[0][0] = 10
    a = np.array([[0,0,0],[0,0,0]])
    a[0][0] = 5

    print('Array inside function:',a)
    a.shape = shape[0]*shape[1]

if __name__ == '__main__':
    main()

我希望做的是共享一个numpy数组并在另一个进程中编辑数组,同时也可以在主程序中观察到变化。 但是我得到的输出如下

('Array in main before process:', array([[1, 2, 3],
       [4, 6, 7]]))
('Array inside function:', array([[5, 0, 0],
       [0, 0, 0]]))
('Array in main after process:', array([[10,  2,  3],
       [ 4,  6,  7]], dtype=uint8))

函数中的'a'似乎在将numpy数组保存到它之后表现得像一个新的独立对象。

请指正我做错的地方。

我建议为此使用内存映射。首先,在其中一个过程中创建数组:

im_arr = np.array([[1,2,3],[4,6,7]])

然后,将其保存到磁盘:

np.save('im_arr.npy', im_arr)

然后,在每个进程中加载​​它,用mode='r+'这样你就可以修改它:

im_arr = np.load('im_arr.npy', 'r+')

现在,内容将始终对两个进程可见。

it seems like 'a' in the function behaves like a new independent object after the numpy array is saved to it.

好吧,这部分是正确的。使用 np.array([[0,0,0],[0,0,0]]) 创建一个新的独立对象,然后使用 a = 将标签 a 附加到它。从那时起,标签 a 不再指向共享数组。

如果你想在共享内存中保存一个新的数组,你可以使用

a[...] = np.array([[0,0,0],[0,0,0]])

(这实际上是有效语法,... 称为省略号文字)