close 和join的顺序是不能变的,而且必须要有close和join’这两个函数少一个都不行。close函数的作用是改变进程池的状态当改变完进程池的状态的时候我们就不能向进程池添加进程了,join是阻塞主进程一直到所有子进程完成后才继续运行主进程。
from multiprocessing import Pool
import os
import time
import random
"""
Waiting for all
Task 0 (pid=8980) is running ...
Task 1 (pid=7204) is running ...
Task 2 (pid=18836) is running ...
Task 2 end
Task 3 (pid=18836) is running ...
Task 3 end
Task 4 (pid=18836) is running ...
Task 0 end
Task 5 (pid=8980) is running ...
Task 1 end
Task 4 end
Task 5 end
Finished
"""
def run_task(name):
print("Task %s (pid=%s) is running ..."%(name,os.getpid()))
time.sleep(random.random()*3)
print("Task %s end"%name)
if __name__ == "__main__":
print("Current process is %s"%os.getcwd())
p = Pool(processes=3)
for i in range(5):
p.apply_async(run_task,args=(i,))
print("Waiting for all")
# 如果没有进程池close 调用join()会报错 assert self._state in (CLOSE, TERMINATE)
# 没有 close 和join 进程池都没法用
# p.apply_async(run_task, args=(5,))
# 从这里我们可以看出 其实 close就是把进程池的状态给改变了在这之后就不能再
# 向进程池添加进程了
p.close()
# 如果把启动进程放到close 会报错
# ValueError: Pool not running
p.apply_async(run_task, args=(5,))
p.join()
print("Finished")