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

asyncio.gather底层工作原理:任务并发执行逻辑疑问

asyncio.gather() 底层工作机制解析

一、参数的初始处理逻辑

  • asyncio.gather()会对每个传入的参数调用asyncio._ensure_future()做统一处理:
    • 若参数已是Future对象,直接返回该对象;
    • 若参数是可等待的协程对象,会通过loop.create_task(arg)将其包装为Task;
    • 若参数本身是asyncio.create_task()创建的Task,此步骤几乎不会执行额外操作。

二、返回的_GatheringFuture对象

  • gather()最终返回一个_GatheringFuture类的实例,该对象内部维护一个children列表,存储所有经_ensure_future()处理后的Future/Task对象。
  • _GatheringFuture自身逻辑简洁,仅实现了cancel()方法,用于批量取消所有子任务。

三、Future.__await__与并发执行的核心

  • _GatheringFuture继承自futures.Future,理解并发的关键在于Future.__await__方法:
    def __await__(self):
        if not self.done():
            self._asyncio_future_blocking = True
            yield self  # This tells Task to wait for completion.
        if not self.done():
            raise RuntimeError("await wasn't used with future")
        return self.result()  # May raise too.
    
  • 这里的yield self并不是直接实现并发,而是将控制权交还给事件循环:
    1. 当你await gather(...)时,事件循环会先调度children列表里的所有Task(未启动的会被启动);
    2. 任意Task执行到await语句时,会暂停执行并把控制权交回事件循环,此时事件循环会转而运行其他就绪的Task;
    3. _GatheringFuture会监听所有子Task/Future的完成状态,只有当所有子对象都完成后,它才会标记自身为done状态,此时__await__方法才会返回所有子任务的结果集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:36:20