【问题标题】:Can't understand the point of async in this code. Is this how it supposed to work?无法理解这段代码中异步的意义。这是它应该如何工作的吗?
【发布时间】:2019-06-05 19:16:22
【问题描述】:

我正在尝试使用 asyncio lib 尝试让我的代码“同时”发出 3 个 HTTP GET/POST 请求,以便尽快获得响应。 (有时一个或另一个请求会延迟,最终会延迟下一个请求。)

所以我去了 asyncio docs,发现了这个例子:https://docs.python.org/3/library/asyncio-task.html#coroutines

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

我实际上是为自己适应的,但它似乎没有任何帮助,只是让代码更复杂而没有任何好处。

在测试示例代码时(上图)我假设如果我增加第一个 say_after() 的延迟时间,第二个将首先打印

    await say_after(5, 'hello') #5 seconds of sleep before print
    await say_after(2, 'world')

然而,它没有。回报是:

16:04:30 开始

你好

世界

16:04:37结束

那么这个 asyncio 代码的目的是什么?我可以在没有 async 的情况下得到相同的结果:

def say_after_b(delay, what):
    time.sleep(delay)
    print(what)

def main_b():
    print(f"started at {time.strftime('%X')}")

    say_after_b(5, 'hello')
    say_after_b(2, 'world')

    print(f"finished at {time.strftime('%X')}")

main_b()

返回:

16:04:37 开始

你好

世界

16:04:44 结束

在我看来,随着时间的增加,异步代码应该是这样的:

sleep 1 sec > sleep 2 sec > print('world') > sleep 3 sec > sleep 4 sec > sleep 5 sec > print('hello') > End.

我的假设错了吗?

【问题讨论】:

    标签: python-3.x asynchronous async-await python-asyncio


    【解决方案1】:

    阅读您提到的文档中的一个额外段落。

    在您引用的示例代码上方,它清楚地说明了

    下面的sn-p代码会在等待1秒后打印“hello”,再等2秒后打印“world”

    下一个例子是

    同时运行两个 say_after 协程

    (提示:您需要创建任务以同时运行协程)

    【讨论】:

    • 可能发生在任何人身上:-)
    猜你喜欢
    • 2017-10-04
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2018-10-29
    • 1970-01-01
    • 2013-01-05
    • 2011-05-16
    相关资源
    最近更新 更多