如何在for循环中使用多处理
How to use multiprocessing within for loop
我试图在 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)]]
这表明 myfun 在循环中的所有迭代中使用 a
= 2。
预期输出:
[[(2, 2, 2), (4, 4, 4)], [(3, 3, 3), (4, 4, 4)]]
注意:实际上, myfunc
是随机输出的耗时模拟(因此即使使用相同的参数我也需要多次重复该函数)并且我必须初始化一个列表是固有的存储结果
我怎样才能达到预期的输出?
所有变量都应该在 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)
我试图在 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)]]
这表明 myfun 在循环中的所有迭代中使用 a
= 2。
预期输出:
[[(2, 2, 2), (4, 4, 4)], [(3, 3, 3), (4, 4, 4)]]
注意:实际上, myfunc
是随机输出的耗时模拟(因此即使使用相同的参数我也需要多次重复该函数)并且我必须初始化一个列表是固有的存储结果
我怎样才能达到预期的输出?
所有变量都应该在 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)