關於asyncio知識(四)

来源:https://www.cnblogs.com/zhaof/archive/2019/03/22/10581972.html
-Advertisement-
Play Games

一、使用 asyncio 總結 最近在公司的一些項目中開始慢慢使用python 的asyncio, 使用的過程中也是各種踩坑,遇到的問題也不少,其中有一次是記憶體的問題,自己也整理了遇到的問題以及解決方法詳細內容看:https://www.syncd.cn/article/memory_trouble ...


一、使用 asyncio 總結

最近在公司的一些項目中開始慢慢使用python 的asyncio, 使用的過程中也是各種踩坑,遇到的問題也不少,其中有一次是記憶體的問題,自己也整理了遇到的問題以及解決方法詳細內容看:https://www.syncd.cn/article/memory_trouble

在前面整理的三篇asyncio文章中,也都是使用asyncio的一些方法,但是在實際項目中使用還是避免不了碰到問題, 在這周的工作中遇到之前碰見過的問題,一個初學asyncio寫代碼中經常會碰到的問題,我的業務代碼在運行一段時間後提示如下錯誤提示:

Task was destroyed but it is pending!task: <Task pending coro=<HandleMsg.get_msg() done, defined at ex10.py:17> wait_for=<Future cancelled>>

這個錯誤我在前面幾篇關於asyncio的系列文章中也反覆說過這個問題,我也認為自己不會在出現這種問題,但是意外的是,我的程式還是出現了這個錯誤。

我將我的業務代碼通過一個demo代碼進行模擬復現以及解決這個問題,下麵整理的就是這個過程

二、“Task was destroyed but it is pending!”

我通過下麵這張圖先描述一下demo程式的邏輯:

 

 

import asyncio
from asyncio import Queue
import uuid
from asyncio import Lock
from asyncio import CancelledError
queue = Queue()
class HandleMsg(object):
    def __init__(self, unid, coroutine_queue, handle_manager):
        self.unid = unid
        self.coroutine_queue = coroutine_queue
        self.handle_manager = handle_manager
    async def get_msg(self):
        while True:
            coroutine_msg = await self.coroutine_queue.get()
            msg_type = coroutine_msg.get("msg")
            if msg_type == "start":
                print("recv unid [%s] is start" % self.unid)
            else:
                print("recv unid [%s] is end" % self.unid)
                # 每個當一個unid收到end消息為結束
                await self.handle_manager.del_unid(self.unid)
class HandleManager(object):
    """
    用於unid和queue的關係的處理
    """
    def __init__(self):
        self.loop = asyncio.get_event_loop()
        self.lock = Lock(loop=self.loop)
        self.handle_dict = dict()
    async def unid_bind(self, unid, coroutine_queue):
        async with self.lock:
            self.handle_dict[unid] = coroutine_queue
    async def get_queue(self, unid):
        async with self.lock:
            if unid in self.handle_dict:
                return self.handle_dict[unid]
    async def del_unid(self, unid):
        async with self.lock:
            if unid in self.handle_dict:
                self.handle_dict.pop(unid)
def make_uniqueid():
    """
    生成unid
    """
    uniqueid = str(uuid.uuid1())
    uniqueid = uniqueid.split("-")
    uniqueid.reverse()
    uniqueid = "".join(uniqueid)
    return uniqueid
async def product_msg():
    """
    生產者
    """
    while True:
        unid = make_uniqueid()
        msg_start = {"unid": unid, "msg": "start"}
        await queue.put(msg_start)
        msg_end = {"unid": unid, "msg": "end"}
        await queue.put(msg_end)
        loop = asyncio.get_event_loop()
        await asyncio.sleep(0.2, loop=loop)
async def consumer_from_queue(handle_manager):
    """
    消費者
    """
    while True:
        msg = await queue.get()
        print("consumer recv %s" % msg)
        msg_type = msg.get("msg")
        unid = msg.get("unid")
        if msg_type == "start":
            coroutine_queue = Queue()  # 用於和handle_msg協程進行數據傳遞
            handle_msg = HandleMsg(unid, coroutine_queue, handle_manager)
            await handle_manager.unid_bind(unid, coroutine_queue)
            await coroutine_queue.put(msg)
            loop = asyncio.get_event_loop()
            # 每次的start消息創建一個task 去處理消息
            loop.create_task(handle_msg.get_msg())
        else:
            coroutine_queue = await handle_manager.get_queue(unid)
            await coroutine_queue.put(msg)
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    handle_manager = HandleManager()
    #  在最開始創建了兩個task 分別是生產者和消費者
    loop.create_task(product_msg())
    loop.create_task(consumer_from_queue(handle_manager))
    loop.run_forever()

上面的代碼錶面上看沒啥問題,我們先看看運行效果:

consumer recv {'unid': '784f436cfaf388f611e94ca974e1ffbe', 'msg': 'start'}
consumer recv {'unid': '784f436cfaf388f611e94ca974e1ffbe', 'msg': 'end'}
Task was destroyed but it is pending!
task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>
Task was destroyed but it is pending!
task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>
Task was destroyed but it is pending!
task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>
Task was destroyed but it is pending!
task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>
Task was destroyed but it is pending!
task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>
Task was destroyed but it is pending!
task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>
..........

程式沒運行一段時間都會出現上面顯示的錯誤提示,我先看看錯誤提示的信息:

 

  1. Task was destroyed but it is pending!
  2. task: <Task pending coro=<HandleMsg.get_msg() done, defined at demo.py:17> wait_for=<Future cancelled>>

 

上面提示的其實就是我的task 是在pendding狀態的時候被destroyed了,代碼行數以及調用方法都告訴我們了是在:HandleMsg.get_msg() done, defined at demo.py:17

其實問題也比較好找,我們為每個unid創建了一個task來處理消息,但是當我們收到每個unid消息的end消息之後其實這個task任務對於我們來說就已經完成了,同時我們刪除了我的unid和queue的綁定,但是我們並沒有手動去取消這個task。


註意:這裡我其實也有一個不理解的地方:關於這個task為什麼會會destroyed,這個協程里是一個死迴圈一直在收消息,當queue裡面沒有消息協程也應該一直在await 地方在等待才對,但是如果我們把收到end消息的那個地方的刪除unid和queue的綁定關係不刪除,那麼這個任務是不會被descroyed。所以沒有完全明白這裡的機制,如果明白的同學歡迎留言討論

但是即使上面的機制我們有點不是特別明白,我們其實也應該把這個task手動進行cancel的,我們們將上面的代碼稍微進行改動如下:

async def get_msg(self):
        try:
            while True:
                coroutine_msg = await self.coroutine_queue.get()
                msg_type = coroutine_msg.get("msg")
                if msg_type == "start":
                    print("recv unid [%s] is start" % self.unid)
                else:
                    print("recv unid [%s] is end" % self.unid)
                    # 每個當一個unid收到end消息為結束
                    await self.handle_manager.del_unid(self.unid)
                    current_task = asyncio.Task.current_task()
                    current_task.cancel()   # 手動cancel 當前的當前的task
        except CancelledError as e:
            print("unid [%s] cancelled success" %self.unid)

這裡有個問題需要註意就是當我們對task進行cancel的時候會拋出cancelledError異常,我們需要對異常進行處理。官網也對此進行專門說明:
https://docs.python.org/3.6/library/asyncio-task.html#coroutine

內容如下:

cancel()
Request that this task cancel itself.
This arranges for a CancelledError to be thrown into the wrapped coroutine on the next cycle through the event loop. The coroutine then has a chance to clean up or even deny the request using try/except/finally.
Unlike Future.cancel(), this does not guarantee that the task will be cancelled: the exception might be caught and acted upon, delaying cancellation of the task or preventing cancellation completely. The task may also return a value or raise a different exception.
Immediately after this method is called, cancelled() will not return True (unless the task was already cancelled). A task will be marked as cancelled when the wrapped coroutine terminates with a CancelledError exception (even if cancel() was not called).

三、小結

雖然還有一些地方不太明白,但是隨著用的越多,碰到的問題越多,一個一個解決,可能現在對某些知識還有點模糊,但是至少比剛開始使用asyncio的時候清晰了好多,之前整理的三篇文章的連接如下:
https://www.syncd.cn/article/asyncio_article_01
https://www.syncd.cn/article/asyncio_article_02
https://www.syncd.cn/article/asyncio_article_03

也歡迎加入交流群一起討論相關內容:948510543

  

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、系統的初始化配置 1、配置靜態IP和DNS 配置靜態IP 1、sudo vim /etc/network/interfaces,修改文件內容如下: auto eth0 #表示讓網卡開機自動掛載eth0網卡 iface eth0 inet static #此處一定要改為static address ...
  • (模板)2-SAT 題目描述 有n個變數,m條語句,沒個形如:xi為a或xj為b(a,b=0或1)... 判斷是否有解,有的話構造出來一組解 思路: 將每個變數分為兩個點,取0和取1(i和i+n) 對於每條語句可以轉換為若xi取(1-a)則xj必須取b,若xj取(1-b)則xi必須取a,按照這樣的關 ...
  • 今天終於有時間好好給大家寫寫關於如何寫簡歷,給自己加分了。 這篇文章拖了很久了應該說,本來想在上周寫的,但是事情實在是太多,又不想草草了事,所以擱置到現在。今天早上正好空出來了,就馬上給大家碼出來了。關註公眾號「Python專欄」,後臺回覆:**簡歷模板**,即可獲取打包全部模版。 ...
  • 從官網下載指定版本的JDK 一、百度搜索jdk,進入最新版Downloads界面 百度搜索jdk,或者jdk下載,點擊進入jdk官網最新版本下載界面,可以看到當前最新版本為jdk12 二、找到JDK歷史版本鏈接 往往我們需要下載的不是最新版,而是老一些的版本,該去哪裡下載呢?其實就在最新版Downl ...
  • 一、如果集合的元素類型是基本數據類型,方法如下 直接調用Collections.sort(list)方法,list為傳入的需要排序的集合 基本數據類型有哪些? 總共8種 4種整型類型byte、short、int、long 2種浮點數類型float、double 1種字元類型char 1種布爾類型bo ...
  • 第一個go程式——HelloWorld.go 源碼 : 在命令行切換到程式所在路徑下,go run HelloWorld.go。或者在HelloWorld.go程式所在路徑下,先執行 go build HelloWorld.go, 生成一個可執行文件HelloWorld。然後直接在命令行輸入Hell ...
  • 一、安裝nginx 1、安裝前提 a)epoll,linux內核版本為2.6或者以上 b)gcc編譯器,g++編譯器 c)pcre庫,函數庫,支持解析正則表達式 d)zlib庫:壓縮解壓功能 e)openssl庫:ssl功能相關庫,用於網站加密通訊 2、nginx源碼下載以及目錄結構簡單認識 ngi ...
  • 正向代理: 客戶端的代理; 反向代理: 服務端的代理; ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...