python - Python multiprocessing Pool 'raise ValueError("Pool not running") ValueError: Pool not running' 函数返回值
问题描述
我正在尝试并行运行具有循环返回值的函数。但它似乎停留在results = pool.map(algorithm_file.foo, population)
for 循环的第二次迭代中
raise ValueError("Pool not running")
ValueError: Pool not running
示例代码:
from multiprocessing.dummy import Pool
import algorithm_file
population = [1, 3, 4]
pool = Pool(len(population))
total = list()
for _ in range(10):
results = pool.map(algorithm_file.foo, population)
pool.close()
pool.join()
total.append(sum(results))
print(total)
里面的内容algorithm_file.py
from random import randint
def foo(x):
return x * randint(0,5)
我尝试放入pool = Pool(len(population))
for 循环,但程序在中途崩溃,没有异常。
我发现一些解决方案使用全局列表()。但是有没有办法用返回值来维护函数呢?
Python 3.7.3
解决方案
我认为问题是一旦关闭池,就不能再次使用它。这就是为什么第一次迭代顺利进行,但在第二次迭代中你得到“池未运行”。
因此,修复提供的代码段的一种方法是在每次迭代时实例化一个新池:
for _ in range(10):
pool = Pool(len(population))
results = pool.map(algorithm_file.foo, population)
pool.close()
pool.join()
total.append(sum(results))
但是,请注意,将池用作上下文管理器(IMO)更优雅和 Pythonic,即
for _ in range(10):
with Pool(len(population)) as pool:
results = pool.map(algorithm_file.foo, population)
total.append(sum(results))
推荐阅读
- javascript - 过滤列中值以下的数据表函数
- dart - 如何在 Dart lang 中获取客户端的 URI/URL?
- sql - 如何在循环查询中以 JSON 形式返回结果?
- node.js - 在 react 和 nodejs 中实时更新
- javascript - 根据日期显示图像
- xslt - XSLT - 删除根节点和第一个子节点并将大子节点作为根节点
- arrays - 空数组情况是否需要 if 语句?
- python - 来自 (x, y, z) 数据的 Plotly 热图
- reactjs - React Router - 登录前和登录后的结构导航栏
- css - Flexbox 单元的大小未调整到包含的 flexbox 单元