装饰器版协程
import threading
import asyncio
#①添加装饰器之后函数变为协程
@asyncio.coroutine
def hello():
print('Hello world! (tid: %s)' % threading.currentThread().ident)
yield from asyncio.sleep(3) # 模拟异步执行耗时任务。yield from从后面的可迭代对象中返回东西
print('Hello again! (tid:%s)' % threading.currentThread().ident)
yield from asyncio.sleep(2)
print('Hello again2! (tid:%s)' % threading.currentThread().ident)
@asyncio.coroutine
def bye():
print('bye (tid:%s)' % threading.currentThread().ident)
yield from asyncio.sleep(1)
print('bye again! (tid:%s)' % threading.currentThread().ident)
yield from asyncio.sleep(1)
print('bye again2! (tid:%s)' % threading.currentThread().ident)
#②下面这些与async异步模式协程一致。
loop = asyncio.get_event_loop()
tasks = [hello(), bye()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()