标签:team while 生产者消费者 包子 关于 调用 赋值 author pen
之前的学习内容,由于没有申请开通博客,就没有分享,今天想分享一下学习内容:通过yield实现在单线程的情况下实现并发运算的效果
采用的是经典的生产消费者模型
定义了两个函数 Consumer与Producer
关于生成器标志yield : 如果用__next__访问,只是单纯调用yield ;如果是send访问,不仅可以访问yield,也可以给yield赋值!
需求:一个人造包子;两个人吃包子;
代码如下:
1 # -*- coding:utf-8 -*- 2 # Author : 何子辰 3 4 # 单线程也可以实现并行运算 5 # 生产者消费者模型 6 7 import time 8 9 def Consumer(name): 10 print(‘%s has started to eat the steamed stuffed bun!‘%name) 11 while True: 12 SS_bun = yield 13 print(‘The %s is coming,but eaten by %s!‘%(SS_bun,name)) 14 15 def Producer(name): 16 C1 = Consumer(‘Luna‘) 17 C2 = Consumer(‘Iriving‘) 18 C1.__next__() 19 C2.__next__() 20 print(‘Hzc is starting to make the steamed stuff bun!!‘) 21 for i in range(10): 22 time.sleep(1) 23 Buns = [‘韭菜馅‘,‘鲅鱼馅‘] 24 print(‘Hzc has made two buns, the first one is %s,the second one is %s‘%(‘韭菜馅‘,‘鲅鱼陷‘)) 25 C1.send(Buns[0]) 26 C2.send(Buns[1]) 27 28 29 Producer(‘HZC‘)
2017/9/5的学习内容___通过yield实现在单线程的情况下实现并发运算的效果
标签:team while 生产者消费者 包子 关于 调用 赋值 author pen
原文地址:http://www.cnblogs.com/IrivingLoveLuna/p/7482530.html