首页 > 其他 > 详细

异步调用与回调机制

时间:2019-10-07 20:20:19      阅读:116      评论:0      收藏:0      [点我收藏+]
# 提交任务的俩方式
  #1,同步调用:提交完任务,在原地等待任务执行完毕,拿到结果,再执行下一段代码,导致程序串行执行
import time, random
from concurrent.futures import ThreadPoolExecutor
def la(name):
    print(%s 在拉屎!%name)
    time.sleep(random.randint(3,5))
    res = random.randint(7, 13) * #
    return {name:name, res: res}

def weigh(shit):
    name = shit[name]
    size = len(shit[res])
    print(%s拉了%skg屎%(name, size))
if __name__ == __main__:
    pool = ThreadPoolExecutor(13)
    shit1 = pool.submit(la, alex).result()
    print(shit1)
    weigh(shit1)
    shit2 = pool.submit(la, wupeqi).result()
    weigh(shit2)
    shit3 = pool.submit(la, yuanhao).result()
    weigh(shit3)


  #2,异步调用

import time, random
from concurrent.futures import ThreadPoolExecutor
def la(name):
    print(%s 在拉屎!%name)
    time.sleep(random.randint(3,5))
    res = random.randint(7, 13) * #
    return {name:name, res: res}

def weigh(shit):
    shit = shit.result()
    name = shit[name]
    size = len(shit[res])
    print(%s拉了%skg屎%(name, size))
if __name__ == __main__:
    pool = ThreadPoolExecutor(13)
    shit1 = pool.submit(la, alex).add_done_callback(weigh)
    shit2 = pool.submit(la, wupeqi).add_done_callback(weigh)
    shit3 = pool.submit(la, yuanhao).add_done_callback(weigh)
#add_done_callback(函数),称为回调机制

 

异步调用与回调机制

原文:https://www.cnblogs.com/yuexijun/p/11631833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!