Python 具有多个参数和 void 函数的多处理池

Python Multiprocessing pool with multiple arguments and void function

我正在尝试在不 return 任何内容的 void 函数上使用具有多个参数的 Python 多处理库。这是我的最小工作示例。

import numpy as np
from multiprocessing import Pool

dim1 = 2
dim2 = 2

test1 = np.zeros((dim1,dim2))
test2 = np.zeros((dim1,dim2))

iteration = []
for i in range(0,dim1):
    for j in range(0,dim2):
        iteration.append((i,j))
        
def testing(num1,num2):
    test1[num1,num2] = 1
    test2[num1,num2] = 2
    
if __name__ == '__main__':
    pool = Pool(processes=4)  
    pool.starmap(testing, iteration)
    
print(test1)
print(test2)

这里的问题是变量 test1 和 test2 在第一次初始化时打印零数组。相反,我为 test1 做的是 1 的数组和 test2 的 2 的数组。我要什么代码

if __name__ == '__main__':
    pool = Pool(processes=4)  
    pool.starmap(testing, iteration)

要做的是:

testing(0,0)
testing(1,0)
testing(0,1)
testing(1,1)

我看过一些相关的 post,例如 this。这个 post 和我的区别在于我的函数是一个 void 函数,而不是 returning 变量,我希望函数只改变变量的值。

要使用全局数组 更新多个进程的数组而不 返回结果:

  • 使用multiprocessing.Arrayclass来存储数组数据
  • 创建池时使用 initializer 参数将数组传递给进程。

请注意 Array 是一维的,因此必须重新整形才能更新和显示。

试试这个代码:

import numpy as np
from multiprocessing import Pool, Array

dim1 = 2
dim2 = 2

def init(tt1,tt2):  # receive shared arrays
   global test1,test2
   test1,test2 = tt1,tt2

def testing(num1,num2):
    t1 = np.frombuffer(test1.get_obj()).reshape((dim1, dim2))  # need to reshape to 2D array
    t2 = np.frombuffer(test2.get_obj()).reshape((dim1, dim2))
    t1[num1,num2] = 1
    t2[num1,num2] = 2
   
if __name__ == '__main__':
    tt1 = Array('d', dim1*dim2)  # 1 dimensional arrays
    tt2 = Array('d', dim1*dim2)

    iteration = []
    for i in range(0,dim1):
        for j in range(0,dim2):
            iteration.append((i,j))
            
    pool = Pool(processes=4, initializer=init, initargs=(tt1,tt2))   # pass shared arrays to processes
    pool.starmap(testing, iteration)
    
    # still have access to the shared arrays
    t1final = np.frombuffer(tt1.get_obj()).reshape((dim1, dim2))
    t2final = np.frombuffer(tt2.get_obj()).reshape((dim1, dim2))
    print(t1final, t2final, sep='\n')

输出

[[1. 1.]
 [1. 1.]]
[[2. 2.]
 [2. 2.]]