天天看點

Python中monkey.patch_all()解決協程阻塞問題

Python 全棧工程師核心面試 300 問深入解析(2020 版)----全文預覽

Python 全棧工程師核心面試 300 問深入解析(2020 版)----歡迎訂閱

直接參考以下執行個體,采用協程通路三個網站

由于IO操作非常耗時,程式經常會處于等待狀态

比如請求多個網頁有時候需要等待,gevent可以自動切換協程

遇到阻塞自動切換協程,程式啟動時執行monkey.patch_all()解決

# 由于IO操作非常耗時,程式經常會處于等待狀态
# 比如請求多個網頁有時候需要等待,gevent可以自動切換協程
# 遇到阻塞自動切換協程,程式啟動時執行monkey.patch_all()解決
# 首行添加下面的語句即可
from gevent import monkey; monkey.patch_all()
import gevent
from urllib import request
def run_task(url):
    print("Visit --> %s" % url)
    try:
        response = request.urlopen(url)
        data = response.read()
        print("%d bytes received from %s." %(len(data), url))
    except Exception:
        print("error")

if __name__ == '__main__':
    urls = ['https://github.com/', 'https://blog.csdn.net/', 'https://bbs.csdn.net/']
    # 定義協程方法
    greenlets = [gevent.spawn(run_task, url) for url in urls]
    # 添加協程任務,并且啟動運作
    gevent.joinall(greenlets)

# 檢視運作結果可以發現,三個協程是同時觸發的,但是結束順序不同
# 網頁請求的時間不同,故結束順序不同
# 但是該程式其實隻有一個線程
           

輸出結果

Visit --> https://github.com/
Visit --> https://blog.csdn.net/
Visit --> https://bbs.csdn.net/
34697 bytes received from https://blog.csdn.net/.
75062 bytes received from https://bbs.csdn.net/.
79347 bytes received from https://github.com/.

Process finished with exit code 0
           

繼續閱讀