生产者消费者模型
生产者消费者模式,即多条消费者线程和多条生产者线程共用同一缓冲区,线程之间协调工作。简单来说,生产者将信息发送至缓冲区,消费者将缓冲区的数据取出并进行处理。
生产者消费者模式的实现
流程图:
生产者线程产生随机数(信息),将其放入队列,而消费者线程将队列中的数据取出,进行处理。
代码
main.py
import producer
import consumer
import threading
import queue
#初始化
q_data=queue.Queue(maxsize=1000)
event=threading.Event()
lock=threading.Lock()
if event.isSet:
event.clear()
for each in range(5):
c=consumer.Consumer(each,q_data,event,lock,5000)
p=producer.Producer(each,q_data,event,5000)
c.start()
p.start()
q_data.join()
producer.py
import threading
import random
class Producer(threading.Thread):
def __init__(self,name,queue,event,num):
threading.Thread.__init__(self)
self.name="生产者"+str(name)
self.queue=queue
self.event=event
self.num=num
self.count=0
def run(self):
while self.count<self.num:
#判断栈是否已经满
if self.queue.full():
#栈满 线程进入等待
self.event.wait()
#线程唤醒后将flag设置为False
if self.event.isSet():
self.event.clear()
else:
#判断栈是否为空,为空则在向栈添加数据后,则将Flag设置为True,
#唤醒前所有在等待的消费者线程
if self.queue.empty():
#未满 向栈添加数据
data=random.randint(0,5000)
self.queue.put(data)
print(self.name+" produced data "+ str(data))
#将Flag设置为True
self.event.set()
else:
#未满 向栈添加数据
data=random.randint(0,5000)
self.queue.put(data)
print(self.name+" produced data "+ str(data))
self.count+=1
consumer.py
import threading
class Consumer(threading.Thread):
def __init__(self,name,queue,event,lock,num):
threading.Thread.__init__(self)
self.name="消费者"+str(name)
self.queue=queue
self.event=event
self.lock=lock
self.num=num
self.count=0
def run(self):
while self.count<self.num:
#判断栈是否为空
if self.queue.empty():
#栈空 线程进入等待
self.event.wait()
#线程唤醒后将flag设置为False
if self.event.isSet():
self.event.clear()
else:
#判断栈是否已满,为满则在向栈取数据后,则将Flag设置为True,
#唤醒前所有在等待的生产者线程
if self.queue.full():
#未满 向栈添加数据
self.lock.acquire()
data=self.queue.get()
self.queue.task_done()
self.lock.release()
print(self.name+" Spend data "+ str(data))
#将Flag设置为True
self.event.set()
else:
#未满 向栈添加数据
self.lock.acquire()
data=self.queue.get()
self.queue.task_done()
self.lock.release()
print(self.name+" Spend data "+ str(data))
self.count+=1