如何确保终止多处理池?

How to ensure termination of a multiprocessing Pool?

我正在使用 Jupyter notebook 从 multiprocessing.Pool 中发起各种废话。不幸的是,有时我的工作人员会出错,我需要关闭池,然后重新开始。

所以,我有一个包含行 pool.close() 的单元格。然后我重新生成一个新池:pool = Pool(n, maxtasksperchild=1),然后继续我的快乐之路。

但是,.close()访问池并没有像我想的那样,现在我的机器上有无数的僵尸。更糟糕的是,我覆盖了 pool 变量,所以我无法关闭它们,除非手动发出 kill 命令。更糟糕的是,当我对其中一个僵尸发出 kill 命令时,一个新的僵尸出现在它的位置,让我怀疑 pool.close() 实际上并没有关闭池,池仍然在那里,隐藏在某个地方,即使在死亡中继续执行它的 map_async 命令,这将需要 2 永远终止。

换句话说,pool.close() 没有关闭我的池。

我要坐在这里 kill 一个小时。与此同时,有谁知道如何:

pool.kill_all_of_the_processes_really_farill_this_time_and_prevent_them_from_ever_popping_back_up_under_any_circumstances_ever()


这是一个工作示例:

单元格 1

import multiprocessing as mp
def work(i):
    import time
    while True:
        time.sleep(0.01)

单元格 2

try: 
    pool.close()
except: 
    pass
pool = mp.Pool(8, maxtasksperchild=1)
pool.map_async(work, range(10000000))

重新运行Cell2,ps aux | grep python | wc -l可以看到打开的进程数增加了8

documentation 中所述:

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

terminate() Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.

所以你应该使用 terminate(),如果你想真正杀死所有进程而不是等待它们。

关于您的评论: 您可以尝试使用以下命令终止进程(另请参阅 here):

kill -9 $(ps aux | grep -v grep | grep "<your search string>" | awk '{print }')

对我来说,python 解释器的路径是独一无二的,因为我是在 virtualenv 中启动它的。您可以使用它来仅过滤 jupyter python 进程。