Python--小功能应用

#生产者消费者模型(单线程高并发)
1、低效率模式  产完在统一给
import time
def producter():
    ret = []
    for i in range(10):
        time.sleep(0.1)
        ret.append(i)
    return  ret
def consumer(res):
    for index,baozi in enumerate(res):
        time.sleep(0.1)
        print('第%s个人,吃了%s' %(index,baozi))
res = producter()
print(consumer(res))
2、高效率模式  产一个给一个
import time
def consumer(name):
    print('我是[%s],我在排队买包子' %name)
    while True:
        baozi = yield
        time.sleep(1)   #模拟在achun在吃包子
        print('%s很开心,%s很好吃' %(name,baozi))
def producter():
    population1 = consumer('achun')   #生成器函数
    population1.__next__()
    population2 = consumer('alin')  # 生成器函数
    population2.__next__()
    for i in range(10):
        time.sleep(1)   #模拟在在做包子
        population1.send('鲜肉菜包 %s' %i)
        population2.send('鲜肉菜包 %s' %i)
producter()
 
原文地址:https://www.cnblogs.com/Essaycode/p/10126515.html