参考
提高:现在还是看不懂
Python “黑魔法” 之 Generator Coroutines
代码分析
#!/usr/bin/env python
import time
def consumer():
r = ''
while True:
n = yield r
print '[CONSUMER] Consuming ', n
time.sleep(1)
r = '200 OK'
def produce(c):
print 'c.next:', c.next()
n = 0
while n < 5:
n += 1
print '[PRODUCER] Producing ', n
r = c.send(n)
print '[PRODUCER] Consumer return: ', r
c.close()
if __name__ == '__main__':
c = consumer()
produce(c)
输出:
c.next:
[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
从main开始,首先是生成器实例化
c = consumer()
然后把这个生成器作为参数扔到produce函数里。
c.next()
先执行第一遍的consumer。一直到遇上yield,yield把r返回给调用者。但是对consumer而言,只是将r返回了,n还没接收到东西(没接收到produce的send)
r = ''
while True:
n = yield r
在这里,其实给c.next()返回了一个空字符串r,produce函数接收到空字符串后将其输出。
在produce函数继续执行,输出
[PRODUCER] Producing 1
然后给cosumer发送了n=1
r = c.send(n)
consumer获得了1
n = yield r
将其输出
[CONSUMER] Consuming 1
然后consumer休眠1秒,然后将r赋值,再循环,执行到yield,给produce函数返回了r = '200 OK'
produce函数接收到回复r,将r打印出来
[PRODUCER] Consumer return: 200 OK
如此循环下去。