生产包子吃包子
第一种方法
生产包子
import time
def producer():
ret=[]
for i in range(100):
#time.sleep(0.1)
ret.append('包子%s'%i)
return ret #吃包子
def consumer(res):
for index,baozi in enumerate(res):
#time.sleep(0.1)
print('第%s个人,吃了%s'%(index,baozi))
res=producer()
consumer(res)
yield相当于return :控制函数的返回值
yield另外特性就是:接收send穿回来的返回值,赋值给x
def test1():
print('开始啦')
first=yield 1 #return = 1 first = None
print('第一次',first)
yield 2
print('第二次')
t=test1()
res=t.__next__() #next(t)
print(res)
#t.__next__()《====》t.send(None)#结果相同,
res=t.send('函数停留在first那个位置,我就是给first赋值的')
print(res)
吃包子
def consumer(name):
print('我是[%s],我准备开始吃包子' %name)
while True:
baozi=yield
print('%s 很开心吧[%s]吃掉了' %(name,baozi))
# for index,baozi in enumerate(res):
# #time.sleep(0.1)
# print('第%s个人,吃了%s'%(index,baozi))
c1=consumer('lzp')
c1.__next__()
c1.send('羊肉包子')
## 3.单线程-并发 生产包子吃包子(最终版本)
import time
#吃包子
def consumer(name):#消费者
print('我是[%s],我准备开始吃包子' %name)
while True:
baozi=yield
time.sleep(1)
print('%s 很开心吧[%s]吃掉了' %(name,baozi))
def producer():#生产者
c1=consumer('lzp')#产生吃货
c2=consumer('wjs')
c1.__next__()
c2.__next__()
for i in range(10):
time.sleep(1)
c1.send('羊肉包子%s' %i)
c2.send('羊肉包子%s' %i)
producer()