生产者、消费者模型

程序1

# 定义生产者函数
def producer():
    arr = []
    for i in range(100):
        arr.append('第%d笼包子' % i)
    return arr
# 定义消费者函数
def customer(arr):
    for i, v in enumerate(arr):
        print('第%d位顾客,%s' %(i, v))
arr = producer()
customer(arr)

程序二

def producer():
    for i in range(100):
        yield '第%d笼包子' % i
def customer():
    g = producer()
    while 1:
        try:
            print(g.__next__())
        except:
            print('卖完啦!')
            break
customer()

send

def test():
    print('开始啦!')
    res = yield 'round one'
    print('%s获胜' % res)
    print('第二回合')
    res = yield 'round two'
    print('%s获胜' % res)
    print('win!')
g = test()
# 开始啦!
g.__next__()
g.send('小猪佩奇')
# 小猪佩奇获胜
# 第二回合

并发

import time
def customer():
    while 1:
        food = yield
        time.sleep(0.2)
        print(food)
def producer():
    c1 = customer()
    c1.__next__()
    for i in range(100):
        time.sleep(0.2)
        c1.send(i)
producer()

猜你喜欢

转载自blog.csdn.net/bus_lupe/article/details/84504157