You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Python Threading Executor shutdown方法wait参数的疑问

Executor.shutdown 中 wait=True 与 wait=False 的核心区别

两者的本质差异仅在于shutdown()方法本身的返回时机,而非已提交的 futures 是否会执行完成——不管wait取值如何,所有已提交的任务都会执行完毕,程序也必须等它们全部完成才会退出。具体区别如下:

当 wait=True 时

调用shutdown(wait=True)后,当前线程会阻塞:

  • 直到所有待处理的 futures 执行完成
  • 且执行器的资源(如线程池里的线程)被完全释放
  • 之后shutdown()方法才会返回,后续代码才能继续执行

当 wait=False 时

调用shutdown(wait=False)后,shutdown()方法会立即返回,当前线程可以马上执行后续代码。但执行器会在后台等待所有 futures 执行完成后,再自动释放资源。


代码示例对比

示例1:wait=True 的阻塞行为

from concurrent.futures import ThreadPoolExecutor
import time

def task(num):
    time.sleep(1)
    print(f"任务 {num} 完成")

executor = ThreadPoolExecutor(max_workers=2)
for i in range(3):
    executor.submit(task, i)

print("调用 shutdown(wait=True)")
executor.shutdown(wait=True)
print("shutdown 完成")  # 这行要等所有任务结束后才会打印

运行输出顺序:

调用 shutdown(wait=True)
任务 0 完成
任务 1 完成
任务 2 完成
shutdown 完成

示例2:wait=False 的非阻塞行为

from concurrent.futures import ThreadPoolExecutor
import time

def task(num):
    time.sleep(1)
    print(f"任务 {num} 完成")

executor = ThreadPoolExecutor(max_workers=2)
for i in range(3):
    executor.submit(task, i)

print("调用 shutdown(wait=False)")
executor.shutdown(wait=False)
print("shutdown 方法已返回,开始执行其他工作...")  # 这行立刻打印
time.sleep(2)  # 模拟后续业务逻辑
print("所有工作结束")

运行输出顺序:

调用 shutdown(wait=False)
shutdown 方法已返回,开始执行其他工作...
任务 0 完成
任务 1 完成
任务 2 完成
所有工作结束


内容的提问来源于stack exchange,提问作者learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:54:18