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()
#生产者与消费者模式
'''
定义:
在并发编程中使用生产者和消费都模式能够解决绝大多数并发问题。
该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据
的速度。
案例:
厨师做包子和顾客吃包子问题。
当生产的慢,消费的快的时候,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()
相关文章推荐
- Python3-线程应用队列(生产者与消费者模式--多生产者VS多消费者)
- python进阶:Python进程、线程、队列、生产者/消费者模式、协程
- python生产者与消费者模式:队列实现线程通信、ThreadLocal、GIL
- 每天学习一算法系列(31)(实现一个队列,队列的应用场景为:一个生产者线程将int 类型的数入列,一个消费者线程将int 类型的数出列)
- 11.python并发入门(part8 基于线程队列实现生产者消费者模型)
- java生产者消费者问题(线程同步与线程等待的应用)
- [知了堂学习笔记]_线程通信(生产者和消费者模式)
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- 多线程应用--生产者、消费者模式
- 进程与线程,同步与死锁,生产者消费者模式
- Java线程实现Redis任务队列(生产者消费者)
- 同步线程--生产者与消费者模式
- 使用阻塞队列实现生产者-消费者模式——Java实现
- [原创]如何编写多个阻塞队列连接下的多生产者多消费者的Python程序
- 多线程之消费者生产者模式加入阻塞队列
- java生产者消费者问题(线程同步与线程等待的应用)
- 生产者/消费者模式(阻塞队列)
- Python 第九篇:队列Queue、生产者消费者模型、(IO/异步IP/Select/Poll/Epool)、Mysql操作
- Java线程(三):线程协作-生产者/消费者模式
- 生产者/消费者模式(阻塞队列) 一个经典的并发模型