asyncio python中的异步IO处理模块

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()
  • 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:
相关文章
相关标签/搜索