今天在看廖雪峰Python教程的时候,看到协程。用了生产者—消费者模型来举例Python中generator中yield关键字对协程一定程度上的支持:
代码来自:
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868328689835ecd883d910145dfa8227b539725e5ed000
import time
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
time.sleep(1)
r = '200 OK'
def produce(c):
c.next()
#x = c.next()
#print x //x=' '
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()
if __name__=='__main__':
c = consumer()
produce(c)
输出结果:
[PRODUCER] Producing 1...
[CONSUMER] Consuming 1...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 2...
[CONSUMER] Consuming 2...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 3...
[CONSUMER] Consuming 3...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 4...
[CONSUMER] Consuming 4...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 5...
[CONSUMER] Consuming 5...
[PRODUCER] Consumer return: 200 OK
在调用c.next()的时候,触发生成器,执行到n=yield r的时候回到produce函数,并将r的值返回,可以将c.next()的值赋值给变量,然后输出查看。
继续执行的c.send(n),将n的值赋给yield表达式,即consumer中n = yield r =10,而c.send(n)的返回值就是下次执行n=yield r中yield的参数r.
第一次调用的时候,需要使用c.next(),或者c.send(None)
推荐几篇yield相关的文章:
http://www.jb51.net/article/15717.htm
http://www.cnblogs.com/huxi/archive/2011/07/14/2106863.html
http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/