首页 > 解决方案 > ProcessPoolExecutor 因大量任务而死锁

问题描述

我正在尝试使用 ProcessPoolExecutor 在 256 核 Ubuntu Linux 机器上运行多个相同的短任务。这些任务是独立的,不共享任何资源。

我用252核初始化ProcessPoolExector,并提交大量任务(100K到100万)

我得到的是任务开始运行,但是在大约 1000 个任务之后,主进程卡住了,不再执行任务

这在不同的机器上重现(具有相同数量的核心)

一个示例程序:

from concurrent.futures import ProcessPoolExecutor
from time import sleep

import multiprocessing as mp


def run_function(id):
    for i in range(int(1e5)):
        i += 1
    print(f"{id}  Done!")


if __name__ == "__main__":
    proc_count = 252

    mp_ctx = mp.get_context('spawn')

    executor = ProcessPoolExecutor(max_workers=proc_count, mp_context=mp_ctx)
    futures = []

    for i in range(int(1e6)):
        task_future = executor.submit(run_function, i)
        futures.append(task_future)

    while not all([f.done() for f in futures]):
        sleep(2)

它是 ProcessPoolExecutor 中的错误吗?该文档缺少对此类限制的描述。

我有一个解决方法,其中包括使用原始 python 多处理对象实现进程池,但我更喜欢了解 ProcessPoolExecutor 并正确使用它

标签: pythonpython-multiprocessingdeadlockconcurrent.futures

解决方案


推荐阅读