Lesson · Multiprocessing
Inter-Process Communication
75 min readInter-Process Communication
Processes communicate through queues, pipes, shared memory, managers, files, or other IPC mechanisms. Each option trades convenience, copying cost, synchronization needs, and portability.
Learning goals
- Choose between a queue, a pipe, shared memory, and a manager for a given data flow, and defend the choice by topology and copying cost.
- Use a pipe's
send/recvpair between a parent and one child and explain where each call blocks. - Predict the deadlock that appears when both ends call
recv()first, and verify it safely withpoll(timeout). - Use a manager list to collect writes from several children and explain how the proxy keeps the parent's view coherent.
- Explain when shared memory removes a copying cost and what synchronization it pushes onto your code.
Mental model
The channels are alternatives, not a ladder: pick by topology (one reader or many), by what crosses the boundary (tiny messages or megabytes), and by who synchronizes access. Queues buffer and serialize for you; pipes connect exactly two ends; shared memory skips the copies and hands you the locking problem; managers keep ordinary objects usable at the cost of a round trip per operation.
Mental model
read it top to bottom
need to move data between processes (nothing is shared live) ↓ who talks, and how much data crosses? Queue many to many, buffered handoff, serialized copies Pipe exactly two ends, direct send/recv, lighter than a queue shared_memory large arrays, no repeated copies, you synchronize access Manager ordinary objects behind a server process, a round trip per call
Core idea
Inter-process communication is the bridge across process isolation, and the mechanism you pick decides how much data is copied and who coordinates access. Queues buffer many-to-many handoffs, pipes connect exactly two ends, shared memory avoids repeated copies at the price of manual synchronization, and managers trade speed for convenience. Choose the simplest channel that matches the exchange, then keep send and receive counts matched so no process waits forever.
Queues
A queue creates an explicit handoff point between producers and consumers. Bounded queues also provide backpressure, while thread/process/async queue types differ in how they synchronize and move data.
Pipes
multiprocessing.Pipe() returns a pair of Connection objects: one process writes with send(), the other reads with recv(), and the data arrives as a serialized copy. It is the lightest channel for a direct exchange between exactly two ends, but it buffers less than a queue: a recv() blocks until a message arrives, and a send() of a large payload blocks once the operating system buffer fills. Closing the sending end makes the other end's recv() raise EOFError instead of waiting forever.
Shared memory overview
Shared memory can avoid repeated serialization of large data, but once memory is shared the program must coordinate access explicitly. It trades copying cost for synchronization complexity.
Manager objects
A multiprocessing.Manager() starts a server process that owns ordinary Python objects, such as a dict, list, or Namespace, and hands out proxy objects that other processes can use like the originals. Each call on a proxy round-trips to the server, which applies the change under its own lock and sends the answer back, so individual operations are safe but compound check-then-act sequences can still interleave. The manager, and its server process, must stay alive for as long as any proxy is used.
Tradeoffs
The right channel follows the exchange pattern and the data size: queues for many-to-many handoffs, pipes for a single pair of ends, shared memory for large arrays that must not be copied per message, managers for small objects where convenience matters more than speed. Judge the options on copying cost, synchronization burden, and failure visibility for the actual workload, because no single mechanism leads on all three.
Walkthrough
Pipe()returns twoConnectionends, andargs=(child,)hands one end to the child process; afterstart(), each process holds one end of the same channel.parent.send(21)writes a serialized 21 into the channel; the child'sconnection.recv()unblocks, reads it, and sends backvalue * 2, which the parent collects withparent.recv(). The exchange works only because the two sides agree on who talks when: every send pairs with a receive at the other end.connection.close()releases the child's end of the channel, andprocess.join()waits for the child to exit, so the reply is already in hand before the program ends and no process is left running.- Predict before running: what
parent.recv()prints, and what would happen if the parent calledparent.recv()before itssend(21).
Experiments to try
- Reproduce the deadlock safely: in a scratch copy, move the parent's
recv()before itssend()and callparent.poll(2.0)instead ofrecv(); the poll returns False because the child is blocked inrecv()waiting for a message the parent has not sent. Send the value afterwards so the script can finish, and explain why the originalrecv()would have waited forever. - Change the worker to close its end without reading or sending, remove the parent's
send, and read theEOFErrorthatrecv()raises; this is how a reader learns that the writer is gone. - Replace the pipe with a
multiprocessing.Queue: the child puts its doubled value, the parent gets it, and you compareput/getwithsend/recvfor call shape and buffering. - Start a
Manager(), share a manager list with two children that append one item each, and print the list in the parent after joining both; explain where each append actually executed and why a plain list would lose it.
Common mistakes
- Calling
recv()before a matchingsend(): the read parks until a message arrives or the sending end closes, so a missing or misordered reply hangs the reader; guard uncertain reads withpoll(timeout). - Sending a large payload through a pipe nobody is reading: the operating system buffer fills and the sender blocks inside
send(), which looks identical to a deadlock from the outside. - Treating a manager proxy like a local object: each method call round-trips to the server, which locks only for that one call, so a check-then-act sequence between two processes can still interleave.
- Reusing a connection after
close(): the wrapper is finished, and further operations raiseOSErrorinstead of reconnecting; keep each end owned by one process and close it when that process is done.
Practice: Easy
- Run the worked example and list the four exchange calls in execution order (parent send, child recv, child send, parent recv), marking which process executes each; then change 21 and predict the printed value before running.
- Replace
Pipewith aQueuein the example: the child putsvalue * 2, the parent gets it, and confirm the output is unchanged. - Send a dict from the parent, have the child add a key, and send it back; check the types on both sides to confirm values travel as full copies.
Practice: Medium
- Build a two-message protocol over one pipe: the parent sends two numbers, the child reads both and returns their sum; keep send and recv counts matched on both ends.
- Guard a receive with
parent.poll(1.0): build a child that never replies and show that poll returns False rather than hanging, then say whenrecv()would have blocked forever. - Collect writes from three children into a manager list; print it after all joins and explain where each append actually happened, and why a plain list would come back empty.
Practice: Hard
- Build a three-stage pipeline: A sends numbers through a pipe to B, B doubles them and forwards through a second pipe to C, which prints; define who closes which end so no stage blocks at shutdown.
- Break the exchange on purpose three ways: a
recv()with no matchingsend(), a writer that closes its end, and a check-then-act sequence on a manager value run by two processes; explain the mechanism behind each failure and the signal that makes it visible (poll,EOFError, the server lock). - Measure three routes for one 10 MB
bytespayload: through aPipe, through aQueue, and intomultiprocessing.shared_memory; time each and explain the results with serialization and copying.
Lesson checklist
- I can pick a channel for a data flow and justify it by topology, size, and synchronization cost.
- I can trace one send/receive round trip and say exactly where each end blocks.
- I can reproduce the receive-first deadlock safely with
poll()and explain why it happens. - I can explain what a manager proxy does per call and where its atomicity stops.
Remember
Inter-process communication is how isolated processes exchange anything at all, and the channel you choose sets the copying cost and the coordination burden. Queues buffer many-to-many handoffs, pipes connect exactly two ends, shared memory removes repeated serialization of large data, and managers keep ordinary objects usable through a server process. Whatever the channel, keep sends and receives paired and guard uncertain reads with `poll()`, because a process that waits on a message that never comes never finishes.
Interview angles
What is the main purpose of **Queues**?+
A queue creates an explicit handoff point between producers and consumers. Bounded queues also provide backpressure, while thread/process/async queue types differ in how they synchronize and move data.
What should you pay attention to when using **Pipes**?+
Pipe() hands back two Connection objects, one per end: send() on one side pairs with recv() on the other, and the data arrives as a serialized copy. A recv() blocks until a message arrives or the sending end closes (then it raises EOFError), which is why a reply that might never come needs poll(timeout) rather than a bare recv().
How does **Shared memory overview** fit into this lesson?+
Shared memory can avoid repeated serialization of large data, but once memory is shared the program must coordinate access explicitly. It trades copying cost for synchronization complexity.
Why does a `recv()` that runs before any `send()` block forever on a fresh pipe?+
A pipe is a direct connection, not a queue that stores messages for later: recv() parks until a send() writes data or the sending end closes. If both processes call recv() first, neither ever writes, so neither ever returns.