使用yield实现协程效果

 1 #!/usr/bin/env python
 2 # -*-coding:utf-8 -*-
 3 
 4 import time
 5 def consumer(name):
 6     print(name)
 7     while True:
 8         bone = yield   #接收send发送的数据
 9         print('%s ,the %d number'%(name,bone))
10         print("---------------------------------")
11         time.sleep(0.2)
12         
13 def producer(con):
14     con.send(None)   #必须先发送None
15     for i in range(5):
16         print('producer %d'%i)
17         con.send(i)
18 if __name__ == "__main__":
19     con = consumer('consumerA')  #创建消费者对象
20     producer(con)

 

 posted on 2021-04-29 00:09  boye169  阅读(65)  评论(0编辑  收藏  举报