Gevent协程

时间:2023-03-08 20:55:17

协程

协程,又称微线程,纤程。英文名Coroutine。一句话说明什么是线程:协程是一种用户态的轻量级线程

协程拥有自己的寄存器上下文和栈。协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈。因此:

协程能保留上一次调用时的状态(即所有局部状态的一个特定组合),每次过程重入时,就相当于进入上一次调用的状态,换种说法:进入上一次离开时所处逻辑流的位置。

Gevent

Gevent是基于协程的Python网络库

特性:

  1. 基于libev的快速事件循环
  2. 基于greenlet的轻量级执行单元
  3. 重用Python标准库且概念相似的API
  4. 支持SSL的协作socket
  5. 通过c-ares或者线程池进行DNS查询
  6. 使用标准库和第三方库中使用了阻塞socket的代码的能力

实例代码1

import gevent
def foo():
print('\033[32;1mrunning in foo\033[0m')
gevent.sleep(1)
print('\033[32;1mExplicit context switch to foo again')
def bar():
print('\033[31;1mExpicit context to bar\033[0m')
gevent.sleep(1)
print('\033[31;1mExplicigt context switch back to bar\033[0m')
def ex():
print('\033[33;1mExpicit context to bar\033[0m')
gevent.sleep(1)
print('\033[33;1mExplicigt context switch back to bar\033[0m') gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
gevent.spawn(ex),
])

执行结果:

running in foo
Expicit context to bar
Expicit context to bar
Explicit context switch to foo again
Explicigt context switch back to bar
Explicigt context switch back to bar