【问题标题】:Building a set of tasks with asyncio, but total time takes longer than longest task使用 asyncio 构建一组任务,但总时间比最长任务花费的时间长
【发布时间】:2022-11-02 01:59:02
【问题描述】:

在以下代码中,当我使用 asyncio 时,为什么需要 10(0+1+2+3+4) 秒而不是 4 秒才能完成?

import asyncio,time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(f"what = {what}, at {time.strftime('%X')}")


background_tasks = set()

async def main():
    for i in range(5):
        task = asyncio.create_task(say_after(delay=i,what=i))
        
        # Add task to the set. This creates a strong reference.
        background_tasks.add(task)
        
        await task
        
        # To prevent keeping references to finished tasks forever,
        # make each task remove its own reference from the set after
        # completion:
        task.add_done_callback(background_tasks.discard) # discard is a set method.
        
if __name__=="__main__":
    asyncio.run(main())

结果在图片中。

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    在循环外执行任务

    import asyncio,time
    
    async def say_after(delay, what):
        await asyncio.sleep(delay)
        print(f"what = {what}, at {time.strftime('%X')}")
    
    
    background_tasks = set()
    
    async def main():
        for i in range(5):
            task = asyncio.create_task(say_after(delay=i,what=i))
            
            # Add task to the set. This creates a strong reference.
            background_tasks.add(task)
            
        await task
        
        # To prevent keeping references to finished tasks forever,
        # make each task remove its own reference from the set after
        # completion:
        task.add_done_callback(background_tasks.discard) # discard is a set method.
            
    if __name__=="__main__":
        asyncio.run(main())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 2017-11-15
      相关资源
      最近更新 更多