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

为何任务完成后asyncio.Future.done()仍未设为True?

问题原因解析

你的代码里用了time.sleep(),这是阻塞式的同步休眠,会直接卡住主线程,连带着asyncio的事件循环也会被彻底阻塞,没法执行任何异步任务的回调处理。

具体流程拆解:

  1. 调用loop.run_in_executor后,线程池启动test函数,开始sleep 5秒。
  2. 主线程执行第一个time.sleep(3),此时事件循环完全停摆,3秒后打印状态,此时test还没结束,所以done()返回False。
  3. test在第5秒结束并打印ending test,但此时主线程还在第二个time.sleep(3)的阻塞中(从第3秒持续到第6秒),事件循环没法运转,自然无法处理线程池任务完成后的回调,也就不会把result的状态标记为done。
  4. 直到第二个sleep结束,执行await result时,事件循环才重新启动,处理了线程完成的通知,把result标记为done,所以此时done()返回True。

如果要让状态及时更新,把所有time.sleep()换成await asyncio.sleep()——这种异步休眠不会阻塞事件循环,休眠期间事件循环仍能处理其他任务,包括线程完成的回调。

修改后的示例代码:

import asyncio
from concurrent.futures.thread import ThreadPoolExecutor
from time import sleep

_executor = ThreadPoolExecutor(max_workers=32)

def test():
    print('starting test')
    sleep(5)
    print('ending test')

async def main():
    loop = asyncio.get_running_loop()
    result = loop.run_in_executor(_executor, test)

    await asyncio.sleep(3)
    print('sleep 1 complete')
    print(f'{result.done()=}')

    await asyncio.sleep(3)
    print('sleep 2 complete')
    print(f'{result.done()=}')

    print('await result')
    await result
    print(f'{result.done()=}')

asyncio.run(main())

运行结果会变成:

starting test
sleep 1 complete
result.done()=False
ending test
sleep 2 complete
result.done()=True
await result
result.done()=True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:52:08