1. 程式人生 > >初識python: 生成器並行(做包子,吃包子)

初識python: 生成器並行(做包子,吃包子)

 知識點:

send(i) :喚醒yield,並將 i 的值傳給 yield

例項:

#!/user/bin env python
# author:Simple-Sir
# time:20181020
# 單執行緒併發:做一個包子,兩個人吃
import time
# 吃包子生成器
def chibaozi(name):
    print('%s想吃包子了!' %name)
    while True:
        baozi = yield #
        print('第%s個包子來了,被%s吃了一半!'%(baozi,name))

# 邏輯解析
# c = chibaozi('SimpleGirl') # c.__next__() # 喚醒yield # b1='牛肉包子' # c.send(b1) # 注:喚醒yield,並將b1的值傳給 yield # 做包子生成器 def zuobaozi(name): c1 = chibaozi('SimpleSir') c2 = chibaozi('SimpleGirl') c1.__next__() c2.__next__() print('%s開始做包子了!'%name) for i in range(1,6): time.sleep(
1) print('%s做了1個包子!'%name) c1.send(i) c2.send(i) # 呼叫函式 zuobaozi('SimpleSir')
單執行緒併發:做一個包子,兩個人吃

執行結果: