萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 多程序機制實戰:multiprocessing 佇列與生產者-消費者模式完整範例

為什麼需要多程序?

Python **GIL (全域解譯器鎖)** 限制單一程序同一時間只能執行一條位元組碼指令。CPU 密集型任務若要發揮多核心效能,必須使用 multiprocessing 啟動獨立程序,各自擁有獨立記憶體空間與 GIL。

核心架構:生產者-消費者 + JoinableQueue

import multiprocessing
import os
import time
import queue  # Python 3: queue, Python 2: Queue

def producer(q, filepath):
    pid = os.getpid()
    print(f"[Producer {pid}] 開始讀取 {filepath}")
    with open(filepath, 'r') as f:
        for line in f:
            line = line.strip()
            q.put(line)
            print(f"[Producer {pid}] 放入: {line} | 隊列大小: {q.qsize()}")
            time.sleep(0.1)  # 模擬 IO 延遲
    # 發送結束信號 (每個消費者一個)
    for _ in range(q._writer._reader._num_consumers):  # 內部屬性,僅示意
        q.put(None)
    q.close()
    print(f"[Producer {pid}] 完成")

def consumer(q, consumer_id):
    pid = os.getpid()
    print(f"[Consumer {consumer_id} PID={pid}] 啟動")
    while True:
        try:
            item = q.get(timeout=2)  # 設定超時避免永久阻塞
            if item is None:  # 結束信號
                q.task_done()
                break
            print(f"[Consumer {consumer_id} PID={pid}] 處理: {item}")
            time.sleep(0.5)  # 模擬處理耗時
            q.task_done()
        except queue.Empty:
            print(f"[Consumer {consumer_id}] 隊列超時空閒,退出")
            break
    print(f"[Consumer {consumer_id}] 結束")

if __name__ == "__main__":
    # 建立有界隊列,防止記憶體暴增
    task_queue = multiprocessing.JoinableQueue(maxsize=10)

    # 準備測試資料檔案
    test_file = "data.txt"
    with open(test_file, 'w') as f:
        f.write("\n".join([f"line-{i}" for i in range(1, 6)]))

    # 啟動 1 生產者 + 3 消費者
    processes = []
    processes.append(multiprocessing.Process(target=producer, args=(task_queue, test_file)))
    for i in range(3):
        processes.append(multiprocessing.Process(target=consumer, args=(task_queue, i)))

    for p in processes:
        p.start()
    for p in processes:
        p.join()

    print("所有程序結束")

關鍵技術點解析

1. JoinableQueue vs Queue

  • JoinableQueue 提供 task_done() 與 join(),允許生產者等待所有任務處理完畢。
  • q.join() 會阻塞直到每個 put() 都有對應的 task_done()。

2. 結束信號設計模式

**毒丸模式**:生產者結束前放入 N 個 None (N = 消費者數量),每個消費者收到一個即退出。

3. 程序間通訊 (IPC) 序列化

multiprocessing.Queue 內部使用 pickle 序列化物件。**注意:** 傳遞大型物件會有效能開銷;共享記憶體請用 multiprocessing.Array/Value 或 shared_memory (Python 3.8+)。

4. 程序池替代手動管理

from multiprocessing import Pool

def process_line(line):
    time.sleep(0.5)
    return line.upper()

if __name__ == "__main__":
    with open("data.txt") as f:
        lines = [l.strip() for l in f]

    with Pool(processes=3) as pool:
        results = pool.map(process_line, lines)
    print(results)

Pool 內建工作分配、結果收集、異常傳播,適用於**資料並行**任務。

5. 觀察程序狀態

# 終端機執行
ps -ef | grep python
# 可見主程序與多個子程序並行運行

常見陷阱與最佳實踐

陷阱解決方案
主程序結束前子程序未結束必須呼叫 p.join() 或設定 daemon=True (但 daemon 程序會被強制終止,不執行 finally)
Queue 滿/空導致死鎖使用有界隊列 maxsize + 超時 get(timeout=...) + 明確結束信號
Windows 下缺少 if __name__ == "__main__" 導致無限遞迴產生程序**務必**將啟動程式碼放入此區塊
大量資料序列化效能差改用共享記憶體 multiprocessing.shared_memory 或外部儲存 (Redis/檔案/DB)
例外在子程序中被吞沒使用 Pool 或手動在子程序捕獲並透過 Queue 回傳異常資訊
copyright © 萬盛學電腦網 all rights reserved