python学习-40 生产者和消费者模型

import time
def buy(name):                      # 消费者
    print('%s上街去买蛋' %name)
    while True:
        eggs=yield
        print('%s买了%s' %(name,eggs))


def product_eggs():              # 生产者
    a =buy('小明')
    a.__next__()
    for i  in range(1,11):
        time.sleep(1)
        a.send('%s个鸡蛋' %i)

product_eggs()

运行结果:

小明上街去买蛋
小明买了1个鸡蛋
小明买了2个鸡蛋
小明买了3个鸡蛋
小明买了4个鸡蛋
小明买了5个鸡蛋
小明买了6个鸡蛋
小明买了7个鸡蛋
小明买了8个鸡蛋
小明买了9个鸡蛋
小明买了10个鸡蛋

Process finished with exit code 0

 

posted @ 2019-07-17 20:47  学python的菜鸟  阅读(230)  评论(0编辑  收藏  举报