Python 实现生产者消费者模式

生产者消费者模型

 

Python 实现生产者消费者模式_第1张图片

 

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

 

生产者消费者模式的实现

流程图:Python 实现生产者消费者模式_第2张图片

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

代码

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

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

 

你可能感兴趣的:(python,生产者消费者模式)