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

时间:2023-11-24 15:23:50
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():
print("start send to customer",i)
r=c.send(i)#向消费者发送值
print("receive customer",r) c=customer()
produce(c)
start send to customer
customer receive
receive customer ok
start send to customer
customer receive
receive customer ok
start send to customer
customer receive
receive customer ok
start send to customer
customer receive
receive customer ok
start send to customer
customer receive
receive customer ok
start send to customer
customer receive
receive customer ok

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

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

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

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