Asyncio.gather 与 asyncio.wait

新手上路,请多包涵

asyncio.gatherasyncio.wait 似乎有相似的用途:我有一堆我想执行/等待的异步事情(不一定要等待一个完成才能下一个开始) .他们使用不同的语法,并且在一些细节上有所不同,但对我来说,拥有两个在功能上有如此巨大重叠的函数似乎非常不符合 pythonic。我错过了什么?

原文由 Claude 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 574
2 个回答

虽然在一般情况下类似(“运行并获得许多任务的结果”),但每个函数在其他情况下都有一些特定的功能:

asyncio.gather()

返回一个 Future 实例,允许对任务进行高级分组:

 import asyncio
from pprint import pprint

import random

async def coro(tag):
    print(">", tag)
    await asyncio.sleep(random.uniform(1, 3))
    print("<", tag)
    return tag

loop = asyncio.get_event_loop()

group1 = asyncio.gather(*[coro("group 1.{}".format(i)) for i in range(1, 6)])
group2 = asyncio.gather(*[coro("group 2.{}".format(i)) for i in range(1, 4)])
group3 = asyncio.gather(*[coro("group 3.{}".format(i)) for i in range(1, 10)])

all_groups = asyncio.gather(group1, group2, group3)

results = loop.run_until_complete(all_groups)

loop.close()

pprint(results)

可以通过调用 group2.cancel() 甚至 all_groups.cancel() 取消组中的所有任务。另见 .gather(..., return_exceptions=True)

asyncio.wait()

支持在第一个任务完成后或指定超时后等待停止,允许较低级别的操作精度:

 import asyncio
import random

async def coro(tag):
    print(">", tag)
    await asyncio.sleep(random.uniform(0.5, 5))
    print("<", tag)
    return tag

loop = asyncio.get_event_loop()

tasks = [coro(i) for i in range(1, 11)]

print("Get first result:")
finished, unfinished = loop.run_until_complete(
    asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED))

for task in finished:
    print(task.result())
print("unfinished:", len(unfinished))

print("Get more results in 2 seconds:")
finished2, unfinished2 = loop.run_until_complete(
    asyncio.wait(unfinished, timeout=2))

for task in finished2:
    print(task.result())
print("unfinished2:", len(unfinished2))

print("Get all other results:")
finished3, unfinished3 = loop.run_until_complete(asyncio.wait(unfinished2))

for task in finished3:
    print(task.result())

loop.close()

原文由 Udi 发布,翻译遵循 CC BY-SA 4.0 许可协议

asyncio.waitasyncio.gather 级别低。

顾名思义, asyncio.gather 主要专注于收集结果。它等待一堆期货并以给定的顺序返回它们的结果。

asyncio.wait 等待期货。它不是直接给你结果,而是给你完成和待处理的任务。您必须手动收集这些值。

此外,您可以指定等待所有期货完成或仅使用 wait 完成第一个期货。

原文由 ospider 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题