在Python中,線程同步可以通過多種方式實現,以確保多個線程在訪問共享資源時不會發生沖突。以下是一些常用的線程同步方法:
使用threading.Lock
類:
Lock
對象可以確保同一時間只有一個線程可以執行被鎖保護的代碼塊。使用acquire()
方法獲取鎖,使用release()
方法釋放鎖。
import threading
lock = threading.Lock()
def critical_section():
lock.acquire()
try:
# 訪問共享資源的代碼
finally:
lock.release()
使用threading.RLock
類:
RLock
對象是可重入鎖,允許同一個線程多次獲取同一個鎖,而不會導致死鎖。
import threading
lock = threading.RLock()
def critical_section():
lock.acquire()
try:
# 訪問共享資源的代碼
finally:
lock.release()
使用threading.Semaphore
類:
Semaphore
對象是一個計數信號量,用于限制同時訪問共享資源的線程數量??梢酝ㄟ^acquire()
方法獲取信號量,使用release()
方法釋放信號量。
import threading
semaphore = threading.Semaphore(3) # 最多允許3個線程同時訪問共享資源
def critical_section():
semaphore.acquire()
try:
# 訪問共享資源的代碼
finally:
semaphore.release()
使用threading.Condition
類:
Condition
對象允許線程等待某個條件成立,然后繼續執行。通過wait()
方法讓線程等待,通過notify()
或notify_all()
方法喚醒等待的線程。
import threading
condition = threading.Condition()
def producer():
with condition:
# 生產數據的代碼
condition.notify_all() # 喚醒所有等待的消費者線程
def consumer():
with condition:
condition.wait() # 等待生產者線程通知數據已準備好
# 消費數據的代碼
使用queue.Queue
類:
Queue
對象是一個線程安全的隊列,用于在多個線程之間傳遞數據。Queue
類內部實現了鎖和條件變量,因此可以確保線程安全。
import threading
import queue
data_queue = queue.Queue()
def producer():
for item in data_source:
data_queue.put(item)
def consumer():
while True:
item = data_queue.get()
if item is None:
break
# 處理數據的代碼
data_queue.task_done()
這些方法可以根據具體需求選擇使用,以確保線程同步。