Asyncio.gather 与 asyncio.wait [英] Asyncio.gather vs asyncio.wait
问题描述
asyncio.gather
和 asyncio.wait
似乎有类似的用途:我有一堆异步的东西要执行/等待(不一定要在下一个开始之前等待一个完成).它们使用不同的语法,并且在一些细节上有所不同,但对我来说,拥有两个功能上有如此巨大重叠的函数似乎非常不符合 Python 风格.我错过了什么?
asyncio.gather
and asyncio.wait
seem to have similar uses: I have a bunch of async things that I want to execute/wait for (not necessarily waiting for one to finish before the next one starts). They use a different syntax, and differ in some details, but it seems very un-pythonic to me to have 2 functions that have such a huge overlap in functionality. What am I missing?
推荐答案
虽然在一般情况下类似(运行并获得许多任务的结果"),但每个函数对于其他情况都有一些特定的功能:
Although similar in general cases ("run and get results for many tasks"), each function has some specific functionality for other cases:
返回一个 Future 实例,允许对任务进行高级分组:
Returns a Future instance, allowing high level grouping of tasks:
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)
,
All tasks in a group can be cancelled by calling group2.cancel()
or even all_groups.cancel()
. See also .gather(..., return_exceptions=True)
,
支持在第一个任务完成后或指定超时后等待停止,允许较低级别的操作精度:
Supports waiting to be stopped after the first task is done, or after a specified timeout, allowing lower level precision of operations:
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()
这篇关于Asyncio.gather 与 asyncio.wait的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!