Back
+20 XP
Concept

Inter-Process Communication with multiprocessing.Pipe

`multiprocessing.Pipe()` returns a pair of connected duplex endpoints `(conn1, conn2)`. It enables direct point-to-point communication between two isolated processes using OS-level socket pairs 🚰.

python
import multiprocessing

def worker(conn):
    conn.send("Task finished 🚰")
    conn.close()

if __name__ == "__main__":
    parent_conn, child_conn = multiprocessing.Pipe()
    p = multiprocessing.Process(target=worker, args=(child_conn,))
    p.start()
    print(f"Parent received: {parent_conn.recv()}")
    p.join()

# 76. Inter-Process Communication with multiprocessing.Pipe `multiprocessing.Pipe()` returns a pair of connected duplex endpoints `(conn1, conn2)`. It enables direct point-to-point communication between two isolated processes using OS-level socket pairs 🚰. ```python import multiprocessing def worker(conn): conn.send("Task finished 🚰") conn.close() if __name__ == "__main__": parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=worker, args=(child_conn,)) p.start() print(f"Parent received: {parent_conn.recv()}") p.join() ``` By default, pipes are bidirectional (`duplex=True`). If you only need one-way data transfer, pass `duplex=False` to save system resources and prevent accidental write collisions 🛡️! --- ### Question What makes `multiprocessing.Pipe()` faster than `multiprocessing.Queue()` for point-to-point IPC? 🧠 - [ ] a. A Pipe is a direct OS socketpair/pipe without feeder thread lock contention overhead 🚰 - [ ] b. A Pipe stores unpickled raw Python pointers directly inside CPU registers - [ ] c. A Pipe bypasses the Linux kernel entirely using hardware DMA interrupts - [ ] d. A Pipe disables memory protection boundaries between parent and child --- ### Challenge Create a `multiprocessing.Pipe()`. In a child process, send `42 * 2`. In the parent, receive it, join the process, and print the integer. 🎯 <details> <summary>Solution</summary> ```python import multiprocessing def worker(conn): conn.send(42 * 2) conn.close() if __name__ == '__main__': parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=worker, args=(child_conn,)) p.start() val = parent_conn.recv() p.join() print(val) ``` </details>

Checkpoint

What makes `multiprocessing.Pipe()` faster than `multiprocessing.Queue()` for point-to-point IPC? 🧠

Practice

Create a `multiprocessing.Pipe()`. In a child process, send `42 * 2`. In the parent, receive it, join the process, and print the integer. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks