import multiprocessing
def consumer(q):
while True:
item = q.get()
if item is None: # 毒丸結束信號
break
print(f"Consumed: {item}")
q.task_done()
def producer(seq, q):
for item in seq:
q.put(item)
q.put(None) # 發送結束信號
if __name__ == '__main__':
q = multiprocessing.JoinableQueue()
c = multiprocessing.Process(target=consumer, args=(q,))
c.daemon = True
c.start()
producer(range(10), q)
q.join() # 等待所有 task_done()
print("All done")
from multiprocessing import Process, Pipe
def consumer(pipe_out, pipe_in):
pipe_in.close() # 關閉寫入端
while True:
try:
item = pipe_out.recv()
print(f"Got: {item}")
except EOFError:
break
def producer(seq, pipe_in):
pipe_out, _ = Pipe() # 只需寫入端
for item in seq:
pipe_in.send(item)
pipe_in.close() # 關閉觸發 EOF
if __name__ == '__main__':
out_p, in_p = Pipe()
c = Process(target=consumer, args=(out_p, in_p))
c.start()
out_p.close() # 主進程關閉讀取端
producer(range(5), in_p)
c.join()
| 特性 | Queue | Pipe |
|---|---|---|
| 模型 | 多生產者/多消費者 | 點對點(一讀一寫) |
| 緩衝 | 可設 maxsize | 無限緩衝(OS 管道限制) |
| 同步 | 內建鎖、條件變數 | OS 管道原子讀寫 |
| 序列化 | pickle(較慢) | pickle(同) |
| 適用 | 工作池、任務分發 | 雙向 RPC、父子進程通訊 |
multiprocessing.Array / Value:C 類型陣列/標量,無 pickle 開銷shared_memory (Python 3.8+):跨進程原始記憶體區塊manager.list() / dict():代理物件,支援任意 Python 物件但較慢Queue 適合多對多任務分發;Pipe 適合雙向點對點通訊。大量數據傳遞優先考慮共享記憶體或序列化優化(msgpack, orjson)。