multiprocessing 是 Python 標準庫的跨平台並行框架,繞過 GIL 限制,利用多核 CPU 實現真並行。核心類 Process 模擬 threading.Thread 接口,學習成本極低。
from multiprocessing import Process
import os
def worker():
print(f"Worker PID: {os.getpid()}, PPID: {os.getppid()}")
if __name__ == "__main__": # Windows 必須保護入口
print(f"Main PID: {os.getpid()}")
p = Process(target=worker)
p.start()
p.join() # 等待子進程結束
print("Child process finished")
# ❌ 錯誤:主進程 PID 在子進程創建前獲取,子進程中不變
def bad_worker(parent_pid):
print(f"Child PID: {os.getpid()}, Parent PID (stale): {parent_pid}")
# ✅ 正確:子進程內部獲取實時 PPID
def good_worker():
print(f"Child PID: {os.getpid()}, Real PPID: {os.getppid()}")
def chain(level, max_level):
level += 1
print(f"Level {level}: PID={os.getpid()}, PPID={os.getppid()}")
if level < max_level:
p = Process(target=chain, args=(level, max_level))
p.start()
p.join()
if __name__ == "__main__":
Process(target=chain, args=(0, 5)).start()
輸出示例:
Level 1: PID=13581, PPID=13580
Level 2: PID=13582, PPID=13581
Level 3: PID=13583, PPID=13582
Level 4: PID=13584, PPID=13583
Level 5: PID=13585, PPID=13584
def fan_worker(index):
print(f"Worker {index}: PID={os.getpid()}, PPID={os.getppid()}")
def fan_out(count):
processes = []
for i in range(count):
p = Process(target=fan_worker, args=(i,))
processes.append(p)
p.start()
# 關鍵:等待所有子進程
for p in processes:
p.join()
print(f"Parent {os.getpid()} reaped all {count} children")
輸出特徵:所有子進程 PPID 相同(父進程 PID),執行順序不確定。
from multiprocessing import Pool
def square(x):
return x * x
if __name__ == "__main__":
with Pool(processes=4) as pool:
results = pool.map(square, range(10))
print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 異步提交
async_result = pool.apply_async(square, (7,))
print(async_result.get(timeout=1)) # 49
| 機制 | 適用場景 | 特點 |
|---|---|---|
Queue | 多生產者/消費者 | 線程/進程安全,支援超時 |
Pipe | 雙向點對點通信 | 輕量,雙端 conn1, conn2 = Pipe() |
Manager | 共享字典/列表/鎖 | 代理對象,網絡透明,性能較低 |
Value/Array | 共享標量/陣列 | 共享內存,需手動同步(Lock) |
p.daemon = True 主進程退出時自動終止子進程Queue 收集異常信息resource.setrlimit 限制內存/CPU,防止 Fork 炸彈with Process(...) as p: (Python 3.3+) 自動 joinmultiprocessing.set_start_method('spawn') 跨平台一致性(默認 fork)multiprocessing 讓 Python 輕鬆突破 GIL 瓶頸,合理設計進程拓撲能充分發揮多核性能。