gevent-协程支持

安装

真是费了牛劲了,一下午才搞定安装,记录如下

  1. 安装libevent brew install libevent
  2. 安装cython pip install cython
  3. 安装greenlet
    此时有可能出现error: could not create '/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/greenlet': Operation not permitted
    直接略过,进入第4步
  4. 安装gevent
  • git clone https://github.com/gevent/gevent/
  • sudo python setup.py build
  • sudo python setup.py install

用法

Python通过yield提供了对协程的支持,Python-协程,第三方的gevent为Python提供了比较完善的协程支持
通过greenlet实现协程,当一个greenlet遇到IO操作的时候,比如访问网络,就自动切换到其他的greenlet,等待IO操作完成,再在适当的时候切换回来继续执行,IO操作比较费时,程序处于等待状态,gevent可以自动切换协程,总保证greenlet在运行,而不是等待IO。
切换是在IO操作时候自动完成,所以gevent需要修改Python自带的标准库,这一过程再启动时通过monkey patch完成

  1. gevent.monkey – Make the standard library cooperative

  2. patch_socket(dns=True, aggressive=True)
    Replace the standard socket object with gevent’s cooperative sockets.
    If dns is true, also patch dns functions in socket.

  3. patch_ssl()
    Replace SSLSocket object and socket wrapping functions in ssl with cooperative versions.
    This is only useful if patch_socket() has been called.

你可能感兴趣的:(gevent-协程支持)