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相关实用技能,欢迎点击关注。

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

 

 

你可能感兴趣的:(Python基础知识)