Python 实现生产者消费者模式

生产者消费者模型

 

 

生产者消费者模式,即多条消费者线程和多条生产者线程共用同一缓冲区,线程之间协调工作。简单来说,生产者将信息发送至缓冲区,消费者将缓冲区的数据取出并进行处理。

 

生产者消费者模式的实现

流程图:

生产者线程产生随机数(信息),将其放入队列,而消费者线程将队列中的数据取出,进行处理。

代码

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

 

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值