使用多处理时,共享一个没有锁定的ctypes numpy数组

时间:2016-08-04 14:49:34

标签: python numpy multiprocessing

我有一个大型数组(~500k行x 9列),我想在使用Python的multiprocessing模块运行多个并行进程时分享这些数组。我正在使用this SO回答来创建我的共享数组,并且从this 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)

错误是这样的:

---------------------------------------------------------------------------
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'

我的问题是我如何分享每次写入时都没有锁定的numpy数组?

1 个答案:

答案 0 :(得分:2)

感谢here

找到答案HYRY

声明lock=True会返回一个包装对象:

multiprocessing.sharedctypes.SynchronizedArray

lock=False返回没有.get_obj()方法

的原始数组时
multiprocessing.sharedctypes.c_double_Array_10

因此,创建解锁数组的代码如下:

shared_array_base = multiprocessing.Array(ctypes.c_double, 90, lock=False)
shared_array = np.ctypeslib.as_array(shared_array_base)
shared_array = shared_array.reshape(-1, 9)