在Python中,等待(wait)通常與線程(threading)模塊一起使用。以下是一些關于Python線程等待的技巧:
使用threading.Event
:
threading.Event
對象可以用于線程間的簡單信號通知。它有一個set()
方法用于發出信號,一個is_set()
方法用于檢查信號是否已發出,以及一個wait()
方法用于阻塞線程直到信號被發出。
import threading
event = threading.Event()
def worker():
print("Worker thread started")
event.wait() # 阻塞線程直到事件被設置
print("Worker thread finished")
thread = threading.Thread(target=worker)
thread.start()
event.set() # 發出信號,喚醒等待的線程
thread.join()
使用threading.Condition
:
threading.Condition
對象允許一個或多個線程等待某個條件成立。它提供了wait()
方法用于阻塞線程直到條件被滿足,以及notify()
或notify_all()
方法用于喚醒等待的線程。
import threading
condition = threading.Condition()
data = []
def worker():
with condition:
print("Worker thread started")
while not data: # 如果數據為空,則等待
condition.wait()
print(f"Worker thread processed {data[0]}")
data.pop(0)
condition.notify_all() # 喚醒所有等待的線程
threads = [threading.Thread(target=worker) for _ in range(5)]
for thread in threads:
thread.start()
for item in range(5):
with condition:
data.append(item)
condition.notify_all() # 喚醒所有等待的線程
for thread in threads:
thread.join()
使用threading.Semaphore
:
threading.Semaphore
對象用于限制同時訪問共享資源的線程數量。它提供了acquire()
和release()
方法,分別用于嘗試獲取信號量和釋放信號量。當信號量的計數器為零時,線程將被阻塞直到其他線程釋放信號量。
import threading
semaphore = threading.Semaphore(3) # 最多允許3個線程同時訪問
def worker(thread_id):
with semaphore:
print(f"Worker thread {thread_id} started")
print(f"Worker thread {thread_id} finished")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
使用threading.Lock
:
threading.Lock
對象用于確保同一時間只有一個線程可以訪問共享資源。它提供了acquire()
和release()
方法,分別用于嘗試獲取鎖和釋放鎖。當鎖被其他線程持有時,線程將被阻塞直到鎖被釋放。
import threading
lock = threading.Lock()
shared_resource = 0
def worker(thread_id):
global shared_resource
with lock:
print(f"Worker thread {thread_id} started")
shared_resource += 1
print(f"Worker thread {thread_id} finished, shared_resource = {shared_resource}")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
這些技巧可以幫助您更有效地使用Python的線程等待功能。在實際應用中,您可能需要根據具體需求選擇合適的同步原語(如Event
、Condition
、Semaphore
或Lock
)。