2016-11-16 73 views
3

我有什麼可能是一個毫無用處的問題,但我覺得我錯過了解可能對了解asyncio如何工作很重要的事情。python 3 asyncio:使用run_until_complete(asyncio.wait(corutines_list))執行協程執行順序

我剛開始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. 

現在,我的問題是:爲什麼在協程開始以混亂的順序開始? 我期待看到從協程0到協程20的有序「協同x開始」消息...只有當我認爲他們會因爲隨機睡眠時間而爭奪...我錯過了什麼?

回答

1

訂單是由.wait()規範undevemenistic。

你不應該關心它。

實際上,所有協程都是在幾乎同一時間的同一循環迭代中啓動的。

+0

感謝您的回覆。你能否把我提到的那個提到的.wait()是不確定的規範的引用連接起來?沒有任何運氣,我一直在尋找相當多的提示。另外文檔字符串非常小。 – Bertone

+0

那麼,它從來沒有明確說過,但也沒有保證任何順序。 另請參見非常相似[關於gather()]的問題(https://github.com/python/asyncio/issues/432) –