本套课在线学习视频(网盘地址,保存到网盘即可免费观看):
链接:https://pan.quark.cn/s/7220b198cf00
在多线程编程中,条件变量是一种用于线程间通信和同步的机制。通过使用条件变量,可以有效地协调线程间的关系,优化资源利用,并减少线程在CPU资源上的不必要占用。本文将通过Python示例代码,详细介绍如何在多线程环境中使用条件变量。
条件变量允许线程在某个条件不满足时进入等待状态,并在条件满足时被唤醒。这样可以避免线程空闲时对CPU资源的占用,并提高程序性能。
- import threading
- import time
-
- # 共享资源
- shared_data = []
- lock = threading.Lock()
- condition = threading.Condition(lock)
-
- class Producer(threading.Thread):
- def __init__(self, name):
- super().__init__()
- self.name = name
-
- def run(self):
- global shared_data
- while True:
- with condition:
- shared_data.append(f"Data from {self.name}")
- print(f"{self.name} produced data")
- condition.notify_all() # 通知所有等待的消费者
- time.sleep(1)
-
- class Consumer(threading.Thread):
- def __init__(self, name):
- super().__init__()
- self.name = name
-
- def run(self):
- global shared_data
- while True:
- with condition:
- while not shared_data:
- print(f"{self.name} is waiting")
- condition.wait() # 等待生产者通知
- data = shared_data.pop(0)
- print(f"{self.name} consumed {data}")
- time.sleep(1)
-
- # 创建生产者和消费者线程
- producers = [Producer(f"Producer-{i}") for i in range(2)]
- 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()
通过引入条件变量,优化了生产者-消费者模型,使得程序在资源不足时能够进入等待状态,并在资源可用时被唤醒继续执行。这种优化方式提高了程序的性能,特别是在资源闲置状态下能够及时释放锁,避免了不必要的阻塞。
- import threading
- import time
- import random
-
- # 共享资源
- buffer = []
- buffer_size = 5
- lock = threading.Lock()
- condition = threading.Condition(lock)
-
- class Producer(threading.Thread):
- def __init__(self, name):
- super().__init__()
- self.name = name
-
- def run(self):
- global buffer
- while True:
- with condition:
- while len(buffer) >= buffer_size:
- print(f"{self.name} is waiting due to full buffer")
- condition.wait() # 等待消费者消费
- item = f"Item from {self.name}"
- buffer.append(item)
- print(f"{self.name} produced {item}")
- condition.notify_all() # 通知所有等待的消费者
- time.sleep(random.random())
-
- class Consumer(threading.Thread):
- def __init__(self, name):
- super().__init__()
- self.name = name
-
- def run(self):
- global buffer
- while True:
- with condition:
- while not buffer:
- print(f"{self.name} is waiting due to empty buffer")
- condition.wait() # 等待生产者生产
- item = buffer.pop(0)
- print(f"{self.name} consumed {item}")
- condition.notify_all() # 通知所有等待的生产者
- time.sleep(random.random())
-
- # 创建生产者和消费者线程
- producers = [Producer(f"Producer-{i}") for i in range(2)]
- 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()
通过这些示例代码,您可以更好地理解如何在Python中使用条件变量来优化多线程编程,特别是在生产者-消费者模型中,条件变量能够显著提高程序的性能和资源利用率。