# 这里我们要介绍一下协程的机制,协程是在单个线程内让两个函数交替执行的一种形式 # 以著名问题生产者和消费者作为基底进行讨论 def consumer(): return_str = '' while True: print(1) n = yield return_str if not n: return print("消费者正在消费{}".format(n)) return_str = "200 OK" def producer(c): next(c) n = 0 while n < 5: n = n + 1 print("生产者正在生产{}".format(n)) return_str = c.send(n) print("消费者收到消息返回{}".format(return_str)) c.close() con = consumer() producer(con)