asyncio python中的非同步IO處理模組

2022-08-04 01:12:15 字數 3743 閱讀 7529

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內建的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 toprint_sum():print_sum()coroutine waits untilcompute()is completed before returning its result.

Python中的descriptor中的一點疑問

在我的印象中,類中的函式是可以有兩種呼叫方式的,如下 class b def func self return 10 b b b.func b.func b 於是,在之前研究descriptor的時候,我就有了幾點困惑 我將 更換成了如下兩個版本 版本1 import time class lazy...

python中的dict Python中的dict

dict python內建了字典 dict的支援,dict全稱dictionary,在其他語言中也稱為map,使用鍵 值 key value 儲存,具有極快的查詢速度。d print dict get michael d michael add a element d adam 67 print d...

zset中的score Redis中的事務

watch 監控某個或幾個key的變化 multi 接下來的命令不會立馬執行,會先放入乙個事務的佇列中 exec 執行事務佇列中的命令 unwatch 可以在watch執行之後 multi命令執行之前執行,效果是解除對某個key的監控 discard 可以在multi命令執行之後exec命令執行之前...