- Python通过yield提供了对协程的基本支持,但是不完全。而第三方的gevent为Python提供了比较完善的协程支持。
- gevent是第三方库,通过greenlet实现协程,其基本思想是:
当一个greenlet遇到IO操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO。 - 由于切换是在IO操作时自动完成,所以gevent需要修改Python自带的一些标准库,这一过程在启动时通过monkey patch完成
安装过程
sudo apt-get install libevent-dev
sudo apt-get install python-all-dev
sudo apt-get install python-setuptools
sudo easy_install greenlet
sudo easy_install gevent
sudo easy_install -mgevent
例子
from gevent import monkey; monkey.patch_socket();monkey.patch_all(dns=False)
import gevent
import urllib2
def f(url):
print('GET: %s' % url)
resp = urllib2.urlopen(url)
data = resp.read()
print('%d bytes received from %s.' % (len(data), url))
g1 = gevent.spawn(f, 'https://www.python.org/')
g2 = gevent.spawn(f, 'https://www.baidu.com/')
g3 = gevent.spawn(f, 'https://github.com/')
gevent.joinall([g1,g2,g3])
输出结果如下:
GET: https://www.python.org/
GET: https://www.baidu.com/
GET: https://github.com/
227 bytes received from https://www.baidu.com/.
47448 bytes received from https://www.python.org/.
25811 bytes received from https://github.com/.