使用multiprocessing.Pool Python类异步调度顺序进程

时间:2015-03-10 08:52:14

标签: python asynchronous multiprocessing

我使用与Python multiprocessing.Pool类并行的可执行文件运行模拟,如下所示:

self._pool = Pool()

return self._pool.apply_async(run_executable, [],
    dict(simulator=self,
    params=params,
    command=self._command,
    results=self._results))

让我们说我们想在一台有4个CPU的计算机上运行5次模拟,然后(如果我理解的话)这些过程安排如下:

Multiprocessing with 5 processes and 4 CPUs

当我需要先前模拟的结果来启动具有调整参数的新模拟时,问题就出现了。如果我们使用与之前相同的数字并让仿真i.j+1跟随仿真i.j,那么对于我们有许多模拟等于CPU数量的简单情况,调度应该如下所示: / p>

Multiprocessing with follow up

我如何等待正确的过程完成,进行后处理,然后在异步模式下再次开始新的模拟? (我真的不在乎是否由同一个CPU完成,我只想使用可用的最大CPU功率)。

1 个答案:

答案 0 :(得分:0)

用这个替换你的代码并查看它的作用。

self._pool = Pool()

def process_ended_callback(result):
    print(self._command, "resulted in", result)

return self._pool.apply_async(run_executable, [],
    dict(simulator=self,
    params=params,
    command=self._command,
    results=self._results), 
    process_ended_callback)

它应该打印刚刚结束的命令。