【问题标题】:python 3 asyncio: coroutines execution order using run_until_complete(asyncio.wait(corutines_list))python 3 asyncio:使用 run_until_complete(asyncio.wait(corutines_list)) 的协程执行顺序
【发布时间】:2017-03-30 19:51:09
【问题描述】:

我有一个可能很无用的问题,但我觉得我错过了一些可能对理解 asyncio 工作原理很重要的东西。

我刚开始熟悉 asyncio,并编写了这段非常基本的代码:

import asyncio
import datetime
from random import randint


async def coroutine(i):
    start = datetime.datetime.now()
    print('coroutine {} started.'.format(i))
    n = randint(1, 11)
    await asyncio.sleep(n)
    end = datetime.datetime.now()
    print('coroutine {} finished after {} with random = {}.'.format(i, (end-start).seconds, n))
    return i


def simple():
    loop = asyncio.get_event_loop()
    cors = [coroutine(x) for x in range(20)]
    loop.run_until_complete(asyncio.wait(cors))


if __name__ == '__main__':
    simple()

这是我得到的一个结果:

coroutine 3 started.
coroutine 9 started.
coroutine 15 started.
coroutine 4 started.
coroutine 10 started.
coroutine 16 started.
coroutine 1 started.
coroutine 5 started.
coroutine 11 started.
coroutine 17 started.
coroutine 2 started.
coroutine 6 started.
coroutine 12 started.
coroutine 18 started.
coroutine 0 started.
coroutine 7 started.
coroutine 13 started.
coroutine 19 started.
coroutine 8 started.
coroutine 14 started.
coroutine 7 finished after 1 with random = 1.
coroutine 12 finished after 2 with random = 2.
coroutine 3 finished after 3 with random = 3.
coroutine 5 finished after 3 with random = 3.
coroutine 0 finished after 3 with random = 3.
coroutine 10 finished after 4 with random = 4.
coroutine 17 finished after 4 with random = 4.
coroutine 2 finished after 5 with random = 5.
coroutine 16 finished after 6 with random = 6.
coroutine 18 finished after 6 with random = 6.
coroutine 15 finished after 7 with random = 7.
coroutine 9 finished after 8 with random = 8.
coroutine 1 finished after 8 with random = 8.
coroutine 6 finished after 8 with random = 8.
coroutine 11 finished after 9 with random = 9.
coroutine 8 finished after 9 with random = 9.
coroutine 4 finished after 10 with random = 10.
coroutine 13 finished after 10 with random = 10.
coroutine 19 finished after 10 with random = 10.
coroutine 14 finished after 10 with random = 10.

现在,我的问题是:为什么协程以乱序开始? 我期待看到一个有序的“协程 x 开始”消息,从协程 0 到协程 20……直到那时我才认为他们会因为随机的睡眠时间而争吵……我错过了什么?

【问题讨论】:

    标签: python-3.5 python-asyncio coroutine


    【解决方案1】:

    .wait() 规范无法确定该顺序。

    你不应该关心它。

    实际上所有的协程都是在同一个循环迭代中启动的,几乎是在同一时间。

    【讨论】:

    • 感谢您的回复。您能否将我引用的规范链接到提到 .wait() 不确定的规范?我一直在寻找这样的提示,但没有任何运气!文档字符串也非常少。
    • 好吧,它从未明确说明过,但也不能保证任何顺序。另见非常相似的question about gather()
    • @AndrewSvetlov 如果订单很重要怎么办?假设您希望 2 个协程同时运行,但协程 A 需要先运行才能将变量添加到工作环境,以便协程 B 可以使用它。
    • await func1(); await func2() 是简单明了的答案
    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多