首页 > 解决方案 > 如何在 for 循环中使用多处理

问题描述

我正在尝试在 for 循环中执行多处理,但问题是 pool.map 似乎正在使用 for 循环中可迭代的最后一个值进行所有迭代。

from multiprocessing import Pool
import random

args = [1,2]
repeat = 3
output = [0] * len(args)

def myfunc(_):    
    b = 2
    return a +1, b +2

count = 0  
for arg in args:
    
    a = arg
    if __name__ == '__main__':
        with Pool(2 ) as p:
             out1,out2  = zip(*p.map(myfunc, range(0, repeat ), chunksize =1))
             temp = [out1,out2 ]
             output[count] = temp
             
    count += 1

输出:

 [[(3, 3, 3), (4, 4, 4)], [(3, 3, 3), (4, 4, 4)]]

这表明 myfuna对循环中的所有迭代都使用 = 2 。

预期输出:

[[(2, 2, 2), (4, 4, 4)], [(3, 3, 3), (4, 4, 4)]]

注意:实际上, myfunc随机输出是耗时的模拟(因此即使使用相同的参数,我也需要多次重复该函数)并且我必须初始化一个列表来存储结果是固有的

我怎样才能达到预期的输出?

标签: pythonfor-loopmultiprocessingpool

解决方案


所有变量都应该在if name == '__main__'.
只有它之外的东西应该是函数定义和导入。
当您生成一个子进程时,它会重新初始化导入并且可能会覆盖您的变量。这在 Windows 中最为明显,但在 Linux 中仍可能发生。

from multiprocessing import Pool

def myfunc(a):    
    b = 2
    return a +1, b +2

if __name__ == '__main__':
    args = [1,2]
    repeat = 3
    output = [0] * len(args)
    count = 0  
    for arg in args:
    
        a = arg
        with Pool(2) as p:
            out1, out2 = zip(*p.map(myfunc, [a]*repeat, chunksize =1))
            temp = [out1,out2]
            output[count] = temp
             
        count += 1

    print(output)

推荐阅读