参考:
https://www.cnblogs.com/zhangxinqi/p/8337207.html
https://www.cnblogs.com/xybaby/p/6337944.html
协程,又称微线程,纤程。英文名Coroutine。
协程是程序级别的,由程序自己决定如何调度。
协程的概念:
在子程序执行过程中可以中断去执行别的子程序,而别的子程序也可以中断回来继续执行之前的子程序,这个过程就称为协程。
类似与yield操作。
协程的优点:
协程的缺点:
def consumer(name):
count = 12
print(‘开始吃包子...‘)
# while True:
bone = 0
while bone <= count:
print(‘%s需要包子‘ % name)
bone = yield # 接收send发送的数据
print(‘%s吃了%s个包子‘ % (name, bone))
def producer(obj1):
obj1.send(None) # 必须先发送None,触发协程运行
for i in range(3):
print(‘[producer]正在做%s个包子‘ % i)
obj1.send(i)
if __name__ == ‘__main__‘:
con1 = consumer(‘消费者A‘) # 创建消费者对象, 此时程序并未执行,只是返回了一个生成器对象。
producer(con1)
print("协程结束")
from greenlet import greenlet
def test1():
print 12
gr2.switch()
print 34
def test2():
print 56
gr1.switch()
print 78
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
# 输出为:
# 12 56 34
原文:https://www.cnblogs.com/dream2sky/p/14233202.html