当前位置: 首页 > 后端技术 > Python

Python的线程池是如何判断所有的任务是否都执行完了呢?

时间:2023-03-25 21:17:45 Python

fromloguruimportloggerimportthreadingimporttimefromconcurrent.futuresimportThreadPoolExecutorpool=ThreadPoolExecutor(max_workers=100)var=0lock=threading.Lock()deffoo():globalvargloballockwithlock:ifvar<10:time.sleep(2)#模拟网络IO操作,比如操作数据库,或者请求接口var+=1for_inrange(100):pool.submit(foo)pool.shutdown(wait=True)#等待所有任务执行完logger.debug(f'Thelast{var}')非常简单。提交任务后,只需使用pool.shutdown(wait=True)等待所有任务执行完毕即可。wait参数可以看官方代码注释:defshutdown(self,wait=True,*,cancel_futures=False):"""清理Executor关联的资源,多次调用这个方法是安全的次。否则,在此之后不能调用其他方法。Args:wait:如果为真,则关闭将不会返回,直到所有正在运行的期货都已完成执行并且执行者使用的资源已被回收。cancel_futures:如果为真然后关闭将取消所有未决的期货。已完成或正在运行的期货不会被取消。"""passIfTruethenshutdownwillnotreturnuntilallrunningfutureshavefinishedexecutionhavebeenreclaimed.执行者已被收回。