欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-08-29 08:58:20|栏目:Python代码|点击:

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

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

上一篇:python 限制函数调用次数的实例讲解

栏    目:Python代码

下一篇:Tensorflow的常用矩阵生成方式

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

本文地址:http://www.codeinn.net/misctech/170935.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有