Python 多处理池 'raise ValueError("Pool not running") ValueError: Pool not running' function with return value

问题描述 投票:0回答:1

我正在尝试并行运行在循环中具有返回值的函数。 但在 for 循环的第二次迭代中,它似乎陷入了

results = pool.map(algorithm_file.foo, population)

    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

python multiprocessing return python-3.7
1个回答
10
投票

我认为问题是一旦关闭泳池,就无法再次使用它。这就是为什么第一次迭代顺利进行,但在第二次迭代时出现“池未运行”错误的原因。

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

for _ in range(10):
    pool = Pool(len(population))
    results = pool.map(algorithm_file.foo, population)
    pool.close()
    pool.join()
    total.append(sum(results))

但是,请注意,(在我看来)使用池作为上下文管理器更加优雅和Pythonic,即

for _ in range(10):
    with Pool(len(population)) as pool:
        results = pool.map(algorithm_file.foo, population)
        total.append(sum(results))
© www.soinside.com 2019 - 2024. All rights reserved.