萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python threading 模組核心機制深度解析:Thread、Lock、RLock、Condition、Event、Semaphore、Barrier

線程基礎:兩種創建方式

方式一:繼承 Thread 重寫 run()


import threading, time, random

counter = 0
lock = threading.Lock()

class CounterThread(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)
    def run(self):
        global counter
        for _ in range(10000):
            with lock:
                counter += 1

threads = [CounterThread(f"T-{i}") for i in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print(counter)  # 50000

方式二:Thread(target=fn, args=(), kwargs={})


def worker():
    global counter
    for _ in range(10000):
        with lock:
            counter += 1

threads = [threading.Thread(target=worker, name=f"W-{i}") for i in range(5)]
for t in threads: t.start()
for t in threads: t.join()

推薦方式二:解耦邏輯與線程控制,便於複用、測試、傳遞參數。

Thread 常用屬性與方法

屬性/方法說明
name / getName() / setName()線程名稱,預設 "Thread-N"
ident線程標識符(整數),start() 後才有值
is_alive()是否存活(start 後到 run 結束前)
daemon守護線程標誌,主線程結束時強制退出,預設 False
join(timeout=None)阻塞等待線程結束,超時返回
native_id (3.8+)內核級線程 ID,便於系統級排查

同步原語全景

1. Lock(互斥鎖)

  • 不可重入:同一線程重複 acquire() 會死鎖。
  • with lock: 上下文管理器自動釋放,防止異常洩漏。

2. RLock(可重入鎖)


rlock = threading.RLock()
rlock.acquire()
rlock.acquire()  # 同一線程不阻塞
rlock.release()
rlock.release()

內部維護 _owner + _count,適用於遞歸函數、嵌套調用同一鎖的場景。**效能略低於 Lock**,非必要勿用。

3. Condition(條件變量)

綁定一把鎖(默認 RLock),支援 wait()/notify()/notify_all(),實現「生產者-消費者」經典模式。


import collections, threading, time, random

queue = collections.deque()
cv = threading.Condition()
MAXSIZE = 10

def producer():
    for i in range(20):
        with cv:
            while len(queue) >= MAXSIZE:
                cv.wait()
            queue.append(i)
            print(f"Produced {i}")
            cv.notify()
        time.sleep(random.random()*0.1)

def consumer():
    while True:
        with cv:
            while not queue:
                cv.wait()
            item = queue.popleft()
            print(f"Consumed {item}")
            cv.notify()
        time.sleep(random.random()*0.2)

threading.Thread(target=producer, daemon=True).start()
threading.Thread(target=consumer, daemon=True).start()
time.sleep(3)

關鍵:wait() 會**原子性釋放鎖並掛起**,被喚醒後**重新獲取鎖**再返回,故條件判斷必須在 while 循環中(防止虛假喚醒)。

4. Event(事件標誌)


event = threading.Event()

def waiter():
    print("Waiting...")
    event.wait()
    print("Notified!")

def notifier():
    time.sleep(2)
    event.set()

threading.Thread(target=waiter).start()
threading.Thread(target=notifier).start()

一次性廣播,clear() 可重置。

5. Semaphore(信號量)


sem = threading.Semaphore(3)  # 允許 3 並發

def limited_task(i):
    with sem:
        print(f"Task {i} running")
        time.sleep(1)
        print(f"Task {i} done")

for i in range(10):
    threading.Thread(target=limited_task, args=(i,)).start()

控制併發度、資源池大小(如連接池)。

6. Barrier(屏障,3.2+)


barrier = threading.Barrier(3)

def worker(i):
    print(f"Worker {i} phase 1")
    barrier.wait()
    print(f"Worker {i} phase 2")

for i in range(3):
    threading.Thread(target=worker, args=(i,)).start()

所有參與者到達 wait() 才同時繼續,適用於多階段同步(如 MapReduce Map 階段結束)。

線程安全數據結構

  • queue.Queue:線程安全 FIFO,內部用 Condition,支援 put/get 阻塞、超時、task_done/join 完成追蹤。
  • queue.LifoQueue、queue.PriorityQueue 變體。
  • collections.deque:CPython 實現原子 append/pop,單生產單消費無需鎖。

GIL 影響與繞過策略

  • CPython GIL 導致 CPU 密集型多線程無法利用多核。
  • I/O 密集型(網絡、磁碟、睡眠)釋放 GIL,多線程有效。
  • CPU 密集型改用 multiprocessing、concurrent.futures.ProcessPoolExecutor、C 擴展(NumPy、Pandas)、cython、pybind11 或異步 asyncio。

最佳實踐清單

  1. 優先用 ThreadPoolExecutor / queue.Queue 高層抽象,減少手動同步。
  2. 鎖粒度最小化:只保護共享狀態,不鎖 I/O、計算。
  3. 避免嵌套鎖 → 死鎖風險;必須嵌套時**固定獲取順序**。
  4. 所有共享可變對象訪問加鎖,或用不可變數據傳遞。
  5. 異常處理:try/finally 確保釋放鎖,或用 with。
  6. 設置有意義的 name,便於 threading.enumerate()、日誌、除錯器識別。
  7. 守護線程 daemon=True 用於後台清理、心跳,主程序退出不等待。

總結

threading 提供完整的用戶級線程與同步原語,理解 Lock/RLock/Condition/Event/Semaphore/Barrier 的語義差異與適用場景,是編寫正確、高併發 Python 程序的基石。實際項目中**優先使用高層抽象(concurrent.futures, queue, asyncio)**,僅在底層協議實現、C 擴展交互、特殊同步需求時直接操作 threading。

copyright © 萬盛學電腦網 all rights reserved