在Python中,處理復雜的線程交互需要考慮以下幾個方面:
import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
for _ in range(100000):
lock.acquire()
counter += 1
lock.release()
def decrement():
global counter
for _ in range(100000):
lock.acquire()
counter -= 1
lock.release()
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=decrement)
t1.start()
t2.start()
t1.join()
t2.join()
print("Counter:", counter)
queue.Queue
,可以用于在多線程環境中安全地傳遞數據。import threading
import queue
def worker(q):
while True:
item = q.get()
if item is None:
break
# 處理item
q.task_done()
q = queue.Queue()
for i in range(10):
q.put(i)
threads = []
for _ in range(4):
t = threading.Thread(target=worker, args=(q,))
t.start()
threads.append(t)
q.join() # 等待所有任務完成
for _ in range(len(threads)):
q.put(None) # 通知線程退出
for t in threads:
t.join()
concurrent.futures.ThreadPoolExecutor
來管理線程,這樣可以避免頻繁地創建和銷毀線程帶來的開銷。import concurrent.futures
def process_item(item):
# 處理item
return item * 2
items = [1, 2, 3, 4, 5]
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(process_item, items))
print("Results:", results)
threading
模塊的Event
對象:Event
對象可以用于線程間的簡單通信,例如通知線程停止執行。import threading
import time
stop_event = threading.Event()
def worker():
while not stop_event.is_set():
# 執行任務
time.sleep(1)
t = threading.Thread(target=worker)
t.start()
time.sleep(5) # 讓線程運行一段時間
stop_event.set() # 通知線程停止執行
t.join()
threading
模塊的Barrier
對象:Barrier
對象可以用于多個線程之間的同步,當所有線程都到達屏障點時,它們才會繼續執行。import threading
def worker(barrier):
print(f"Thread {threading.current_thread().name} is waiting at barrier.")
barrier.wait() # 等待其他線程到達屏障點
print(f"Thread {threading.current_thread().name} has arrived at barrier.")
barrier = threading.Barrier(3) # 設置屏障點,需要等待3個線程到達
t1 = threading.Thread(target=worker, args=(barrier,))
t2 = threading.Thread(target=worker, args=(barrier,))
t3 = threading.Thread(target=worker, args=(barrier,))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
通過以上方法,可以處理Python多線程編程中的復雜線程交互問題。在實際應用中,需要根據具體場景選擇合適的同步原語和數據結構。