多处理.Pool正常终止子进程

时间:2017-10-16 21:48:45

标签: python multiprocessing

我正在努力更好地控制我的流程池。我发现在池循环中调用break会调用pool.terminate()并强行终止子进程,但我希望让它们完成它们的块并优雅地退出。手册说我应该使用pool.close():close() Prevents any more tasks from being submitted to the pool.

测试过程:

chunks = range(7)
with Pool(2) as pool:
    ret = pool.imap_unordered(work, chunks)
    for reply in ret:
        info(reply)
        if reply == "processed 2":
           pool.close()

子进程:

def work(arg):
    sleep(1)
    return "processed {}".format(arg)

我希望在调用close()之后最多完成2个任务,但不会停止任何任务:

22:46:00 processed 0
22:46:00 processed 1 
22:46:01 processed 2
22:46:01 processed 3 
22:46:02 processed 4 
22:46:02 processed 5
22:46:03 processed 6

0 个答案:

没有答案