提交任务的两种方式
#1、同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码,导致程序是串行执行
#2、异步调用:提交完任务后,不地等待任务执行完毕
同步调用:
from concurrent.futures import ThreadPoolExecutor import random import time def la(name): print(name,‘正在拉。。。。‘) res = random.randint(0, 10) time.sleep(res) return {‘name‘: name, ‘res‘: res} def weight(obj): print(‘%s 拉了 %s kg!‘ % (obj[‘name‘], obj[‘res‘])) if __name__ == ‘__main__‘: pool = ThreadPoolExecutor(3) # 同步调用,等待执行结果 # eggon = pool.submit(la, ‘eggon‘).result(timeout=2) eggon = pool.submit(la, ‘eggon‘).result() pool.submit(weight(eggon)) alex = pool.submit(la, ‘alex‘).result() pool.submit(weight(eggon))
运行结果:
eggon 正在拉。。。。 eggon 拉了 5 kg! alex 正在拉。。。。 eggon 拉了 5 kg!
异步调用与回调机制:
from concurrent.futures import ThreadPoolExecutor import random import time def la(name): print(name,‘正在拉。。。。‘) res = random.randint(0, 10) time.sleep(res) return {‘name‘: name, ‘res‘: res} def weight(obj): # print(obj) # obj是pool.submit(la, ‘eggon‘)的对象,要获取结果需要obj.result()获取函数la的返回值 obj = obj.result() print(‘%s 拉了 %s kg!‘ % (obj[‘name‘], obj[‘res‘])) if __name__ == ‘__main__‘: pool = ThreadPoolExecutor(3) # 异步调用,不等待执行结果,继续执行下一行代码 # pool.submit(la, ‘eggon‘).add_done_callback(weight) 意思是: # 执行函数la # 执行结果后,把pool.submit(la, ‘eggon‘)对象当作weight的参数 # 再执行weight函数。 pool.submit(la, ‘eggon‘).add_done_callback(weight) #回调add_done_callback函数weight的参数是pool.submit(la, ‘eggon‘)对象,所以weight只能有一个参数 pool.submit(la, ‘alex‘).add_done_callback(weight)
执行结果:
eggon 正在拉。。。。 alex 正在拉。。。。 <Future at 0x103da2f98 state=finished returned dict> eggon 拉了 8 kg! <Future at 0x103f609b0 state=finished returned dict> alex 拉了 8 kg!
原文地址:https://www.cnblogs.com/beallaliu/p/9192528.html
时间: 2024-10-12 19:58:44