[英]python multiprocessing Pool with multiple arguments and recursion
[英]Python Multiprocessing pool with multiple arguments and void function
我正在尝试在不返回任何内容的 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)
我已经看到了一些相关的职位像这样。 这篇文章和我的不同之处在于我的函数是一个 void 函数,我希望函数只更改变量的值,而不是返回变量。
要使用全局数组更新跨多个进程的数组而不返回结果:
multiprocessing.Array
类来存储数组数据。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.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.