# yield 相当于return,控制的返回值
# res = yield 的另外一个特性,接收send传过来的值,赋值给res
def yieldTest():
print("刘备")
res = yield 1
print("关羽", res)
yield 2
print("张飞")
yield 3
g = yieldTest()
res = g.__next__() # next(g)
print(res)
res = g.send("赵云") # send()也能出发生成器的执行
print(res)
通过yield实现单线程并发模式
def killMonster(name):
while True:
monNum = yield
print("%s 正在杀[第%s个]怪物" % (name,monNum))
def playRole():
g1 = killMonster("关公")
g2 = killMonster("拿破仑")
g1.__next__()
g2.__next__()
for i in range(10):
g1.send(i+1)
g2.send(i+1)
playRole()