python - 共享只读数据是否复制到不同的进程以进行多处理?

标签 python numpy multiprocessing

我的这段代码看起来像这样:

glbl_array = # a 3 Gb array

def my_func( args, def_param = glbl_array):
    #do stuff on args and def_param

if __name__ == '__main__':
  pool = Pool(processes=4)
  pool.map(my_func, range(1000))

有没有办法确保(或鼓励)不同的进程不会获得 glbl_array 的副本而是共享它。如果无法停止复制,我将使用 memmapped 数组,但我的访问模式不是很规律,所以我希望 memmapped 数组更慢。以上似乎是首先要尝试的。这是在 Linux 上。我只是想从 Stackoverflow 获得一些建议,不想惹恼系统管理员。如果第二个参数是真正的不可变对象(immutable对象),如 glbl_array.tostring(),您认为会有帮助吗?

最佳答案

您可以很容易地将 multiprocessing 中的共享内存内容与 Numpy 一起使用:

import multiprocessing
import ctypes
import numpy as np

shared_array_base = multiprocessing.Array(ctypes.c_double, 10*10)
shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
shared_array = shared_array.reshape(10, 10)

#-- edited 2015-05-01: the assert check below checks the wrong thing
#   with recent versions of Numpy/multiprocessing. That no copy is made
#   is indicated by the fact that the program prints the output shown below.
## No copy was made
##assert shared_array.base.base is shared_array_base.get_obj()

# Parallel processing
def my_func(i, def_param=shared_array):
    shared_array[i,:] = i

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=4)
    pool.map(my_func, range(10))

    print shared_array

打印

[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]
 [ 3.  3.  3.  3.  3.  3.  3.  3.  3.  3.]
 [ 4.  4.  4.  4.  4.  4.  4.  4.  4.  4.]
 [ 5.  5.  5.  5.  5.  5.  5.  5.  5.  5.]
 [ 6.  6.  6.  6.  6.  6.  6.  6.  6.  6.]
 [ 7.  7.  7.  7.  7.  7.  7.  7.  7.  7.]
 [ 8.  8.  8.  8.  8.  8.  8.  8.  8.  8.]
 [ 9.  9.  9.  9.  9.  9.  9.  9.  9.  9.]]

不过,Linux 在 fork() 上有 copy-on-write 语义,所以即使不使用 multiprocessing.Array,数据也不会被复制,除非它被写入到。

关于python - 共享只读数据是否复制到不同的进程以进行多处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5549190/

相关文章:

如果 Web 表单中没有 ID 值,Python Selenium 自动登录问题

python - 使用 python 进行多元线性回归

python - python中有二维字典吗?

python - 使用 numpy 测试误报和漏报

Python 多处理。如何将 XMLRPC ServerProxy 对象排入队列

python - 使用顺序初始化参数的多进程池初始化

python - 根据首字母修改字符串内容

python - 为什么 scipy.sparse.csc_matrix.sum() 的结果将其类型更改为 numpy 矩阵?

python - 有没有任何pythonic方法可以组合两个dicts(为两者中出现的键添加值)?

Python 多处理意外阻塞