• 异步调用与回调机制


    # 提交任务的俩方式
      #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(函数),称为回调机制
  • 相关阅读:
    多媒体基础知识之PCM数据
    FFmpeg在Linux下编译使用
    AndroidStudio 中使用FFMPEG
    Android 音频播放分析笔记
    【Linux 命令】- more和less
    【Linux】- 简明Vim练习攻略
    【Linux】- 对find,xargs,grep和管道的一些理解
    【Linux 命令】- find 命令
    【Linux 命令】- tar 命令
    【Linux】- CentOS7 下 安装 supervisor
  • 原文地址:https://www.cnblogs.com/yuexijun/p/11631833.html
Copyright © 2020-2023  润新知