代码之家  ›  专栏  ›  技术社区  ›  Koklushkin

如何按X一次运行中的任务列表?等待每组完成

  •  0
  • Koklushkin  · 技术社区  · 3 年前

    我有一组1000项任务。

    import asyncio
    
    async def my_task(x):
        await asyncio.sleep(0.1)
        print(f"done: {x}")
    
    
    async def main():
        my_tasks = []
        for x in range(1000):
            my_tasks.append(lambda: my_task)         
    
        # ???
        # how to scoop up the consequent 10 out of `my_tasks`
        # to execute them asyncronously?
        # and then wait for them?
        # 
    
        # ??
        # asyncio.create_task(my_task())
        # pending = asyncio.all_tasks()
        # group = asyncio.gather(*pending, return_exceptions=True)
        # await group
    

    我想管理他们 10乘10。 也就是说,一次10个。然后等待他们(10个)完成,然后再跑10个,以此类推。

    怎么做?

    1 回复  |  直到 3 年前
        1
  •  1
  •   partyguy11    3 年前

    您可以通过使用asyncio.gather以10个为一组的方式同时运行任务来实现这一点。以下是如何修改主函数以实现此目的的示例:

    import asyncio
    
    async def my_task(x):
        await asyncio.sleep(0.1)
        print(f"done: {x}")
    
    async def main():
        my_tasks = [my_task(x) for x in range(1000)]
    
        # Run tasks in groups of 10
        for i in range(0, len(my_tasks), 10):
            group = my_tasks[i:i+10]
            await asyncio.gather(*group)
    
    asyncio.run(main())
    

    这段代码创建了一个1000个任务的列表,然后以10步为一步进行迭代。对于每组10个任务,它使用asyncio.gather并行运行它们,并等待它们完成后再进入下一组。

    注意:在一些python代码编辑器(如googlecolab笔记本)中,您应该使用 await main() 而不是 asyncio.run(main())