progress pid: None progress pid: 3391 do something in sub_progress main progress finished
当然也可以使用继承的方式,重写内部的 run 方法,这部分和多线程中的代码类似。
进程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import time import multiprocessing
defdo_something(n): time.sleep(n) print("do something in sub_progress") return n
if __name__ == '__main__': # using a pool to manage process pool = multiprocessing.Pool(multiprocessing.cpu_count()) result = pool.apply_async(do_something, args=(3,))
# waiting all tasks finished # must close a pool before join it, for new task added to pool pool.close() pool.join() print(result.get())
输出如下:
1 2 3
❯ python multiprocessing_test.py do something in sub_progress 3
pool 中还有 imap 方法,类似线程中 excuter.map 方法,result 为每个函数的返回值:
1 2 3 4 5 6 7
# 进入顺序 for result in pool.imap(do_something, [1, 3, 5]): print(f"do something in {result}s")
# 完成顺序 for result in pool.imap_unordered(do_something, [1, 3, 5]): print(f"do something in {result}s")
输出如下:
1 2 3 4 5 6 7
❯ python multiprocessing_test.py do something in sub_progress do something in 1s do something in sub_progress do something in 3s do something in sub_progress do something in 5s