gevent的深入实践

26 篇文章 0 订阅

Gevent是python的第三方库,提供了比较完善的对协程的支持。Python中GIL的存在,导致多线程一直不是很好用,相形之下,协程的优势就更加突出了。
Gevent的基本思想是:当遇到IO操作时,会自动写换到其他gevent,再在适当的时间切回来继续执行。这样就减少了IO操作时的等待耗时,从而能够提高硬件资源的利用率。
注:本文使用python版本2.7.12, gevent版本1.2.2

1. greenlet/eventlet/gevent的关系

Greelent实现了一个比较易用(相比yeild)的协程切换的库。但是greenlet没有自己的调度过程,所以一般不会直接使用。
Eventlet在Greenlet的基础上实现了自己的GreenThread,实际上就是greenlet类的扩展封装,而与Greenlet的不同是,Eventlet实现了自己调度器称为Hub,Hub类似于Tornado的IOLoop,是单实例的。在Hub中有一个event loop,根据不同的事件来切换到对应的GreenThread。同时Eventlet还实现了一系列的补丁来使Python标准库中的socket等等module来支持GreenThread的切换。Eventlet的Hub可以被定制来实现自己调度过程。
Gevent基于libev和Greenlet。不同于Eventlet的用python实现的hub调度,Gevent通过Cython调用libev来实现一个高效的event loop调度循环。同时类似于Eventlet,Gevent也有自己的monkey_patch,在打了补丁后,完全可以使用python线程的方式来无感知的使用协程,减少了开发成本。

2. gevent猴子补丁

猴子补丁monkey_patch,将标准库中大部分的阻塞式调用替换成非阻塞的方式,包括socket、ssl、threading、select、httplib等。通过monkey.patch_xxx()来打补丁。按照gevent文档中的建议,应该将猴子补丁的代码尽可能早的被调用,这样可以避免一些奇怪的异常。
我是这样理解的,gevent实现了协程的创建、切换和调度,本身是同步的,而猴子补丁将gevent调用的阻塞库变成非阻塞的,两者配合实现了高性能的协程。

3. gevent和popen

Gevent虽然提供了subprocess的支持,但是没有提供对os.popen的支持,os.system也是一样。也就是说,os.popen是阻塞的。测试如下:

from gevent import monkey
monkey.patch_all()
import gevent
import os


def func(num):
    print "start", num
    os.popen("sleep 3")
    # os.system("sleep 3")
    print "end", num


g1 = gevent.spawn(func, 1)
g2 = gevent.spawn(func, 2)
g3 = gevent.spawn(func, 3)
g1.join()
g2.join()
g3.join()

说明一下,这里的join是用来阻塞主协程,用来做协程间同步用的。和thread类似。
输出结果

start 1
end 1
start 2
end 2
start 3
end 3

需要注意的是,不使用gevent时, os.popen("sleep 3")本身是不阻塞的,os.popen("sleep 3").read()才会阻塞。但是使用gevent时,os.popen("sleep 3")也是会阻塞
但是使用subprocess就可以实现非阻塞式调用,subprocess.call和subprocess.Popen都是非阻塞的。测试如下:

from gevent import monkey
monkey.patch_all()
import gevent
import os
import subprocess

def func(num):
    print "start", num
    susubprocess.call(['sleep', '3'])
    # sub = subprocess.Popen(['sleep 3'], shell=True)
    # out, err = sub.communicate()
    print "end", num

g1 = gevent.spawn(func, 1)
g2 = gevent.spawn(func, 2)
g3 = gevent.spawn(func, 3)
g1.join()
g2.join()
g3.join()

输出结果

start 1
start 2
start 3
end 1
end 2
end 3

4. gevent和time

Monkey.patch_all会将time库也变成非阻塞的,也就是说monkey.patch_all之后,time.sleep等同等于gevent.sleep。测试如下:

from gevent import monkey
monkey.patch_all()
import gevent
import time

def func(num):
    print "start", num
    time.sleep(3)
    print "start", num


g1 = gevent.spawn(func, 1)
g2 = gevent.spawn(func, 2)
g3 = gevent.spawn(func, 3)
g1.join()
g2.join()
g3.join()

输出结果

start 1
start 2
start 3
end 1
end 2
end 3

当然,如果没有monkey.patch_all或者monkey.patch_time的话,time还是阻塞的。
可以查看patch_all的函数原型,就能知道打了哪些补丁:

patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, httplib=False, subprocess=True, sys=False, aggressive=True, Event=False, builtins=True, signal=True)

可以看到httplib和Event默认是关闭的,其他默认都是开启的。

5. gevent和timeout

看到有文章说,gevent里使用timeout会失效,因为已经是非阻塞的了。
经过验证,上面的说法是错误的。无论使用urllib2,requests库,timeout设置都有效

from gevent import monkey
monkey.patch_all()
import gevent
import requests
import urllib2

def func(url):
    # print "start", url 
    # urllib2.urlopen(url, timeout=3)
    requests.get(url, timeout=3)
    # print "end", url 


g1 = gevent.spawn(func, "http://www.baidu.com")
g2 = gevent.spawn(func, "http://www.sina.com")
g3 = gevent.spawn(func, "http://www.google.com")
g1.join()
g2.join()
g3.join()

会有正常的超时报错:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 536, in run
    result = self._run(*self.args, **self.kwargs)
  File "<stdin>", line 2, in func
  File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 429, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 447, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1228, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1198, in do_open
    raise URLError(err)
URLError: <urlopen error [Errno 101] Network is unreachable>
Tue Jul 24 20:22:50 2018 <Greenlet at 0x7ff390f14af0: func('http://www.google.com')> failed with URLError

另外,gevent里有个Timeout对象,可以很方便的实现非阻塞式的超时控制:

with gevent.Timeout(seconds, exception) as timeout:
     pass  # ... code block ...

如果不指定exception,超时会raise timeout

6. gevent和数据库操作

既然monkey.patch_all将socket变成非阻塞了,那么进行数据库操作请求,也会建立socket连接,自然也是非阻塞的。
比如redis:

from gevent import monkey
monkey.patch_all()
import gevent
import redis

r = redis.Redis(host="localhost",port=6379)

def func(key):
    print "start", key
    v = r.get(key)
    print "end", key


g1 = gevent.spawn(func, "a")
g2 = gevent.spawn(func, "b")
g3 = gevent.spawn(func, "c")
g1.join()
g2.join()
g3.join()

结果

start a
start b
start c
end a
end b
end c

但是MySQL是阻塞的,因为,MySQL是用C写的,patch的socket补丁,并不生效。

from gevent import monkey
monkey.patch_all()
import gevent
import MySQLdb


def func(data):
    print "start", data
    conn = MySQLdb.connect(host="localhost",user="root",passwd="root",db="test")
    cur = conn.cursor()
    cur.execute("insert into test (data) values(%s)", (data,))
    conn.commit()
    print "end", data

g1 = gevent.spawn(func, "a")
g2 = gevent.spawn(func, "b")
g3 = gevent.spawn(func, "c")
g1.join()
g2.join()
g3.join()

输出

 

start a
end a
start b
end b
start c
end c

测试MongoDB,结果也是非阻塞

from gevent import monkey
monkey.patch_all()
import gevent
import MySQLdb
 
conn = MySQLdb.connect(host="localhost",user="root",passwd="root",db="test")
cur = conn.cursor()
 
def func(data):
    print "start", data
    cur.execute("insert into test (data) values(%s)", (data,))
    conn.commit()
    print "end", data
 
def run():
    g1 = gevent.spawn(func, "a1")
    g2 = gevent.spawn(func, "b1")
    g3 = gevent.spawn(func, "c1")
    g1.join()
    g2.join()
    g3.join()

结果

start a
start b
start c
end a
end c
end b

7. gevent文件IO

注意:gevent里文件IO操作是不做切换的。

from gevent import monkey
monkey.patch_all()
import gevent
import os


def func(fn):
    print "start", fn
    with open(fn, "w") as f:
        f.write("*"*100000000)
    with open(fn) as f:
        print len(f.read())
    print "end", fn


g1 = gevent.spawn(func, "text1")
g2 = gevent.spawn(func, "text2")
g3 = gevent.spawn(func, "text3")
g1.join()
g2.join()
g3.join()

结果

start text1
100000000
end text1
start text2
100000000
end text2
start text3
100000000
end text3

8. gevent的结果和异常

Gevent运行的结果和异常可以通过value和exception来获取。需要注意的是,协程内部运行的异常,不会被抛出(会被打印)从而影响到其他协程。

print g1.value, g1.exception

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值