python 协程

一、实质

协程的本质是线程

在多个任务之间切换来节省一些IO时间

进程和线程是操作系统调度

协程是代码调度

二、greenlet

from greenlet import greenlet


def eat():
    print('start eat')
    g2.switch()
    print('end eat')
    g2.switch()


def play():
    print('start play')
    g1.switch()
    print('end play')


g1 = greenlet(eat)
g2 = greenlet(play)
g1.switch()
"""
打印:
start eat
start play
end eat
end play
"""

三、gevent

"""
常用方法
from gevent import monkey;monkey.patch_all()
打补丁,用于识别IO
gevent.spawn(方法名, 参数)
创建协程对象
obj.join() 等待协程对象的结果
obj.value() 协程对象的返回值
"""
from gevent import monkey;monkey.patch_all()
import gevent
import time


def eat():
    print('start eat')
    time.sleep(0.5)
    print('end eat')


def play():
    print('start play')
    time.sleep(0.5)
    print('end play')


g1 = gevent.spawn(eat)
g1.join()   # 等待g1执行结束
g2 = gevent.spawn(play)
g2.join()   # 等待g2执行结束
"""
打印:
start eat
start play
end eat
end play
"""

 

上一篇:python – 正确的greenlet终止


下一篇:协程