python yield实现协程(生产者-消费者)

def customer():
    r=""
    while True:
        n=yield r#,接收生产者的消息,并向消费者发送r
        print("customer receive",n)
        r="ok"

def produce(c):
    c.send(None)#第一次启动协程必须发送None值,否则报如下错误
    #TypeError: can't send non-None value to a just-started generator
    for i in range(6):
        print("start send to customer",i)
        r=c.send(i)#向消费者发送值
        print("receive customer",r)

c=customer()
produce(c)
start send to customer 0
customer receive 0
receive customer ok
start send to customer 1
customer receive 1
receive customer ok
start send to customer 2
customer receive 2
receive customer ok
start send to customer 3
customer receive 3
receive customer ok
start send to customer 4
customer receive 4
receive customer ok
start send to customer 5
customer receive 5
receive customer ok

简单的生产者-消费者模型就这样生成了!

yield不仅可以yield r发送数据,还可以接收数据n=yield,或者同时接收并发送数据n=yield r接收n发送r

传统的生产者-消费者模型是一个线程写消息,一个线程取消息,通过锁机制控制队列和等待,但一不小心就可能死锁。

如果改用协程,生产者生产消息后,直接通过yield跳转到消费者开始执行,待消费者执行完毕后,切换回生产者继续生产,效率极高

 

posted @ 2019-12-07 01:17  腹肌猿  阅读(827)  评论(0编辑  收藏  举报