码迷,mamicode.com
首页 > 其他好文 > 详细

异步调用与回调机制

时间:2018-06-19 16:26:36      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:机制   rom   usr   pytho   llb   one   mit   sub   current   

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/6/19 14:05
# @File    : 异步调用与回调机智.py


# 1、同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,在执行下一行代码,导致程序串行执行
# from concurrent.futures import ThreadPoolExecutor
# import time
# import random
#
#
# def la(name):
#     print(‘%s is laing‘ % 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 la l <%s> kg‘ % (name, size))
#
#
# if __name__ == ‘__main__‘:
#     pool = ThreadPoolExecutor(13)  # 限制池中数量
#     shit1 = pool.submit(la, ‘alex‘).result()
#     weigh(shit1)
#
#     shit2 = pool.submit(la, ‘wupeiqi‘).result()
#     weigh(shit2)
#
#     shit3 = pool.submit(la, ‘yuanhao‘).result()
#     weigh(shit3)

# 2、异步调用:提交完任务后,不等待任务执行完毕,

from concurrent.futures import ThreadPoolExecutor
import time
import random


def la(name):
    print(‘%s is laing‘ % 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 la l <%s> kg‘ % (name, size))


if __name__ == ‘__main__‘:
    pool = ThreadPoolExecutor(13)  # 限制池中数量
    pool.submit(la, ‘alex‘).add_done_callback(weigh)  # 前面任务执行完毕,自动触发weigh函数,把前面对象(pool.submit(la, ‘alex‘))传入
    pool.submit(la, ‘wupeiqi‘).add_done_callback(weigh)
    pool.submit(la, ‘yuanhao‘).add_done_callback(weigh)


异步调用与回调机制

标签:机制   rom   usr   pytho   llb   one   mit   sub   current   

原文地址:https://www.cnblogs.com/fmgao-technology/p/9198413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!