本套课在线学习视频(网盘地址,保存到网盘即可免费观看):
链接:https://pan.quark.cn/s/20887ab45e97
生产者和消费者模式是一种常见的多线程编程模式,通过将任务划分为生产数据和消费数据两部分,实现代码的清晰分工与高效维护。本文将通过Python示例代码,详细介绍如何在多线程环境中实现生产者-消费者模式。
00:00 - 多线程编程:生产者与消费者模式详解
创建生产者和消费者线程
生产者线程负责生成随机金钱数额并不断增加到总金额中,而消费者线程则负责消耗这些金额。为防止数据竞争,使用了锁机制来同步对全局变量的操作。
import threading
import random
import time
# 全局变量
total_amount = 0
lock = threading.Lock()
class Producer(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
global total_amount
while True:
amount = random.randint(100, 1000)
with lock:
total_amount += amount
print(f"{self.name} produced {amount}, total amount is {total_amount}")
time.sleep(random.random())
class Consumer(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
global total_amount
while True:
amount = random.randint(100, 1000)
with lock:
if total_amount >= amount:
total_amount -= amount
print(f"{self.name} consumed {amount}, total amount is {total_amount}")
else:
print(f"{self.name} tried to consume {amount}, but insufficient funds")
time.sleep(random.random())
# 创建生产者和消费者线程
producers = [Producer(f"Producer-{i}") for i in range(3)]
consumers = [Consumer(f"Consumer-{i}") for i in range(3)]
# 启动线程
for producer in producers:
producer.start()
for consumer in consumers:
consumer.start()
# 等待线程结束(这里实际上是无限循环,所以不会结束)
for producer in producers:
producer.join()
for consumer in consumers:
consumer.join()
04:35 - 消费者线程的消费逻辑及其同步问题
消费者通过继承threading.Thread类创建,并实现一个无限循环以不断进行消费。消费过程中会从全局总金额中随机扣除一个值(100到5000之间的随机整数),并判断是否足够支付。若总金额充足,则执行扣款操作,并输出消费信息;否则,输出余额不足的信息。
class Consumer(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
global total_amount
while True:
amount = random.randint(100, 5000)
with lock:
if total_amount >= amount:
total_amount -= amount
print(f"{self.name} consumed {amount}, total amount is {total_amount}")
else:
print(f"{self.name} tried to consume {amount}, but insufficient funds")
time.sleep(random.random())
07:11 - 多线程下的生产者-消费者模型实现
本次讨论重点在于使用多线程技术实现生产者-消费者模型,通过创建多个生产者和消费者线程进行模拟生产和消费过程。首先介绍如何通过in range
语句创建特定数量的线程实例,并指定它们的名字和执行的任务。接着探讨了如何通过传递参数以及设置循环次数来控制生产者和消费者的运行行为,以达到预期的模拟效果。
# 创建生产者和消费者线程
producers = [Producer(f"Producer-{i}") for i in range(3)]
consumers = [Consumer(f"Consumer-{i}") for i in range(3)]
# 启动线程
for producer in producers:
producer.start()
for consumer in consumers:
consumer.start()
# 等待线程结束(这里实际上是无限循环,所以不会结束)
for producer in producers:
producer.join()
for consumer in consumers:
consumer.join()
增加延时以保证公平性
通过增加延时,可以保证各线程有平等的机会执行,从而提升模型的公平性。
class Producer(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
global total_amount
while True:
amount = random.randint(100, 1000)
with lock:
total_amount += amount
print(f"{self.name} produced {amount}, total amount is {total_amount}")
time.sleep(random.random())
class Consumer(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
global total_amount
while True:
amount = random.randint(100, 5000)
with lock:
if total_amount >= amount:
total_amount -= amount
print(f"{self.name} consumed {amount}, total amount is {total_amount}")
else:
print(f"{self.name} tried to consume {amount}, but insufficient funds")
time.sleep(random.random())
通过这些示例代码,您可以更好地理解如何在Python中使用多线程技术实现生产者-消费者模式,并通过锁机制确保数据的一致性和程序的正确运行。