在 Python 中實現多任務處理,主要有兩種方式:多進程與多線程。進程是由一個或多個線程組成的,線程是作業系統直接支援的執行單元。Python 內建了對多線程的支援,其線程實際上是真正的 POSIX Thread,而非模擬實現。標準庫提供了 thread(低階)與 threading(高階封裝)兩個模組,實際開發中幾乎只需使用 threading。
啟動一個線程的方式是將目標函數傳入 Thread 建構子,並呼叫 start() 方法:
import time, threading
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n += 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
執行結果顯示主線程 MainThread 建立子線程 LoopThread 並等待其結束。若未指定名稱,Python 會自動命名為 Thread-1、Thread-2 等。
多線程共享全域變數時,若多線程同時修改同一變數,極易導致資料錯亂。例如兩個線程各自對 balance 進行 10 萬次「先存後取」操作,理論結果應為 0,但實際執行往往不為 0。原因在於 balance = balance + n 並非原子操作,而是分為「計算暫存」與「寫回」兩步,線程切換會導致覆蓋。
透過 threading.Lock() 建立鎖,確保同一時間只有一個線程能進入關鍵區段:
balance = 0
lock = threading.Lock()
def change_it(n):
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
with lock:
change_it(n)
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance) # 穩定輸出 0
with lock: 區塊會自動獲取與釋放鎖,避免忘記釋放導致死鎖。這是 Python 多線程編程中保障資料一致性的核心手段。
Python 的全域解譯器鎖(GIL)導致同一時刻只有一個線程能執行 Python 位元組碼,因此多線程在 CPU 密集型任務上無法發揮多核優勢。對於 IO 密集型任務(如網路請求、檔案讀寫),多線程仍能顯著提升效能;若需利用多核進行計算,建議改用 multiprocessing 多進程方案。