首页 > 解决方案 > 当活动作业数量小于 N 时添加新任务

问题描述

我正在尝试在一定数量的内核上并行化一些非常耗时的任务。我的目标是尽可能地利用服务器资源。CPU 的总数为 20,但要执行的任务数量要多得多(例如,100)。

每个任务运行的时间不同,因此下面的代码为一定数量的内核留下了空闲而没有工作的机会。

import multiprocessing as mp


def some_task(*args):
    # Something happening here
    pass


cpu_count = mp.cpu_count()
p = mp.Pool(cpu_count)

n_thread = 1
for something in somethings:

    p.apply_async(some_task, args=(something, ))

    if n_thread == cpu_count:
        p.close()
        p.join()
        p = mp.Pool(cpu_count)
        n_thread = 1
        continue
    n_thread += 1

p.close()
if n_thread != 1:
    p.join()

当活动作业的数量少于 CPU 的数量时,如何编写将启动新任务的代码?

标签: pythonmultiprocessingpython-multiprocessing

解决方案


推荐阅读