当前位置:   article > 正文

Python-4.27 异步调用与回调机制_python concurrent.futures 提交任务后不等待任务执行成功

python concurrent.futures 提交任务后不等待任务执行成功

提交任务的两种方式:

  • 同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码,程序是串行执行
import random
import time
from concurrent.futures import ThreadPoolExecutor


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 拉了 《%s》kg' % (name, size))


if __name__ == '__main__':
    pool = ThreadPoolExecutor(13)

    shit1 = pool.submit(la, 'allen').result()
    weigh(shit1)

    shit2 = pool.submit(la, 'winnie').result()
    weigh(shit2)

    shit3 = pool.submit(la, 'vivian').result()
    weigh(shit3)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 异步调用:提交完任务后,不地等待任务执行完毕
import random
import time
from concurrent.futures import ThreadPoolExecutor


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 拉了 《%s》kg' % (name, size))


if __name__ == '__main__':
    pool = ThreadPoolExecutor(13)

    pool.submit(la, 'allen').add_done_callback(weigh)

    pool.submit(la, 'winnie').add_done_callback(weigh)

    pool.submit(la, 'vivian').add_done_callback(weigh)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/102650
推荐阅读
相关标签
  

闽ICP备14008679号