异步调用及回调函数

主要知识点

  1. 同步调用:会等进程执行完才会执行下一个进程(串行)
  2. 异步调用:简单理解就是并行
  3. 回调函数:pool.submit().add_done_callback(funcname) ,参数为要执行的函数名,在并行的情况解决了函数需要传递函数的问题,接受参数的函数内部,需要使用 res.result() 来取值,不然是一个对象。
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os, time, random


def make(name):
    print('pid:%s 开始了 name:%s' % (os.getpid(), name))
    time.sleep(1)
    res = random.randint(1,3)
    return res


def eat(res):
    res = res.result()  # 拿到结果
    print('eat  %s ' % res)


if __name__ == '__main__':
    f = ThreadPoolExecutor(2)
    #f = ProcessPoolExecutor(2)
    name = ['a', 'b', 'c', 'd']
    for i in name:
        f.submit(make, i).add_done_callback(eat)  # 回调函数 add_done_callback(func)

    f.shutdown() # 在完成设定的数量后,结束线程池,默认参数为wait=True 结束后不能再次发任务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值