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

kun*_*hil 5 python numpy multiprocessing

我有一个大数组(~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 数组?

kun*_*hil 3

感谢HYRY在这里找到了答案

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

multiprocessing.sharedctypes.SynchronizedArray
Run Code Online (Sandbox Code Playgroud)

lock=False返回一个没有该.get_obj()方法的原始数组时

multiprocessing.sharedctypes.c_double_Array_10
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)