threading 是 Python 標準庫的高級線程接口,模仿 Java 線程模型,提供 Thread、Lock、RLock、Condition、Semaphore、Event、Timer、local 等核心類。
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 屬性 | 獲取/設置守護狀態 |
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")
lock = threading.Lock()
lock.acquire() # 阻塞直到獲取
try:
# 臨界區
pass
finally:
lock.release()
# 上下文管理器寫法(推薦)
with lock:
# 臨界區
pass
rlock = threading.RLock()
rlock.acquire()
rlock.acquire() # 同一線程可重複獲取
# 必須 release 兩次才真正釋放
rlock.release()
rlock.release()
選擇原則:默認用 Lock;遞歸函數、同一線程多次進入同一鎖保護區域時用 RLock。
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()
| 類 | 用途 | 關鍵方法 |
|---|---|---|
Semaphore(value) | 限制並發訪問數 | acquire(), release() |
BoundedSemaphore | 防止 release 超過初始值 | 同上 |
Event | 線程間標誌信號 | set(), clear(), wait(), is_set() |
Timer(interval, func) | 延時執行一次 | start(), cancel() |
local() | 線程局部存儲 | local.data = 1 每線程獨立 |
threading.current_thread() # 當前 Thread 對象
threading.enumerate() # 所有活躍線程列表
threading.active_count() # 活躍線程數
threading.main_thread() # 主線程對象 (3.4+)
threading.get_ident() # 當前線程標識符 (3.3+)
multiprocessing.Process 多進程(繞過 GIL,獨立內存)concurrent.futures.ProcessPoolExecutor 進程池with lock: 確保釋放。RLock、設置 acquire(timeout)。join()。concurrent.futures.ThreadPoolExecutor)。threading 實現基於 _thread C 模塊,性能穩定。