“Talk is cheap, show me the code.”
废话不多说,直接上代码:
"""
生产者消费者模型 Python实现
"""
import queue
import threading
import random
import time
class ConsProd:
# 队列参数
_que = None # 队列
# 生产者参数
_producer_num = 0 # 生产者数量
_prod_block_time = 0.0 # 生产者阻塞时间
_prod_work_time = 0.0 # 生产者生产耗时
# 消费者参数
_consumer_num = 0 # 消费者数量
_cons_block_time = 0.0 # 消费者阻塞时间
_cons_work_time = 0.0 # 消费者消费耗时
def __init__(self, que_size=4, producer_num=4, consumer_num=3, prod_work_time=0.5, cons_work_time=0.3,
prod_block_time=1.0, cons_block_time=1.0):
self._que_size = que_size
self._producer_num = producer_num
self._consumer_num = consumer_num
self._prod_work_time = prod_work_time
self._cons_work_time = cons_work_time
self._prod_block_time = prod_block_time
self._cons_block_time = cons_block_time
# 生产者逻辑
def __produce(self):
while True:
if self._que.full():
print(f"生产者线程 {threading.currentThread().getName()}: 队列已满,阻塞中...")
time.sleep(self._prod_block_time)
else:
time.sleep(self._prod_work_time)
product = random.randint(0, 100)
print(f"生产者线程 {threading.currentThread().getName()}: 生产了一个值为 {product} 的数字")
self._que.put(product)
# 消费者逻辑
def __consume(self):
while True:
if self._que.empty():
print(f"消费者线程 {threading.currentThread().getName()}: 队列已空,阻塞中...")
time.sleep(self._cons_block_time)
else:
time.sleep(self._cons_work_time)
consumption = self._que.get()
print(f"消费者线程 {threading.currentThread().getName()}: 消费了一个值为 {consumption} 的数字")
def start(self):
# 初始化队列
self._que = queue.Queue(self._que_size)
# 生产者线程组
pro = [threading.Thread(name="prod-" + str(i), target=self.__produce)
for i in range(0, self._producer_num)]
# 消费者线程组
csm = [threading.Thread(name="cons-" + str(i), target=self.__consume)
for i in range(0, self._consumer_num)]
# 启动所有线程
for c in csm:
c.start()
for p in pro:
p.start()
if __name__ == "__main__":
demo = ConsProd(que_size=16,
producer_num=6,
consumer_num=4,
cons_work_time=0.2,
prod_work_time=0.4)
demo.start()