Python 3.6.8 - multiprocessing.Pool.apply_async() 不工作

Python 3.6.8 - multiprocessing.Pool.apply_async() not working

它似乎 apply_async 不工作,没有任何反应。不知道这里出了什么问题。我正在使用 MacOS catalina

import time
from multiprocessing import Pool

def worker(sl):
    print(sl)
    time.sleep(sl)
    return sl

if __name__ == '__main__':
    with Pool(processes=3) as pool:
        for i in range(5,30,5):
            result = pool.apply_async(func=worker,args=(i,))

当您调用 pool.apply_async 时,您正在安排一项任务 运行。该调用的 return 值是一个 multiprocessing.pool.AsyncResult 实例,您在该实例上调用方法 get 将阻塞,直到任务完成,并将 return 为 return 值来自 apply_async 方法调用中指定的辅助函数。但是您还没有在任何这些 AsyncResult 实例上调用 get(或 wait)。相反,您让自己 立即 跌落到 with Pool(processes=3) as pool: 块的末尾,这就是您的问题。

文档不是很明确。但是,有这个警告:

Warning: multiprocessing.pool objects have internal resources that need to be properly managed (like any other resource) by using the pool as a context manager or by calling close() and terminate() manually. Failure to do this can lead to the process hanging on finalization.

由于 with 语句,您 正在 使用池作为上下文管理器,而实际发生的是 with 完成时阻止对 pool.terminate() 的调用。因此,池中的所有进程在有机会 运行 您提交的任何任务之前都会立即终止。

由于您对 worker 中的实际 return 值不感兴趣,因此保存 AsyncResult 对象并对其调用 get 的替代方法是调用 pool.close() 后跟 pool.join(),然后退出 with 块,它将等待所有提交的任务完成:

close() Prevents any more tasks from being submitted to the pool. Once all the tasks have been completed the worker processes will exit.

join() Wait for the worker processes to exit. One must call close() or terminate() before using join().

import time
from multiprocessing import Pool

def worker(sl):
    print(sl)
    time.sleep(sl)
    return sl

if __name__ == '__main__':
    with Pool(processes=3) as pool:
        for i in range(5,30,5):
            result = pool.apply_async(func=worker,args=(i,))
        pool.close()
        pool.join()

打印:

5
10
15
20
25