Python多处理池'raise ValueError("Pool not running") ValueError: Pool not running'函数带返回值

Zac*_*0ne 3 python return multiprocessing python-3.7

我正在尝试并行运行在循环中有返回值的函数。但它似乎停留在results = pool.map(algorithm_file.foo, population)for 循环的第二次迭代中

    raise ValueError("Pool not running")
ValueError: Pool not running
Run Code Online (Sandbox Code Playgroud)

示例代码:

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)
Run Code Online (Sandbox Code Playgroud)

里面的内容algorithm_file.py

from random import randint

def foo(x):
    return x * randint(0,5)
Run Code Online (Sandbox Code Playgroud)

我尝试放入pool = Pool(len(population))for 循环,但程序毫无例外地崩溃了。

我发现一些解决方案使用全局列表()。但无论如何,有没有办法维护具有返回值的函数呢?

Python 3.7.3

Moo*_*oot 10

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

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

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

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

for _ in range(10):
    with Pool(len(population)) as pool:
        results = pool.map(algorithm_file.foo, population)
        total.append(sum(results))
Run Code Online (Sandbox Code Playgroud)