python 协程
2020-12-13 03:24
标签:多个 print from 打印 key pytho 返回值 时间 obj 一、实质 协程的本质是线程 在多个任务之间切换来节省一些IO时间 进程和线程是操作系统调度 协程是代码调度 二、greenlet 三、gevent python 协程 标签:多个 print from 打印 key pytho 返回值 时间 obj 原文地址:https://www.cnblogs.com/wt7018/p/11074486.htmlfrom 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
"""
"""
常用方法
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
"""
上一篇:Spring这棵大树
下一篇:算法之原码、补码、反码(四)