Python使用monkey.patch_all()解决协程阻塞问题
作者:cool小伙 时间:2021-05-11 17:27:19
直接参考以下实例,采用协程访问三个网站
由于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/
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
来源:https://www.cnblogs.com/xiaozengzeng/p/12687936.html
标签:Python,monkey,patch,协程
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
http通过StreamingHttpResponse完成连续的数据传输长链接方式
2023-06-04 03:33:45
YUI学习笔记(4)
2009-03-10 18:25:00
jupyter读取错误格式文件的解决方案
2022-04-02 18:56:57
![](https://img.aspxhome.com/file/2023/1/85061_0s.jpg)
用Python抢火车票的简单小程序实现解析
2023-09-06 06:31:28
利用pandas合并多个excel的方法示例
2021-05-28 00:02:00
![](https://img.aspxhome.com/file/2023/0/86410_0s.png)
Python通过Tesseract库实现文字识别
2023-02-28 13:29:46
![](https://img.aspxhome.com/file/2023/8/100828_0s.png)
Python多线程中阻塞(join)与锁(Lock)使用误区解析
2022-03-22 08:00:31
如何做好一份前端工程师的简历?
2009-02-17 12:52:00
基于pygame实现童年掌机打砖块游戏
2023-09-18 20:41:28
![](https://img.aspxhome.com/file/2023/4/87514_0s.jpg)
Python使用tkinter写一个本地密码管理器
2022-09-19 13:05:53
![](https://img.aspxhome.com/file/2023/1/86391_0s.png)
为什么定位会被float和clear影响!
2008-11-10 11:06:00
javascript中类的创建和继承
2008-05-08 12:07:00
Python实现判断一个字符串是否包含子串的方法总结
2023-04-17 06:27:58
python 如何去除字符串头尾的多余符号
2021-12-29 03:17:36
appium+python adb常用命令分享
2022-12-27 09:16:24
![](https://img.aspxhome.com/file/2023/7/80537_0s.jpg)
MySQL也能并发导入数据
2010-03-25 10:38:00
混乱的标记语言XHTML2/HTML5
2009-07-31 14:27:00
![](https://img.aspxhome.com/file/UploadPic/20097/31/200973114466783s.jpg)
Pytorch自动求导函数详解流程以及与TensorFlow搭建网络的对比
2023-07-08 18:44:37
![](https://img.aspxhome.com/file/2023/0/95860_0s.png)
在asp中使用js的encodeURIComponent方法
2012-11-30 20:05:53
Mysql入门系列:MySQL数据目录的位置
2008-11-24 12:59:00
![](https://img.aspxhome.com/file/UploadPic/200811/20081129183226513.jpg)