zoukankan      html  css  js  c++  java
  • 异步调用与回调机制

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

    """

    同步调用和阻塞不一样:

    同步调用不管是io型程序还是计算型程序,执行一个程序之后就是等待,

    阻塞是io型特有的,因为io耗时而形成了阻塞现象

    """

    # 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)
    View Code

    # 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)
    View Code




  • 相关阅读:
    Java数据处理,Map中数据转double并取小数点后两位
    19年7月份面试7家公司,整理的java面试题(答案自行百度解决,也是个学习的过程)
    2019阿里云面试题,竟然现场敲代码,现在的企业越来越实在了
    解决win10状态栏的搜索框无法搜索本地应用或无反应
    sql,按照时间排序,取前N条
    List数组排序
    阿里云的maven仓库 地址
    hashcode相等两个类一定相等吗?equals呢?相反呢?
    杂记
    java排序
  • 原文地址:https://www.cnblogs.com/fmgao-technology/p/9198413.html
Copyright © 2011-2022 走看看