python - 如何在 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
随机输出是耗时的模拟(因此即使使用相同的参数,我也需要多次重复该函数)并且我必须初始化一个列表来存储结果是固有的
我怎样才能达到预期的输出?
解决方案
所有变量都应该在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)
推荐阅读
- scala - 在 Apache Spark 的 Scala API 中,使用单引号和 $"" 表示法有区别吗?
- css - 菜单图标垂直对齐
- javascript - 尝试获取数组的平均值时没有得到输出
- c++ - C/C++:结构如何包含指向自身的指针?
- libgit2sharp - 如何使用 LibGit2Sharp 获取文件夹的最后一次提交?
- ios - iOS 将 UITableViewCell.isSelected 设置为 true,导致未调用委托方法
- python - 如何在 Python 中以“年龄:18”格式显示来自 Python 列表的信息
- java - 仅将两个文本大文件与 Java 中的 URL 与外部存储器进行比较?
- bash - Bash 新手的问题:成功安装 CMake GUI 后如何启动 CMake GUI
- python - 从网站读取特定内容并使用 python 显示