异步任务VS协程 [英] Asyncio task vs coroutine

查看:23
本文介绍了异步任务VS协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读asyncio documentation时,我意识到我不了解一个非常基本和基本的方面:直接等待协同例程和等待包装在任务中的相同协同例程之间的区别。

在文档示例中,对say_after协程的两个调用在没有create_task等待时顺序运行,在create_task中包装时并发运行。所以我明白这基本上就是不同之处,这是一个相当重要的区别。

然而,让我困惑的是,在我到处阅读的示例代码中(例如,演示如何使用aiohttp),有许多地方等待(用户定义的)协程(通常在其他一些用户定义的协程中间),而不是包装在任务中,我想知道为什么会这样。确定何时应在任务中包装协程的标准是什么?

推荐答案

确定协程何时应包装在任务中的标准是什么?

如果希望协程在后台有效运行,则应使用任务。您看到的代码直接等待协同程序,因为它需要它们按顺序运行。例如,假设HTTP客户端发送请求并等待响应:

# these two don't make too much sense in parallel
await session.send_request(req)
resp = await session.read_response()

在某些情况下,您希望操作并行运行。在这种情况下,asyncio.create_task是合适的工具,因为它将执行协同程序的责任移交给事件循环。这允许您启动多个协同例程,并在它们执行时闲置,通常等待部分或全部完成:

dl1 = asyncio.create_task(session.get(url1))
dl2 = asyncio.create_task(session.get(url2))
# run them in parallel and wait for both to finish
resp1 = await dl1
resp2 = await dl2

# or, shorter:
resp1, resp2 = asyncio.gather(session.get(url1), session.get(url2))

如上所示,也可以等待任务。就像等待协同例程一样,这将挡路当前的协同例程,直到任务驱动的协同例程完成。与线程类似,等待任务大致等同于连接()线程(除非返回返回值)。再举一个例子:

queue = asyncio.Queue()

# read output from process in an infinite loop and
# put it in a queue
async def process_output(cmd, queue, identifier):
    proc = await asyncio.create_subprocess_shell(cmd)
    while True:
        line = await proc.readline()
        await queue.put((identifier, line))

# create multiple workers that run in parallel and pour
# data from multiple sources into the same queue
asyncio.create_task(process_output("top -b", queue, "top")
asyncio.create_task(process_output("vmstat 1", queue, "vmstat")

while True:
    identifier, output = await queue.get()
    if identifier == 'top':
        # ...

总而言之,如果您需要协程的结果才能继续,您只需等待它,而不创建任务,即:

# this is ok
resp = await session.read_response()
# unnecessary - it has the same effect, but it's
# less efficient
resp = await asyncio.create_task(session.read_reponse())

若要继续线程类比,创建任务只是为了立即等待它就像运行t = Thread(target=foo); t.start(); t.join(),而不是仅仅运行foo()-效率低下且多余。

这篇关于异步任务VS协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆