
共享數據並發訪問導致競態條件。鎖確保臨界區互斥訪問:

acquire,需配對 release。解決「生產者-消費者」等待/通知問題:

wait():釋放鎖並等待通知notify():喚醒一個等待線程notify_all():喚醒所有等待線程
Condition.wait()sleep()、join()、I/O(不釋放已持有鎖)thread(不推薦生產使用)import thread, time
def func():
for i in range(5):
print('func')
time.sleep(1)
lock = thread.allocate_lock()
thread.start_new_thread(func, ())
time.sleep(6) # 主線程等待,否則子線程隨主線程退出
缺點:無守護線程控制、無條件變量、無高級同步原語、主線程結束強制殺死子線程。
threading(標準選擇)import threading, time
# 方式一:傳入 target 函數
def worker():
print(f"{threading.current_thread().name} running")
t1 = threading.Thread(target=worker, name="Worker-1")
t1.start()
# 方式二:繼承 Thread 重寫 run()
class MyThread(threading.Thread):
def run(self):
print(f"{self.name} running")
t2 = MyThread(name="Worker-2")
t2.start()
# 等待線程結束
t1.join()
t2.join()
name/getName()/setName():線程名ident:線程標識符(啟動後有效)is_alive():是否運行中daemon:守護線程標誌(主線程結束時自動終止)join(timeout):阻塞等待線程結束# Lock:不可重入,第二次 acquire 會死鎖
lock = threading.Lock()
lock.acquire()
lock.acquire() # 死鎖!
# RLock:可重入,同一線程多次 acquire 需配對 release
rlock = threading.RLock()
rlock.acquire()
rlock.acquire() # OK
rlock.release()
rlock.release() # 真正釋放
import threading
buffer = []
cv = threading.Condition()
def producer():
for i in range(5):
with cv:
buffer.append(i)
print(f"Produced {i}")
cv.notify() # 通知消費者
time.sleep(0.1)
def consumer():
for _ in range(5):
with cv:
while not buffer:
cv.wait() # 等待通知,釋放鎖並阻塞
item = buffer.pop(0)
print(f"Consumed {item}")
threading.Thread(target=producer).start()
threading.Thread(target=consumer).start()
關鍵模式:with cv: 獲取鎖 → 條件檢查 → wait() 釋放鎖並等待 → 被喚醒後重新獲取鎖 → 處理數據。
wait()/set()/clear()。CPython 全局解釐器鎖(GIL)導致同一時刻只有一個線程執行字節碼。
multiprocessing 多進程或 C 擴展(NumPy、Cython)繞過 GIL。threading 高級 API,避免 thread。with lock: 上下文管理器。wait/notify。RLock、設置 acquire(timeout)。multiprocessing.Process 或進程池。