您的位置:首页 > 编程语言 > Python开发

Python3-线程应用队列(生产者与消费者模式--2生产者VS4消费者)

2018-04-02 14:02 561 查看
#两个厨师对四个顾客

#生产者与消费者模式
'''
定义:
在并发编程中使用生产者和消费都模式能够解决绝大多数并发问题。
该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据
的速度。

案例:
厨师做包子和顾客吃包子问题。
当生产的慢,消费的快的时候,get()会发生阻塞,等待
当生产的忙,消费的快的时候,get_nowait()会发生queue.Empty error
当生产的太快,消费的很慢的时候,队列会很快放满,生产过剩
'''
import threading,queue,time

q=queue.Queue(10)

#生产者
def producer(name):
count=1
while True:
q.put('包子%d'%count)
print('生产了包子%d'%count)
count+=1
time.sleep(0.1)

#消费者
def consumer(name):
count=1
while True:
print('[%s]取到了[%s]包子并且吃了它'%(name,q.get()))#get_nowait()不会阻塞等待
time.sleep(4)

if __name__=='__main__':
p=threading.Thread(target=producer,args=('刘大厨',))
con_A=threading.Thread(target=consumer,args=('A',))
con_B = threading.Thread(target=consumer, args=('B',))
p.start()
con_A.start()
con_B.start()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐