栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python使用monkey.patch_all()解决协程阻塞问题

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python使用monkey.patch_all()解决协程阻塞问题

直接参考以下实例,采用协程访问三个网站

由于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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/19950.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号