使用多处理将值分配给 numpy 数组

计算科学 Python 麻木的 scipy
2021-12-16 06:24:17

我有一个类似的代码:

import numpy as np
import multiprocessing as mp

a = np.zeros((4, 4))  # 4x4 array containing zeros

def f(x, y):
    # uses scipy functions
    # takes long to compute
    #result = <someValue after calculation>
    global a
    a[x][y] = x+y  # simple example function

# since f takes long to compute, I want to run it in parallel
jobs = []
for x in range(4):
    for y in range(4):
        p = mp.Process(target=f, args=(x, y))
        p.start()
        jobs.append(p)

# wait for a to be filled for the next step
for j in jobs:
    j.join()

print a  # prints an array of zeros! 

为什么没有将值分配给 a ,我该如何解决这个问题?谢谢!

1个回答

mp.ProcessMultiprocessing 为您要求的每个进程创建单独的 Python 进程(即 UNIX 或 Windows 进程) 。这些共享内存。如果您希望它们对相同的数据进行操作,则必须使用类中的一种托管数据类型mp.Manager来显式地在不同的任务之间进行通信。

FWIW,这非常慢,因为您放入mp.Manager容器中的任何对象在通信之前都会被腌制。

其它你可能感兴趣的问题