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
试试:async
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()
结果:oop
Hello world! (<_MainThread(MainThread, started 140735195337472)>) Hello world! (<_MainThread(MainThread, started 140735195337472)>) (暂停约1秒) Hello again! (<_MainThread(MainThread, started 140735195337472)>) Hello again! (<_MainThread(MainThread, started 140735195337472)>)
由打印的线程名称能够看出,两个coroutine
是由同一个线程并发执行的。线程
若是把asyncio.sleep()
换成真正的IO操做,则多个coroutine
就能够由一个线程并发执行。code
- 一种方法是经过调用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()
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()
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.事件