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,便於系統級排查 |
Lock(互斥鎖)acquire() 會死鎖。with lock: 上下文管理器自動釋放,防止異常洩漏。RLock(可重入鎖)
rlock = threading.RLock()
rlock.acquire()
rlock.acquire() # 同一線程不阻塞
rlock.release()
rlock.release()
內部維護 _owner + _count,適用於遞歸函數、嵌套調用同一鎖的場景。**效能略低於 Lock**,非必要勿用。
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 循環中(防止虛假喚醒)。
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() 可重置。
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()
控制併發度、資源池大小(如連接池)。
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,單生產單消費無需鎖。multiprocessing、concurrent.futures.ProcessPoolExecutor、C 擴展(NumPy、Pandas)、cython、pybind11 或異步 asyncio。ThreadPoolExecutor / queue.Queue 高層抽象,減少手動同步。try/finally 確保釋放鎖,或用 with。name,便於 threading.enumerate()、日誌、除錯器識別。daemon=True 用於後台清理、心跳,主程序退出不等待。threading 提供完整的用戶級線程與同步原語,理解 Lock/RLock/Condition/Event/Semaphore/Barrier 的語義差異與適用場景,是編寫正確、高併發 Python 程序的基石。實際項目中**優先使用高層抽象(concurrent.futures, queue, asyncio)**,僅在底層協議實現、C 擴展交互、特殊同步需求時直接操作 threading。