关于python:Python的线程池如何判断任务是否全部执行完毕

from loguru import logger
import threading
import time
from concurrent.futures import ThreadPoolExecutor


pool = ThreadPoolExecutor(max_workers=100)

var = 0

lock=threading.Lock()


def foo():
    global var
    global lock
    with lock:
        if var < 10:
            time.sleep(2) # 模拟网咯 IO 操作,比方操作数据库,或者申请接口
            var += 1


for _ in range(100):
    pool.submit(foo) 

pool.shutdown(wait=True) # 期待所有工作执行结束

logger.debug(f'最初的 {var}')

很简略,在提交完工作之后,只用 pool.shutdown(wait=True) 期待所有工作执行结束

对于 wait 参数,能够看官网的代码正文:

def shutdown(self, wait=True, *, cancel_futures=False):
    """Clean-up the resources associated with the Executor.

    It is safe to call this method several times. Otherwise, no other
    methods can be called after this one.

    Args:
        wait: If True then shutdown will not return until all running
            futures have finished executing and the resources used by the
            executor have been reclaimed.
        cancel_futures: If True then shutdown will cancel all pending
            futures. Futures that are completed or running will not be
            cancelled.
    """
    pass

If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.

翻译一下就是:

如果是 “True”,那么在所有正在运行的期货实现执行和执行器应用的资源被回收之前,敞开将不会返回。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理