异步调用与回调机制
同步调用与异步调用指提交任务的方式就
同步调用:提交完任务后就在原地等待任务执行完,拿到结果再执行下一步任务,导致程序串行执行
from concurrent.futures import ThreadPoolExecutor import time,random def la(name): print("%s is laing" % name) time.sleep(random.randrange(3,5)) res=random.randint(3,17)*"#" return {'name':name,'res':res} def weight(shit): name=shit['name'] size=len(shit['res']) print("%s la <%s>kg"%(name,size)) if __name__=="__main__": pool=ThreadPoolExecutor(10) shit1=pool.submit(la,'user1').result()#wait run weight(shit1) shit2=pool.submit(la,'user2').result()#wait run weight(shit2) shit3 = pool.submit(la, 'user3').result() # wait run weight(shit3)
异步调用:提交完任务后,不在原地等待任务执行完毕
from concurrent.futures import ThreadPoolExecutor import time,random def la(name): print("%s is laing" % name) time.sleep(random.randrange(3,5)) res=random.randint(3,17)*"#" return {'name':name,'res':res} def weight(shit): shit=shit.result()#result() return func value name=shit['name'] size=len(shit['res']) print("%s la <%s>kg"%(name,size)) if __name__=="__main__": pool=ThreadPoolExecutor(10) pool.submit(la,'user1').add_done_callback(weight)#bind callback func pool.submit(la,'user2').add_done_callback(weight) pool.submit(la, 'user3').add_done_callback(weight)
user1 is laing
user2 is laing
user3 is laing
user1 la <12>kg
user2 la <14>kg
user3 la <10>kg
阻塞与非阻塞:进程运行的一种状态,同步调用和阻塞没有任何关系。