Python使用monkey.patch_all()解決協程阻塞問題
直接參考以下實例,采用協程訪問三個網站
由于IO操作非常耗時,程序經常會處于等待狀態
比如請求多個網頁有時候需要等待,gevent可以自動切換協程
遇到阻塞自動切換協程,程序啟動時執行monkey.patch_all()解決
# 由于IO操作非常耗時,程序經常會處于等待狀態# 比如請求多個網頁有時候需要等待,gevent可以自動切換協程# 遇到阻塞自動切換協程,程序啟動時執行monkey.patch_all()解決# 首行添加下面的語句即可from gevent import monkey; monkey.patch_all()import geventfrom urllib import requestdef 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/bytes received from https://blog.csdn.net/.bytes received from https://bbs.csdn.net/.bytes received from https://github.com/.
Process finished with exit code 0
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: