Python:concurrent异步并行任务编程模块、 线程池、进程池、上下文管理

Python的concurrent包提供了高级的异步并行任务编程接口,包括ThreadPoolExecutor和ProcessPoolExecutor。ThreadPoolExecutor用于线程池,而ProcessPoolExecutor则用于进程池。concurrent模块支持上下文管理,使得使用with语句可以更方便地管理和关闭执行器。总结来说,这个模块简化了多线程和多进程编程,尽管无法直接设置线程名称。
摘要由CSDN通过智能技术生成

目录

concurrent包

ThreadPoolExecutor对象

ProcessPoolExecutor对象

支持上线文管理

总结



concurrent包

3.2版本引入的模块。
异步并行任务编程模块,提供一个高级的异步可执行的便利接口。

提供2个池执行器:
ThreadPoolExcentor   异步调用线程池的Executor
ProcessPoolExecutor 异步调用的进程池的Executor

ThreadPoolExecutor对象

首先需要定义一个池的执行器对象,Exector子类对象

方法 含义
ThreadPoolExector(max_workers=1) 池中至多创建max_workers个线程的池来同时异步执行,返回Executor实例
submit(fn,*args,**kwargs) 提交执行的函数及其参数,返回Future实例
shutdown(wait=True) 清理池

Future类

方法 含义
done() 如果调用被成功的取消或者执行完成,返回True
cancelled() 如果调用被成功的取消,返回True
running() 如果正在运行且不能被取消,返回True
cancel() 尝试取消调用,如果已经执行且不能取消返回False,否则返回True
result(timeout=None) 取消返回的结果,timeout为None,一直等待返回;timeout设置到期,抛出concurrent.futures.TimeoutError异常
exception(timeout=None) 取返回的异常,timeout为None,一直等待返回;timeout设置到期,抛出concurrent.futures.TimeoutError异常
#ThreadPoolExecutor例子
import threading
import logging
import time
from concurrent import futures

#输出定义
FORMAT='%(asctime)-15s\t [%(processName)s:%(threadName)s,%(process)d:%(thread)8d] %(message)s'
logging.basicConfig(level=logging.INFO,format=FORMAT)

def worker(n):
    logging.info("begin to work{}".format(n))
    time.sleep(5)
    logging.info("finished {}".format(n))

#创建线程池,池的容量为3
exect = futures.ThreadPoolExecutor(max_workers=3)
fs = []
for i in range(3):
    future = exect.submit(worker,i)
    fs.append(future)

for i in range(3,6):
    future = exect.submit(worker,i)

while True:
    time.sleep(2)
    logging.info(threading.enumerate())

    flag = True
    for _ in fs:   #判断是否还有任务未完成
        logging.info(_.done())
        flag = flag and _.done()
    print("="*30)

    if flag:
        exect.shutdown()  #清理池,池中线程全部杀掉
        logging.info(threading.enumerate())
        break

#线程池一旦创建了,就不需要在频繁清楚
结果:
2021-06-27 16:06:37,177	 [MainProcess:ThreadPoolExecutor-0_0,20060:    9812] begin to work0
2021-06-27 16:06:37,177	 [MainProcess:ThreadPoolExecutor-0_1,20060:    2816] begin to work1
2021-06-27 16:06:37,177	 [MainProcess:ThreadPoolExecutor-0_2,20060:   13268] begin to work2
2021-06-27 16:06:39,178	 [MainProcess:MainThread,20060:   26076] [<_MainThread(MainThread, started 26076)>, <Thread(ThreadPoolExecutor-0_0, started daemon 9812)>, <Thread(ThreadPoolExecutor-0_1, started daemon 2816)>, <Thread(ThreadPoolExecutor-0_2, started daemon 13268)>]
2021-06-2
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值