• 异步调用与回调机制


    # 提交任务的俩方式
      #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(函数),称为回调机制
  • 相关阅读:
    JUC 1
    给定一个随机数生成器randm(),获得randn()
    堆与优先队列
    集合与映射
    二分搜索树
    链表
    栈与队列
    PostgreSQL ALTER TABLE 命令
    postgresql修改自增序列
    SQL 删除重复行,只保留一条记录
  • 原文地址:https://www.cnblogs.com/yuexijun/p/11631833.html
Copyright © 2020-2023  润新知