共计 1028 个字符,预计需要花费 3 分钟才能阅读完成。
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”,那么在所有正在运行的期货实现执行和执行器应用的资源被回收之前,敞开将不会返回。
正文完