multiprocessing.Pipe() 回傳 (conn1, conn2) 兩個 Connection 物件,雙向通訊,類似雙工管道。
import multiprocessing
def consumer(out_pipe, in_pipe):
in_pipe.close() # 消費者只讀
while True:
try:
item = out_pipe.recv()
print(f"Consumed: {item}")
except EOFError:
break
print("Consumer done")
def producer(seq, in_pipe):
for item in seq:
in_pipe.send(item)
in_pipe.close() # 關閉寫入端 → 對方收到 EOFError
if __name__ == '__main__':
out_p, in_p = multiprocessing.Pipe()
c = multiprocessing.Process(target=consumer, args=(out_p, in_p))
c.start()
out_p.close() # 主進程只寫
producer([1, 2, 3, 4], in_p)
c.join()
def worker(conn):
while True:
cmd = conn.recv()
if cmd == 'exit':
break
result = cmd * 2
conn.send(result)
conn.close()
if __name__ == '__main__':
parent, child = multiprocessing.Pipe()
p = multiprocessing.Process(target=worker, args=(child,))
p.start()
for i in range(5):
parent.send(i)
print(f"Result: {parent.recv()}")
parent.send('exit')
p.join()
| 特性 | Pipe | Queue |
|---|---|---|
| 連接數 | 點對點 (1 對 1) | 多對多 |
| 雙向 | 原生雙向 | 單向 (需兩個 Queue) |
| 緩衝 | OS 管道緩衝 (~64KB) | 可設 maxsize |
| 序列化 | pickle | pickle |
| 效能 | 略快 (較輕量) | 略慢 (鎖開銷) |
if __name__ == '__main__': 保護下建立進程 (Windows 必須)recv() 永不收到 EOFshared_memory 或 mmap