Python multiprocessing Pool 'raise ValueError("Pool not running") ValueError: Pool not running' function with return value

Python multiprocessing Pool 'raise ValueError("Pool not running") ValueError: Pool not running' function with return value

我正在尝试 运行 在循环中具有 return 值的并行函数。 但是它似乎在

的 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 循环中,但程序在中途崩溃,无一例外。

我发现一些解决方案使用 global list()。但是无论如何,是否可以使用 return 值来维护功能?

Python 3.7.3

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

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

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