asyncio是Python3.4版本引入的标准库,直接内置了对异步IO的支持。
asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
用asyncio实现Hello world代码如下:
import asyncio
@asyncio.coroutine
def hello():
print("Hello world!")
# 异步调用asyncio.sleep(1):
r = yield from asyncio.sleep(1)
print("Hello again!")
# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
@asyncio.corountine把一个generator标记为coroutine类型,然后,我们就把这个协程扔到EventLoop中执行。
hello()会首先打印出Hellow world!,然后,yield from语法可以让我们方便的调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(这里是None),然后接着执行下一个语句。
把asyncio.sleep(1)看成是一个耗时1秒的IO操作,在此期间,主线程并未等待,而失去执行EvenLoop中其它可以执行的coroutine了,因此也可以实现并发执行。
我们用Task封装两个coroutine试试:
import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
结果:
Hello world! (<_mainthread started>)
Hello world! (<_mainthread started>)
(暂停约1秒)
Hello again! (<_mainthread started>)
Hello again! (<_mainthread started>)
由打印的线程名称可以看出,两个coroutine是由同一个线程并发执行的。
如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。
两种开启事件循环的方法
一种方法是通过调用run_until_complete()
另外一种就是调用run_forever()
run_until_complete内置的add_done_callback()。使用run_forever()的好处就是可以自定义add_done_callback()方法,具体差异:
run_until_complete()
import asyncio
async def sloww_operation(future):
await asyncio.sleep(1)
future.set_result('Future is done!')
#得到一个标准的事件循环
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(future))
print(loop.is_running())
loop.run_until_complete(future)
print(future.result())
loop.close()
run_forever()
run_forever相比run_until_complete()的优势是添加了一个add_done_callback()可以让我们在task(future)完成的时候调用相应的方法进行后续的处理:
import asyncio
async def slow_operation(future):
await asyncio.sleep(1)
future.set_result('Future is dong!')
def got_result(future):
print(future.result())
loop.stop()
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(future))
future.add_done_callback(got_result)
try:
loop.run_forever()
finally:
loop.close()
example Chain Coroutine
import asyncio
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
compute() is chained to print_sum(): print_sum() coroutine waits until compute() is completed before returning its result.
Sequence diagram of the example: