title: 《Python-yield的简单练习》—yield实现单线程下的并行
date: 2017-07-06 10:40
tag: -Python
主要练习yield的使用,理解其作用。
代码实现
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
@author: 烽火
@license: Apache Licence
@file: yield_test.py
@time: 7/6/17 9:30 AM
"""
"""
利用yield,将函数变为生成器,同时可以实现.单线程下的并行.(简单的生产者消费者模型)
"""
import time
def consumer(name):
print("%s准备开始消费..."%name)
while True:
goods = yield
if goods == "q":
break
else:
print("%s 消费 %s"%(name, goods))
def produce(*consumers):
for i in range(10):
time.sleep(1)
goods = "馒头[%d]"%i;
for c in consumers:
c.send(goods)
c1 = consumer("张飞")
c2 = consumer("李逵")
c1.__next__()
c2.__next__()
produce(c1, c2)