首页 > 解决方案 > 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

标签: pythonmultiprocessingreturnpython-3.7

解决方案


我认为问题是一旦关闭池,就不能再次使用它。这就是为什么第一次迭代顺利进行,但在第二次迭代中你得到“池未运行”。

因此,修复提供的代码段的一种方法是在每次迭代时实例化一个新池:

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))

推荐阅读