[Python]异步wait和gather

发布时间 2023-03-30 17:29:17作者: LeoShi2020

相同点:

  • 从功能上看, asyncio.wait 和 asyncio.gather 实现的效果是相同的。
    不同点:
  • 使用方式不一样,wait需要传一个可迭代对象,gather传多个元素
  • wait比gather更底层,gather可以直接得到结果,wait先得到future再得到结果
  • wait可以通过设置timeout和return_when来终止任务
  • gather可以给任务分组,且支持组级别的取消任务
import asyncio


async def f1():
    print(1)
    await asyncio.sleep(3)
    print(2)
    return "f1"


async def f2():
    print(3)
    await asyncio.sleep(3)
    print(4)
    return "f2"


async def main():
    group1 = asyncio.gather(f1(), f1())
    group2 = asyncio.gather(f2(), f2())
    group1.cancel()
    all_groups = await asyncio.gather(group1, group2, return_exceptions=True)
    print(all_groups)


asyncio.run(main())

'''
3
3
4
4
[CancelledError(), ['f2', 'f2']]
'''