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

ThreadPoolExecutor单任务超时处理:如何确保所有任务执行完成

解决方案:ThreadPoolExecutor 单个任务超时不终止其他任务

原代码使用exe.map()的timeout参数时,该超时是针对整个迭代流程的——一旦某个任务触发超时,会直接抛出TimeoutError,且ThreadPoolExecutor的上下文管理器会立即关闭线程池,终止所有未完成的任务,导致第四个任务无法执行。

要实现单个任务超时提示、其他任务正常执行的需求,需要放弃map()方法,改用submit()逐个提交任务,单独处理每个任务的超时:

import time
from concurrent.futures import ThreadPoolExecutor, TimeoutError

def sleeping(i):
    time.sleep(i)
    return f'slept {i} seconds'

with ThreadPoolExecutor(max_workers=1) as exe:
    # 提交所有任务并保存对应的Future对象
    task_futures = [exe.submit(sleeping, duration) for duration in [1, 2, 10, 3]]
    
    # 逐个处理每个任务的结果
    for future in task_futures:
        try:
            # 为单个任务设置超时时间
            result = future.result(timeout=5)
            print(result)
        except TimeoutError:
            print('Timeout waiting for task')

代码说明

  1. 使用exe.submit()提交每个任务,返回的Future对象可以单独跟踪任务状态和结果。
  2. 遍历Future列表时,对每个任务调用result(timeout=5),仅针对当前任务设置超时。
  3. 单个任务触发超时后,捕获TimeoutError并打印提示,后续任务仍会继续处理,直到所有任务完成。

运行该代码后,输出与期望一致:

slept 1 seconds
slept 2 seconds
Timeout waiting for task
slept 3 seconds

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:31:00