python中可异步执行的多进程、多线程模块concurrent.futures

官方文档:https://pythonhosted.org/futures/

中文文档:https://docs.python.org/zh-cn/3/library/concurrent.futures.html

什么是concurrent.futures

concurrent.futures模块为异步执行可调用函数提供了一个高级接口。

异步执行可以由使用ThreadPoolExecutor的线程执行,也可以使用ProcessPoolExecutor分离进程。两者都实现相同的接口,该接口由抽象执行器类Executor定义。

Executor是一个抽象类,它提供异步执行调用的方法。不应该直接使用它,而是通过它的两个子类:ThreadPoolExecutor和ProcessPoolExecutor。

 

本质上:

concurrent.futures依赖于multiprocessing和threading库,只不过封装后,更方便使用这两个库,写法上更简单,也方便于多线程和多进程的代码转换。

 

线程池和进程池的用法:

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from multiprocessing import current_process
from threading import current_thread
import time,os,random


def task(i):
    print(f'{current_thread().name} 在运行 任务{i}')  # 这里把具体的线程名称标记出来
    # print(f'{current_process().name} 在运行 任务{i}') # 这是进程的名称
    time.sleep(2)
    return i**2

if __name__ == '__main__':
    start = time.time()
    pool = ThreadPoolExecutor(max_workers=5)  # 这里用多线程,如果是多进程,只需要把这里换成ProcessPoolExecutor(max_workers=5)
    fu_list = []
    for i in range(20):
        future = pool.submit(task,i)
        print('拿到了',i,future.result())  # 注意:这里不print的话就是异步的,如果print,那么需要等待task函数return,也就做不到异步了
        fu_list.append(future)
    pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
    for i in fu_list:
        print(i.result())  # 注意,需要.result() 方法才能得到返回的数据
    print('耗时',time.time()-start)



    # 更精简的写法是:
    # start = time.time()
    # pool = ThreadPoolExecutor(5)
    # fu_list =  [pool.submit(task,i) for i in range(20)]
    # pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
    # result = [i.result() for i in fu_list]
    # print(result)
    # print('耗时',time.time()-start)

 

更多python相关实用技能,欢迎点击关注。

所有文章亲测有效再分享,希望对你有所帮助。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值