主要知识点
- 同步调用:会等进程执行完才会执行下一个进程(串行)
- 异步调用:简单理解就是并行
- 回调函数:pool.submit().add_done_callback(funcname) ,参数为要执行的函数名,在并行的情况解决了函数需要传递函数的问题,接受参数的函数内部,需要使用 res.result() 来取值,不然是一个对象。
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os, time, random
def make(name):
print('pid:%s 开始了 name:%s' % (os.getpid(), name))
time.sleep(1)
res = random.randint(1,3)
return res
def eat(res):
res = res.result() # 拿到结果
print('eat %s ' % res)
if __name__ == '__main__':
f = ThreadPoolExecutor(2)
#f = ProcessPoolExecutor(2)
name = ['a', 'b', 'c', 'd']
for i in name:
f.submit(make, i).add_done_callback(eat) # 回调函数 add_done_callback(func)
f.shutdown() # 在完成设定的数量后,结束线程池,默认参数为wait=True 结束后不能再次发任务