生成器-生产者消费模式
1,用普通方法实现
def producer(): ret=[] for i in range(100): ret .append('包子%s'%i) return ret def consumer(res): for index,baozi in enumerate(res): print('第%s个人,吃了%s'%(index,baozi)) res = producer() consumer(res)
2,用生成器方法实现
def consumer(name): print('我是[%s],吃咸平'%name) while True: baozi=yield print('%s开心【%s】吃掉'%(name,baozi)) def producer(): c1=consumer('kkk') c2=consumer('sss') c1.__next__() c2.__next__() for i in range(1,11): c1.send('咸平%s'%i) c2.send('咸平%s'%i) producer()

浙公网安备 33010602011771号