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試試:

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(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就可以由一個線程並發執行。

兩種開啟事件循環的方法

  • 一種方法是通過調用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:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM