ProcessPoolExecutor用起来很简单,完全可以当成一个小模块使用,使用时通过submit函数注册需要调用的work函数,然后通过add_done_callback注册需要回调结果的函数when_done即可,当work被进程执行完成后,结果会通过回调when_done返回
demo代码如下:
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
processpool的小用例
"""
from concurrent.futures import ProcessPoolExecutor
import time
def when_done(r):
for x in r.result():
print("Got", x)
def work(x):
time.sleep(3)
a = set()
a.add(x)
return a
def run_one_process():
with ProcessPoolExecutor() as pool:
future_result = pool.submit(work, "ccc")
future_result.add_done_callback(when_done)
print("with end.")
print("run one end.")
if __name__ == '__main__':
run_one_process()
print("main end.")
结果如下:
with end.
Got b
Got a
Got ccc
run one end.
main end.
可以看出在没有退出with之前,进程尚未启动,退出with后进程启动并阻塞,看到进程结束回调完成,然后运行print(“run one end.”)
此种场景针对那种需要并发执行,尽可能利用cpu很有用处。要知道python的线程很难利用多核的优势。
实际使用在大型项目中,由于with一退出就会阻塞到执行结束,所以一般需要配合apscheduler模块进行,使得在一个异步中阻塞,不致于影响整个主线程