目录
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