栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Asyncio.gather vs asyncio.wait

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Asyncio.gather vs asyncio.wait

尽管在一般情况下类似(“为许多任务运行并获取结果”),但是对于其他情况,每个功能都有一些特定的功能:

[
asyncio.gather()
](https://docs.python.org/3/library/asyncio-

task.html#asyncio.gather)

返回一个Future实例,允许高层任务分组:

import asynciofrom pprint import pprintimport randomasync def coro(tag):    print(">", tag)    await asyncio.sleep(random.uniform(1, 3))    print("<", tag)    return tagloop = 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()
](https://docs.python.org/3/library/asyncio-

task.html#asyncio.wait)

支持在第一个任务完成后或在指定的超时后等待停止,从而降低了操作的精度:

import asyncioimport randomasync def coro(tag):    print(">", tag)    await asyncio.sleep(random.uniform(0.5, 5))    print("<", tag)    return tagloop = 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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641236.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号