相关疑难解决方法(0)

在共享内存中使用numpy数组进行多处理

我想在共享内存中使用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]
Run Code Online (Sandbox Code Playgroud)

这会产生如下输出:

Originally, the first two elements of arr = …
Run Code Online (Sandbox Code Playgroud)

python shared numpy multiprocessing

95
推荐指数
6
解决办法
6万
查看次数

使用多处理时共享无锁的 ctypes numpy 数组

我有一个大数组(~500k 行 x 9 列),我想在使用 Pythonmultiprocessing模块运行多个并行进程时共享它。我正在使用这个 SO答案来创建我的共享数组,我从这个 SO答案中了解到该数组已被锁定。但是,在我的情况下,因为我从来没有同时写入同一行,所以锁是多余的,会增加处理时间。

lock=False但是,当我指定时,出现错误。

我的代码是这样的:

shared_array_base = multiprocessing.Array(ctypes.c_double, 90, lock=False)
shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
shared_array = shared_array.reshape(-1, 9)
Run Code Online (Sandbox Code Playgroud)

错误是这样的:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-d89681d70c37> in <module>()
      1 shared_array_base = multiprocessing.Array(ctypes.c_double, len(np.unique(value)) * 9, lock=False)
----> 2 shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
      3 shared_array = shared_array.reshape(-1, 9)

AttributeError: 'c_double_Array_4314834' object has no attribute 'get_obj'
Run Code Online (Sandbox Code Playgroud)

我的问题是如何共享每次写入时未锁定的 numpy 数组?

python numpy multiprocessing

5
推荐指数
1
解决办法
1246
查看次数

标签 统计

multiprocessing ×2

numpy ×2

python ×2

shared ×1