2

我想存储一个2-d数组作为共享内存数组,所以每个由多处理模块创建的进程都可以访问2-d数组。但似乎只有矢量是允许的。如果我将以下示例中的形状从(6,1)更改为(2,3),该示例将不起作用,并且它会显示“TypeError:只能将长度为1的数组转换为Python标量”python多处理共享内存数组不允许二维数组

from multiprocessing import Process, Value, Array 
import numpy as np 

def f(n,a): 
    a[:] = np.ones(shape=(6,1), dtype=float)[:] 

if __name__ == '__main__': 
    tmp = np.zeros(shape=(6,1), dtype=float) 
    print tmp 

    arr = Array('f', tmp) 

    p1 = Process(target=f, args=(1,arr)) 
    p1.start() 
    p1.join() 

    print 'done' 
    print arr[:] 

回答

3

这是因为mutiprocessing.Array是python的array类型的包装,而不是numpy.ndarray和python的array类型不支持多维度。具体而言,看为initializer的文档:

A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, string, or iterable over elements of the appropriate type.

你有一个可迭代(多维阵列),但它产生的观点/阵列,适当类型的不元件。

+0

有没有一种快速的方法将numpy.ndarray转换为数组? –

+0

@readRead - 只有一维numpy数组可以转换为'array' - 它会复制(不是视图) – mgilson

+0

谢谢。我打算对每个进程中的共享数组执行一些矩阵操作。如果我只是存储一维数组,这不是很方便。如何跨进程共享一个2-D numpy阵列并避免复制?也许使用除多处理以外的其他东西。数组? –