萬盛學電腦網

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

Python threading 模塊深度解析:Thread、Lock、RLock、Condition 與同步模式

threading 模塊概覽

threading 是 Python 標準庫的高級線程接口,模仿 Java 線程模型,提供 Thread、Lock、RLock、Condition、Semaphore、Event、Timer、local 等核心類。

1. Thread 類:創建與管理線程

兩種創建方式

import threading, time

# 方式一:target 函數
def worker(name, delay):
    print(f"{name} start")
    time.sleep(delay)
    print(f"{name} end")

t1 = threading.Thread(target=worker, args=("Thread-1", 1), name="Worker-1")
t1.start()

# 方式二:繼承 Thread 重寫 run()
class MyThread(threading.Thread):
    def __init__(self, name, delay):
        super().__init__(name=name)
        self.delay = delay

    def run(self):
        print(f"{self.name} start")
        time.sleep(self.delay)
        print(f"{self.name} end")

t2 = MyThread("Thread-2", 2)
t2.start()

# 等待結束
t1.join()
t2.join()

構造函數簽名

Thread(group=None, target=None, name=None, args=(), kwargs={}, daemon=None)
  • group:保留字段,必須為 None。
  • daemon:守護線程標誌,默認繼承創建者。主線程結束時守護線程強制終止。

常用實例方法

方法說明
start()啟動線程,調用 run()
join(timeout)阻塞等待線程終止
is_alive()線程是否運行中
name / getName() / setName()線程名稱
ident線程標識符(整數,啟動後有效)
daemon 屬性獲取/設置守護狀態

join() 示例:主線程等待子線程

def child():
    print("Child start")
    time.sleep(2)
    print("Child end")

t = threading.Thread(target=child)
t.start()
print("Main: waiting...")
t.join()
print("Main: child finished")

2. 鎖:Lock vs RLock

Lock:基本互斥鎖

lock = threading.Lock()
lock.acquire()  # 阻塞直到獲取
try:
    # 臨界區
    pass
finally:
    lock.release()

# 上下文管理器寫法(推薦)
with lock:
    # 臨界區
    pass

RLock:可重入鎖

rlock = threading.RLock()
rlock.acquire()
rlock.acquire()  # 同一線程可重複獲取
# 必須 release 兩次才真正釋放
rlock.release()
rlock.release()

選擇原則:默認用 Lock;遞歸函數、同一線程多次進入同一鎖保護區域時用 RLock。

3. Condition:條件變量(生產者-消費者核心)

Condition 內部封裝一把鎖(默認 RLock),提供等待/通知機制。

核心方法(必須在持有鎖時調用)

  • acquire() / release() / with cv::鎖操作
  • wait(timeout):釋放鎖並阻塞,被 notify 喚醒後重新獲取鎖
  • notify(n=1):喚醒 n 個等待線程
  • notify_all():喚醒所有等待線程

經典生產者-消費者模式

import threading, time, random
from collections import deque

buffer = deque(maxlen=5)
cv = threading.Condition()

def producer(name):
    for i in range(10):
        item = f"{name}-{i}"
        with cv:
            while len(buffer) == buffer.maxlen:
                cv.wait()  # 滿了等待
            buffer.append(item)
            print(f"Produced: {item}, buffer={list(buffer)}")
            cv.notify_all()
        time.sleep(random.random() * 0.5)

def consumer(name):
    for _ in range(10):
        with cv:
            while not buffer:
                cv.wait()  # 空了等待
            item = buffer.popleft()
            print(f"Consumed: {item}, buffer={list(buffer)}")
            cv.notify_all()
        time.sleep(random.random() * 0.5)

threading.Thread(target=producer, args=("P1",)).start()
threading.Thread(target=producer, args=("P2",)).start()
threading.Thread(target=consumer, args=("C1",)).start()
threading.Thread(target=consumer, args=("C2",)).start()

4. 其他同步原語速覽

類用途關鍵方法
Semaphore(value)限制並發訪問數acquire(), release()
BoundedSemaphore防止 release 超過初始值同上
Event線程間標誌信號set(), clear(), wait(), is_set()
Timer(interval, func)延時執行一次start(), cancel()
local()線程局部存儲local.data = 1 每線程獨立

5. 模塊級工具函數

threading.current_thread()   # 當前 Thread 對象
threading.enumerate()        # 所有活躍線程列表
threading.active_count()     # 活躍線程數
threading.main_thread()      # 主線程對象 (3.4+)
threading.get_ident()        # 當前線程標識符 (3.3+)

6. GIL 影響與繞過策略

  • CPython GIL 導致同一時刻只有一個線程執行字節碼。
  • I/O 密集型(網絡、磁盤、用戶輸入):線程有效,I/O 時釋放 GIL。
  • CPU 密集型(計算、圖像處理):線程無法並行,改用:
    • multiprocessing.Process 多進程(繞過 GIL,獨立內存)
    • concurrent.futures.ProcessPoolExecutor 進程池
    • C 擴展(NumPy、Pandas、Cython)釋放 GIL 進行計算

7. 最佳實踐清單

  1. 共享數據必須加鎖,使用 with lock: 確保釋放。
  2. 條件變量操作必須在鎖內,避免竊態條件。
  3. 避免死鎖:固定鎖獲取順序、使用 RLock、設置 acquire(timeout)。
  4. 守護線程用於後台服務,主業務用非守護線程並 join()。
  5. 線程數不可無限增長,使用線程池(concurrent.futures.ThreadPoolExecutor)。
  6. CPython 3.2+ threading 實現基於 _thread C 模塊,性能穩定。
copyright © 萬盛學電腦網 all rights reserved