函数执行到yield发生了中断,并且保存了函数的中断状态,单纯调用next会调用yield但不会给yield传值,send的作用是调用yield并给yield传值。
这样就模拟出了两个线程交替执行的情况。
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
def producer(name):
p1 = consumer('A')
p2 = consumer('B')
c.__next__()
c2.__next__()
print(“ %s 开始准备做包子啦!” ,name)
for i in range(10):
time.sleep(1)
p1.send(i)
p2.send(i)
print(“ %s 做了1个包子,分两半!” %name)
consumer("Chen")
producer(“Echo”)