欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 线程池 异步调用与回调机制

程序员文章站 2022-06-12 20:06:02
...

#提交任务的两种方式

#1、同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码,导致程序是串行执行

#线程池
from concurrent.futures import ThreadPoolExecutor
import time
import random

def mai(name):
    print('%s is mai' %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(mai,'nihao').result()
    weigh(shit1)

    shit2=pool.submit(mai,'buqingchu').result()
    weigh(shit2)

    shit3=pool.submit(mai,'buzhidao').result()
    weigh(shit3)

python 线程池 异步调用与回调机制

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


if __name__ == '__main__':
    pool=ThreadPoolExecutor(13)
    #谁拉完自己去调用称重的方法   add_done_callback()前面的任务运行完毕,这是回调函数自动触发(当参数自动穿进去)
    pool.submit(la,'nihao').add_done_callback(weigh)

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

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

python 线程池 异步调用与回调机制