【问题标题】:Dynamically add new tasks after gather(*tasks)gather(*tasks) 后动态添加新任务
【发布时间】:2022-12-10 17:11:40
【问题描述】:

例如这段代码:

async def f1(num):
    while True:
        print(num)
        await asyncio.sleep(2)

class ExampleClass:
  def __init__():
     self.tasks = []

  async def main():
    for i in range(10):
        tasks.append(asyncio.create_task(f1(i)))
    await asyncio.gather(*tasks)

  def add_new_task(task):
      self.tasks.append(task)

然后我在外面的某个地方打电话

ExampleClass.add_new_task(task)

我需要的是添加新任务并与现有任务异步执行。

也许我应该使用任何其他结构来实现我想要的? 重要的是我的任务可能需要永远执行(永远轮询)

【问题讨论】:

    标签: python async-await concurrency python-asyncio gather


    【解决方案1】:

    asyncio.gather 函数对于这样的任务来说并不是很方便。但是,你可以看看asyncio.TaskGroup,它是在 Python3.11 中发布的,可以更轻松地动态添加新任务。

    import asyncio
    from concurrent.futures import wait, FIRST_COMPLETED
    
    
    async def main():
        async with asyncio.TaskGroup() as group:
            # Create some tasks
            tasks = [
                group.create_task(asyncio.sleep(1.0))
                for _ in range(10)
            ]
            
            # Wait for some tasks to finish
            done, tasks = await wait(tasks, return_when=FIRST_COMPLETED)
    
            # Add more tasks (/! `tasks` is now a set)
            tasks.add(group.create_task(asyncio.sleep(2.0)))
           
           # Wait the rest to complete 
            await asyncio.gather(*tasks)
    
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多