模拟python中的Yield伪并发

并发,在操作系统中,是指一个时间段中有几个程序都处于已启动运行到运行完毕之间,且这几个程序都是在同一个处理机上运行,但任一个时刻点上只有一个程序在处理机上运行。

#Yield伪并发
_author_='lanyinhao'
import  time
def consumer(name):
    print("%s准备吃包子啦!"%name)
    while True:
        baozi=yield
        print("包子[%s]来了,被[%s]吃了!"%(baozi,name))

def producer(name):
    c=consumer("lanyinhao1")
    c2=consumer("lanliuchen")
    #c.__next__()#到这一步才开始第一次打印,因为是生成器需要next调用,如果第一次没有next,对象不懂赋值给哪个会报错
    #c2.__next__()
    next(c)#等价于c2.__next__
    next(c2)
    print("老子开始准备做包子啦")
    for i in range(3):
        time.sleep(1)
        print("做了两个包子")
        c.send(i)#直接·跳入yield中执行
        c2.send(i)
producer("lanyinhao")

猜你喜欢

转载自www.cnblogs.com/lanyinhao/p/9138045.html
今日推荐