问题在最下面!
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import threading, asyncio, time
@asyncio.coroutine
def sleep1():
print("Am I being executed concurrently?")
#yield from asyncio.sleep(3)
time.sleep(1)
yield
@asyncio.coroutine
def hello(n):
print(n,'Hello world! (%s)' % threading.currentThread())
yield from sleep1()
print(n,'Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop() # 获得时间循环
tasks = [hello(n) for n in range(1,5)] # 布置任务
loop.run_until_complete(asyncio.wait(tasks)) # 开始执行
loop.close()
输出结果:
2 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
1 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
3 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
4 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
2 Hello again! (<_MainThread(MainThread, started 13608)>)
1 Hello again! (<_MainThread(MainThread, started 13608)>)
3 Hello again! (<_MainThread(MainThread, started 13608)>)
4 Hello again! (<_MainThread(MainThread, started 13608)>)
问题:4个协程hello的:hello world! 为什么没有并发输出? 而是等了 sleep1() ?
重新补充:
我清楚 time.sleep 无法异步,只能串行。这个没有问题。
但是 yield from sleep1(),遇到 yield 按照协程的规则,当前协程等待 sleep1()返回,但控制权应该交给其他协程继续运行啊??
我期待的结果是 4个hello world 迅速输出然后 阻塞的 sleep 依次等待。然后 4个 hello again 输出。这也是串行的,单线程。应该符合协程的规则。
time.sleep改成asyncio.sleep