python 入坑路-生成器并行运算
通过生成器 yield 单线程,并发处理 。
想把什么返回,就在 前面加 yield ,
by the way: yield 是在函数中,中断,并返回该值,等一下回来,从中断 点开始。保存当前状态,等一下返回。
1 import time 2 3 def consumer(name): 4 print("%s 准备吃包子啦!"%name) 5 while True: 6 baozi = yield 7 8 print("包子[%s]来了,被[%s]吃了!"%(baozi,name)) 9 10 c= consumer("chenkeven") 11 c.__next__() 12 13 #b1="韭菜" 14 #c.send(b1) # 新方法,把b1 发送到 生成器里面 15 #next 只调用 yield , send ,调用,并传值。 16 17 18 def producer(name): 19 c= consumer("A") 20 c2=consumer("B") 21 c.__next__() 22 c2.__next__() 23 print("老子开始准备吃包子啦!") 24 for i in range(10): 25 time.sleep(1) 26 print("做了两个包子") 27 c.send(i) 28 c2.send(i) 29 30 producer("keven")

浙公网安备 33010602011771号