本套課在線學習視頻(網盤地址,保存到網盤即可免費觀看):
鏈接:https://pan.quark.cn/s/7220b198cf00
在多線程編程中,條件變量是一種用于線程間通信和同步的機制。通過使用條件變量,可以有效地協調線程間的關系,優化資源利用,并減少線程在CPU資源上的不必要占用。本文將通過Python示例代碼,詳細介紹如何在多線程環境中使用條件變量。
00:00 - 多線程編程中的條件變量及其優化
使用條件變量優化線程間的協調與資源利用
條件變量允許線程在某個條件不滿足時進入等待狀態,并在條件滿足時被喚醒。這樣可以避免線程空閑時對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 = namedef run(self):global shared_datawhile 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 = namedef run(self):global shared_datawhile 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()
02:02 - 條件變量實現生產者-消費者模型
通過引入條件變量,優化了生產者-消費者模型,使得程序在資源不足時能夠進入等待狀態,并在資源可用時被喚醒繼續執行。這種優化方式提高了程序的性能,特別是在資源閑置狀態下能夠及時釋放鎖,避免了不必要的阻塞。
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 = namedef run(self):global bufferwhile 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 = namedef run(self):global bufferwhile 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中使用條件變量來優化多線程編程,特別是在生產者-消費者模型中,條件變量能夠顯著提高程序的性能和資源利用率。