【1.47】包子模型 - 新 - 协程 - 并发

# coding=utf-8
def producer():
    ret = []
    for i in range(10000):
        ret.append(i)
    return ret


def cousumer(res):
    for index, baozi in enumerate(res):
        print("第%s个人,吃了%s" % (index + 1, baozi + 1))


res = producer()
cousumer(res)

# 本来这是一个并发进行
# 但是这里是生产完包子 才开始吃
# 这样就会占用大量的内存,效率低
# 应该使用生成器模型来

#改写
def test():
    print("开始")
    yield 1
    print("22")
    yield 2
    print("33")
    yield 3
test1=test()
#这里有yield 就是生成器函数
#执行 test1 没有返回值,这里只是拿到了生成器
#执行 __next__ 才会执行下一步    这就是生成器保存状态

print (test1.__next__())  #开始 1 实现从当前状态执行到下一个yield执行完 停下

#触发 生成器运行的方法 3 种方法
#send
#next
#__next__

print(test1.send(None)) #22 2    实现从当前状态执行到下一个yield执行完 停下
#这里我们看看None在哪里
#就是在 他执行 yield 后 的返回值
#1 可以实现next 功能,     2 、可以将send 中的None  值 传给yield 然后再传给 执行yield 的返回值

# print(next(test1))    #33 3     实现从当前状态执行到下一个yield执行完 停下


def cousumer(name,num):
    print("我是%s,我来吃%s个包子"%(name,num))
    while True:
        baozi=yield
        print("%s吃[%s]"%(name,baozi))

def ducu(total):
    for i in range(total):
        yield "包子%s"%i

def maibaozi():  
    total = int((input("开始卖包子了,共计发售:")).strip())
    baozi = total
    a = ducu(total)
    person_num = 1
    while total:
        print (("第%s个顾客"%person_num).center(40,"*"))
        person_num += 1
        print("老板,还有包子没有?\n还有哦。")
        name = (input("你的名字:")).strip()
        num = int((input("你要几个包子:")).strip())
        if total < num:
            print("包子只有%s个了" % total)
            sure = ((input("你还要吗?(y/n)")).lstrip()).upper()
            if sure == "Y":
                num = total
                c1 = cousumer(name, num)
                c1.__next__()
                for i in range(num):
                    c1.send(a.__next__())
            if sure == "N":
                continue
        else:
            c1 = cousumer(name, num)
            c1.__next__()
            for i in range(num):
                c1.send(a.__next__())
        total -= num
    print("今天把包子卖完了,%s个哟,好能干。"%baozi)
maibaozi()

  

posted @ 2016-04-12 14:26  科学小怪癖  阅读(100)  评论(0)    收藏  举报