生成器并行运算

还可通过yield实现在单线程的情况下实现并发运算的效果

import time
def consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
        baozi = yield

        print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
c = consumer("ChenRongHua")
c.__next__()

def producer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("我开始做包子啦!")
    for i in range(10):
        time.sleep(2)
        print("做了2个包子!")
        c.send(i)
        c2.send(i)

producer("zhuziqin")

 

 

 

  

posted @ 2017-08-26 19:29  _Cohen  阅读(94)  评论(0)    收藏  举报