Python生成器生产者消费者

通过生成器实现的生产者消费者模型。
没有用到多线程与多进程,协程异步就更没用到了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import time
def consumer():
msg = 'Here'
while True:
info = yield msg
if not info:
return
print '[顾客] 吃第%s个煎饼,RUA!RUA!RUA!' % info
time.sleep(2)
msg = '吃完第%s个了。。' % str(info)
def producer(c):
start_consumer = c.next()
n = 0
while n < 5:
n = n + 1
if n == 5:
print '[厨师] 有完没完啊。不玩了!'
break
print '[厨师] 开始做第%s个煎饼...' % n
time.sleep(1)
print '小伙子等一会啊。。。'
time.sleep(2)
print '做好嘞!接着!'
time.sleep(1)
info = c.send(n)
print '[顾客]说: %s' % info
time.sleep(2)
c.close()
producer(consumer())