《Python-yield的简单练习》---yield实现单线程下的并行

主要练习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)

运行结果

这里写图片描述

发布了170 篇原创文章 · 获赞 55 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/w695050167/article/details/74528481
今日推荐