#协程(又称微线程,纤程)
#协程,与线程的抢占式调度不同,它是协作式调度。协程也是单线程,但是它能让原来要使用异步+回调方式写的非人类代码,可以用看似同步的方式写出来。
#当程序执行到produce的yield i时,返回了一个generator并暂停执行,当我们在custom中调用p.next(),程序又返回到produce的yield i 继续执行,这样 l 中又append了元素,然后我们print l.pop(),直到p.next()引发了StopIteration异常。
import time
import sys
# 生产者
def produce(l):
i=0
while 1:
if i < 10:
l.append(i)
yield i
i=i+1
time.sleep(1)
else:
return
# 消费者
def consume(l):
p = produce(l)
while 1:
try:
next(p) #在python3.x版本中,python2.x的g.next()函数已经更名为g.__next__(),使用next(g)也能达到相同效果。
while len(l) > 0:
print (l.pop())
except StopIteration:
sys.exit(0)
if __name__ == "__main__":
l = []
consume(l)