前言
書接上文,本文造第三個輪子,也是asyncio包里面非常常用的一個函式gather
一、知識準備
● 相對于前兩個函式,gather的使用頻率更高,因為它支持多個協程任務“同時”執行
● 理解__await__ __iter__的使用
● 理解關鍵字async/await,async/await是3.5之后的語法,和yield/yield from異曲同工
● 今天的文章有點長,請大家耐心看完
二、環境準備
| 組件 | 版本 |
|---|---|
| python | 3.7.7 |
三、
gather的實作
先來看下官方gather的使用方法:
|># more main.py
import asyncio
async def hello():
print('enter hello ...')
return 'return hello ...'
async def world():
print('enter world ...')
return 'return world ...'
async def helloworld():
print('enter helloworld')
ret = await asyncio.gather(hello(), world())
print('exit helloworld')
return ret
if __name__ == "__main__":
ret = asyncio.run(helloworld())
print(ret)
|># python3 main.py
enter helloworld
enter hello ...
enter world ...
exit helloworld
['return hello ...', 'return world ...']
來看下造的輪子的使用方式:
? more main.py
import wilsonasyncio
async def hello():
print('enter hello ...')
return 'return hello ...'
async def world():
print('enter world ...')
return 'return world ...'
async def helloworld():
print('enter helloworld')
ret = await wilsonasyncio.gather(hello(), world())
print('exit helloworld')
return ret
if __name__ == "__main__":
ret = wilsonasyncio.run(helloworld())
print(ret)
? python3 main.py
enter helloworld
enter hello ...
enter world ...
exit helloworld
['return hello ...', 'return world ...']
自己造的輪子也很好的運行了,下面我們來看下輪子的代碼
四、代碼決議
輪子代碼
1)代碼組成
|># tree
.
├── eventloops.py
├── futures.py
├── main.py
├── tasks.py
├── wilsonasyncio.py
| 檔案 | 作用 |
|---|---|
| eventloops.py | 事件回圈 |
| futures.py | futures物件 |
| tasks.py | tasks物件 |
| wilsonasyncio.py | 可呼叫方法集合 |
| main.py | 入口 |
2)代碼概覽:
eventloops.py
| 類/函式 | 方法 | 物件 | 作用 | 描述 |
|---|---|---|---|---|
| Eventloop | 事件回圈,一個執行緒只有運行一個 | |||
__init__ |
初始化兩個重要物件 self._ready 與 self._stopping |
|||
self._ready |
所有的待執行任務都是從這個佇列取出來,非常重要 | |||
self._stopping |
事件回圈完成的標志 | |||
call_soon |
呼叫該方法會立即將任務添加到待執行佇列 | |||
run_once |
被run_forever呼叫,從self._ready佇列里面取出任務執行 |
|||
run_forever |
死回圈,若self._stopping則退出回圈 |
|||
run_until_complete |
非常重要的函式,任務的起點和終點(后面詳細介紹) | |||
create_task |
將傳入的函式封裝成task物件,這個操作會將task.__step添加到__ready佇列 |
|||
Handle |
所有的任務進入待執行佇列(Eventloop.call_soon)之前都會封裝成Handle物件 |
|||
__init__ |
初始化兩個重要物件 self._callback 與 self._args |
|||
self._callback |
待執行函式主體 | |||
self._args |
待執行函式引數 | |||
_run |
待執行函式執行 | |||
get_event_loop |
獲取當前執行緒的事件回圈 | |||
_complete_eventloop |
將事件回圈的_stopping標志置位True |
|||
run |
入口函式 | |||
gather |
可以同時執行多個任務的入口函式 | 新增 | ||
_GatheringFuture |
將每一個任務組成串列,封裝成一個新的類 | 新增 |
tasks.py
| 類/函式 | 方法 | 物件 | 作用 | 描述 |
|---|---|---|---|---|
| Task | 繼承自Future,主要用于整個協程運行的周期 | |||
__init__ |
初始化物件 self._coro ,并且call_soon將self.__step加入self._ready佇列 |
|||
self._coro |
用戶定義的函式主體 | |||
__step |
Task類的核心函式 | |||
__wakeup |
喚醒任務 | 新增 | ||
ensure_future |
如果物件是一個Future物件,就回傳,否則就會呼叫create_task回傳,并且加入到_ready佇列 |
futures.py
| 類/函式 | 方法 | 物件 | 作用 | 描述 |
|---|---|---|---|---|
| Future | 主要負責與用戶函式進行互動 | |||
__init__ |
初始化兩個重要物件 self._loop 與 self._callbacks |
|||
self._loop |
事件回圈 | |||
self._callbacks |
回呼佇列,任務暫存佇列,等待時機成熟(狀態不是PENDING),就會進入_ready佇列 |
|||
add_done_callback |
添加任務回呼函式,狀態_PENDING,就虎進入_callbacks佇列,否則進入_ready佇列 |
|||
set_result |
獲取任務執行結果并存盤至_result,將狀態置位_FINISH,呼叫__schedule_callbacks |
|||
__schedule_callbacks |
將回呼函式放入_ready,等待執行 |
|||
result |
獲取回傳值 | |||
__await__ |
使用await就會進入這個方法 | 新增 | ||
__iter__ |
使用yield from就會進入這個方法 | 新增 |
3)執行程序
3.1)入口函式
main.py
if __name__ == "__main__":
ret = wilsonasyncio.run(helloworld())
print(ret)
ret = wilsonasyncio.run(helloworld())使用run,引數是用戶函式helloworld(),進入run,run的流程可以參考上一小節run-->run_until_complete
3.2)事件回圈啟動,同之前
3.3)第一次回圈run_forever --> run_once
- 將
_ready佇列的內容(即:task.__step)取出來執行,這里的coro是helloworld()
def __step(self, exc=None):
coro = self._coro
try:
if exc is None:
result = coro.send(None)
else:
result = coro.throw(exc)
except StopIteration as exc:
super().set_result(exc.value)
else:
blocking = getattr(result, '_asyncio_future_blocking', None)
if blocking:
result._asyncio_future_blocking = False
result.add_done_callback(self.__wakeup, result)
finally:
self = None
__step較之前的代碼有改動result = coro.send(None),進入用戶定義函式
async def helloworld():
print('enter helloworld')
ret = await wilsonasyncio.gather(hello(), world())
print('exit helloworld')
return ret
ret = await wilsonasyncio.gather(hello(), world()),這里沒啥可說的,進入gather函式
def gather(*coros_or_futures, loop=None):
loop = get_event_loop()
def _done_callback(fut):
nonlocal nfinished
nfinished += 1
if nfinished == nfuts:
results = []
for fut in children:
res = fut.result()
results.append(res)
outer.set_result(results)
children = []
nfuts = 0
nfinished = 0
for arg in coros_or_futures:
fut = tasks.ensure_future(arg, loop=loop)
nfuts += 1
fut.add_done_callback(_done_callback)
children.append(fut)
outer = _GatheringFuture(children, loop=loop)
return outer
loop = get_event_loop()獲取事件回圈def _done_callback(fut)這個函式是回呼函式,細節后面分析,現在只需要知道任務(hello()與world())執行完之后就會回呼就行for arg in coros_or_futuresfor回圈確保每一個任務都是Future物件,并且add_done_callback將回呼函式設定為_done_callback,還有將他們加入到_ready佇列等待下一次回圈調度- 3個重要的變數:
? ? ? ?children里面存放的是每一個異步任務,在本例是hello()與world()
? ? ? ?nfuts存放是異步任務的數量,在本例是2
? ? ? ?nfinished存放的是異步任務完成的數量,目前是0,完成的時候是2 - 繼續往下,來到了
_GatheringFuture,看看原始碼:
class _GatheringFuture(Future):
def __init__(self, children, *, loop=None):
super().__init__(loop=loop)
self._children = children
_GatheringFuture最主要的作用就是將多個異步任務放入self._children,然后用_GatheringFuture這個物件來管理,需要注意,這個物件繼承了Future- 至此,
gather完成初始化,回傳了outer,其實就是_GatheringFuture - 總結一下
gather,初始化了3個重要的變數,后面用來存放狀態;給每一個異步任務添加回呼函式;將多個異步子任務合并,并且使用一個Future物件去管理
3.3.1)gather完成,回到helloworld()
async def helloworld():
print('enter helloworld')
ret = await wilsonasyncio.gather(hello(), world())
print('exit helloworld')
return ret
ret = await wilsonasyncio.gather(hello(), world())gather回傳_GatheringFuture,隨后使用await,就會進入Future.__await__
def __await__(self):
if self._state == _PENDING:
self._asyncio_future_blocking = True
yield self
return self.result()
- 由于
_GatheringFuture的狀態是_PENDING,所以進入if,遇到yield self,將self,也就是_GatheringFuture回傳(這里注意yield的用法,流程控制的功能) - 那
yield回到哪兒去了呢?從哪兒send就回到哪兒去,所以,他又回到了task.__step函式里面去
def __step(self, exc=None):
coro = self._coro
try:
if exc is None:
result = coro.send(None)
else:
result = coro.throw(exc)
except StopIteration as exc:
super().set_result(exc.value)
else:
blocking = getattr(result, '_asyncio_future_blocking', None)
if blocking:
result._asyncio_future_blocking = False
result.add_done_callback(self.__wakeup, result)
finally:
self = None
- 這里是本函式的第一個核心點,流程控制/跳轉,需要非常的清晰,如果搞不清楚的同學,再詳細的去閱讀有關
yield/yield from的文章 - 繼續往下走,由于用戶函式
helloworld()沒有結束,所以不會拋例外,所以來到了else分支 blocking = getattr(result, '_asyncio_future_blocking', None)這里有一個重要的狀態,那就是_asyncio_future_blocking,只有呼叫__await__,才會有這個引數,默認是true,這個引數主要的作用:一個異步函式,如果呼叫了多個子異步函式,那證明該異步函式沒有結束(后面詳細講解),就需要添加“喚醒”回呼result._asyncio_future_blocking = False將引數置位False,并且添加self.__wakeup回呼等待喚醒__step函式完成
這里需要詳細講解一下_asyncio_future_blocking 的作用
- 如果在異步函式里面出現了await,呼叫其他異步函式的情況,就會走到
Future.__await__將_asyncio_future_blocking設定為true
async def helloworld():
print('enter helloworld')
ret = await wilsonasyncio.gather(hello(), world())
print('exit helloworld')
return ret
class Future:
def __await__(self):
if self._state == _PENDING:
self._asyncio_future_blocking = True
yield self
return self.result()
- 這樣做了之后,在
task.__step中就會把該任務的回呼函式設定為__wakeup - 為啥要
__wakeup,因為helloworld()并沒有執行完成,所以需要再次__wakeup來喚醒helloworld()
這里揭示了,在Eventloop里面,只要使用await呼叫其他異步任務,就會掛起父任務,轉而去執行子任務,直至子任務完成之后,回到父任務繼續執行
先喝口水,休息一下,下面更復雜,,,
3.4)第二次回圈run_forever --> run_once
eventloops.py
def run_once(self):
ntodo = len(self._ready)
for _ in range(ntodo):
handle = self._ready.popleft()
handle._run()
- 從佇列中取出資料,此時
_ready佇列有兩個任務,hello()world(),在gather的for回圈時添加的
async def hello():
print('enter hello ...')
return 'return hello ...'
async def world():
print('enter world ...')
return 'return world ...'
- 由于
hello()world()沒有await呼叫其他異步任務,所以他們的執行比較簡單,分別一次task.__step就結束了,到達set_result()處 set_result()將回呼函式放入_ready佇列,等待下次回圈執行
3.5)第三次回圈run_forever --> run_once
- 我們來看下回呼函式
def _done_callback(fut):
nonlocal nfinished
nfinished += 1
if nfinished == nfuts:
results = []
for fut in children:
res = fut.result()
results.append(res)
outer.set_result(results)
- 沒錯,這是本文的第二個核心點,我們來仔細分析一下
- 這段代碼最主要的邏輯,其實就是,只有當所有的子任務執行完之后,才會啟動父任務的回呼函式,本文中只有
hello()world()都執行完之后if nfinished == nfuts:,才會啟動父任務_GatheringFuture的回呼outer.set_result(results) results.append(res)將子任務的結果取出來,放進父任務的results里面- 子任務執行完成,終于到了喚醒父任務的時候了
task.__wakeup
def __wakeup(self, future):
try:
future.result()
except Exception as exc:
raise exc
else:
self.__step()
self = None
3.6)第四次回圈run_forever --> run_once
future.result()從_GatheringFuture取出結果,然后進入task.__step
def __step(self, exc=None):
coro = self._coro
try:
if exc is None:
result = coro.send(None)
else:
result = coro.throw(exc)
except StopIteration as exc:
super().set_result(exc.value)
else:
blocking = getattr(result, '_asyncio_future_blocking', None)
if blocking:
result._asyncio_future_blocking = False
result.add_done_callback(self.__wakeup, result)
finally:
self = None
result = coro.send(None)其實就是helloworld() --> send又要跳回到當初yield的地方,那就是Future.__await__
def __await__(self):
if self._state == _PENDING:
self._asyncio_future_blocking = True
yield self
return self.result()
return self.result()終于回傳到helloworld()函式里面去了
async def helloworld():
print('enter helloworld')
ret = await wilsonasyncio.gather(hello(), world())
print('exit helloworld')
return ret
helloworld終于也執行完了,回傳了ret
3.7)第五次回圈run_forever --> run_once
- 回圈結束
- 回到
run
3.8)回到主函式,獲取回傳值
if __name__ == "__main__":
ret = wilsonasyncio.run(helloworld())
print(ret)
3.9)執行結果
? python3 main.py
enter helloworld
enter hello ...
enter world ...
exit helloworld
['return hello ...', 'return world ...']
五、流程總結

六、小結
● 終于結束了,這是一個非常長的小節了,但是我感覺很多細節還是沒有說到,大家有問題請及時留言探討
● _GatheringFuture一個非常重要的物件,它不但追蹤了hello() world()的執行狀態,喚醒helloworld(),并且將回傳值傳遞給helloworld
● await async yield對流程的控制需要特別關注
● 本文中的代碼,參考了python 3.7.7中asyncio的源代碼,裁剪而來
● 本文中代碼:代碼
至此,本文結束
在下才疏學淺,有撒湯漏水的,請各位不吝賜教...
更多文章,請關注我:wilson.chai
本文來自博客園,作者:wilson排球,轉載請注明原文鏈接:https://www.cnblogs.com/MrVolleyball/p/15812407.html
本文著作權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連接,否則保留追究法律責任的權利,轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/412910.html
標籤:其他
上一篇:不卷了!技術團隊成員集體辭職
下一篇:常用快捷鍵和dos命令
