首页 > 代码库 > python3--生成器并行运算

python3--生成器并行运算

# Auther: Aaron Fan

"""
def consumer(name):
print("%s 准备吃包子啦!" % name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" % (baozi, name))

people = consumer("FanHeng")
people.__next__()

stuffing = "胡萝卜陷"
people.send(stuffing) #把stuffing的值传给生成器consumer中的yield,并调用yield

people.__next__() # 单纯的调用next不会给yield传值,仅仅是调用yield。所以程序显示的是:
# 包子[None]来了,被[FanHeng]吃了!

stuffing = ["韭菜馅", "牛肉馅", "黄金菜团"]
for i in stuffing:
people.send(i)
"""

# 完整的演示一个协程:
# 原理和上面的示例是一样的,都是用的yield和send来实现,只是这个示例使用了两个函数互相协作去完成了一个生产包子和吃包子的功能
import time
def consumer(name):
print("%s 准备吃包子啦!" % name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" % (baozi, name))


def producer(name):
people1 = consumer(‘Aaron‘)
people2 = consumer(‘James‘)
people1.__next__()
people2.__next__()
for i in range(6):
time.sleep(1)
print("\n做了1个包子,分成了两半")
people1.send(i)
people2.send(i)

producer("FanHeng")

python3--生成器并行运算