在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡安全/ 關于協(xié)程coroutine的執(zhí)行順序問題

關于協(xié)程coroutine的執(zhí)行順序問題

import threading
import asyncio
import time

@asyncio.coroutine
def hello(n):
    print("-----")
    time.sleep(3)
    print("======")
    print(n,'Hello world! (%s)' % threading.currentThread())
    yield from asyncio.sleep(1) # 異步調用asyncio.sleep(1):  
    print(n,'Hello again! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()  # 獲取EventLoop:
h1 = hello(1)
h2 = hello(2)
tasks = [h1,h2]
loop.run_until_complete(asyncio.wait(tasks)) # 執(zhí)行coroutine
loop.close()

運行結果:

-----
======
2 Hello world! (<_MainThread(MainThread, started 4328)>)
-----
======
1 Hello world! (<_MainThread(MainThread, started 4328)>)
2 Hello again! (<_MainThread(MainThread, started 4328)>)
1 Hello again! (<_MainThread(MainThread, started 4328)>)

問題: 為什么 2 hello world 先被輸出了??

回答
編輯回答
拼未來

異步,順序是由操作系統(tǒng)決定啊, 是不一定的,你再運行一次沒準就不一樣了.

在我的機器上看到的是

$ python3 thread_test.py 
-----
======
1 Hello world! (<_MainThread(MainThread, started 140735704728384)>)
-----
======
2 Hello world! (<_MainThread(MainThread, started 140735704728384)>)
1 Hello again! (<_MainThread(MainThread, started 140735704728384)>)
2 Hello again! (<_MainThread(MainThread, started 140735704728384)>)

要想解釋原因需要知道三個時間

一個時CPU切換上下文時間~1000ns
http://blog.tsunanet.net/2010...

一個是線程打印一個字符串的時間~100us
https://stackoverflow.com/que...

一個是CPU時間給每個線程的時間片~1ms
https://www.javamex.com/tutor...

整個過程執(zhí)行時間很容易遇到線程上下文切換從而改變執(zhí)行的先后順序,但這個過程并不是隨機的, 但同一臺機器上很可能多次重復的都是同一種順序.

2018年9月14日 04:01