0
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)) # 执行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 先被输出了??

落叶 155
2017-12-29 提问
1 个回答
0

异步,顺序是由操作系统决定啊, 是不一定的,你再运行一次没准就不一样了.

在我的机器上看到的是

$ 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...

整个过程执行时间很容易遇到线程上下文切换从而改变执行的先后顺序,但这个过程并不是随机的, 但同一台机器上很可能多次重复的都是同一种顺序.

撰写答案

推广链接