Sub topic 11
Sending data between processes: queues, pipes, and pickling costs
This chapter assumes you can start a multiprocessing.Process, know why the __main__ guard is needed, and understand that each process has its own memory. Because memory is not shared, anything a child produces has to be sent to the parent explicitly.
How data crosses a process boundary
Two processes cannot see each other's variables. When you pass an object between them, Python pickles it (serializes it to bytes), writes the bytes to an operating system channel, and the receiver unpickles it (rebuilds an equal copy). The receiver gets a copy, not the original object.
This has three consequences:
- Mutating the copy does not change the original.
- The object must be picklable. Lambdas, open files, locks, and sockets are not.
- Time is spent on serialization, so large objects are expensive to send.
Queues
A multiprocessing.Queue is a process-safe FIFO queue. Several processes can put and get items without extra locking.
from multiprocessing import Process, Queue
def worker(q):
q.put(sum(range(1_000_000)))
if __name__ == "__main__":
q = Queue()
p = Process(target=worker, args=(q,))
p.start()
print(q.get()) # read the result before joining
p.join()Call get() before join(). A child cannot exit until the data it queued has been flushed into the pipe. If the item is large and nobody reads it, the child blocks, and join() waits forever. This is a classic deadlock.
A Queue also supports get(timeout=...) and put_nowait(). Both raise queue.Empty or queue.Full when they cannot proceed, so import those exceptions from the queue module.
Pipes
multiprocessing.Pipe() returns two connected Connection objects. It links exactly two endpoints and is lighter than a queue, but it is not safe if two processes read or write the same end at once.
from multiprocessing import Process, Pipe
def worker(conn):
request = conn.recv()
conn.send(request.upper())
conn.close()
if __name__ == "__main__":
parent_end, child_end = Pipe()
p = Process(target=worker, args=(child_end,))
p.start()
parent_end.send("hello")
print(parent_end.recv()) # HELLO
p.join()| Tool | Endpoints | Safe for many writers | Best for |
|---|---|---|---|
| `Queue` | Many | Yes | Work distribution, collecting results |
| `Pipe` | Two | No | A private channel between a pair |
What pickling costs
Sending an argument to a pool worker and getting a result back both involve pickling. For a tiny task, this overhead can exceed the work itself. The following snippet measures it.
import pickle
import time
data = list(range(5_000_000))
start = time.perf_counter()
blob = pickle.dumps(data)
copy = pickle.loads(blob)
elapsed = time.perf_counter() - start
print(f"{len(blob) / 1e6:.0f} MB, {elapsed:.2f}s round trip")Exact numbers depend on your machine, but a few million elements typically take a noticeable fraction of a second and tens of megabytes. If a worker spends less time computing than you spend shipping its input and output, processes will be slower than a plain loop.
Ways to reduce the cost:
- Send small inputs, such as file paths or index ranges, and let the worker load the data itself.
- Return summaries instead of full intermediate results.
- Batch many small items into one task so the fixed overhead is paid once.
pool.mapaccepts achunksizeargument for this. - For large numeric buffers, look at
multiprocessing.shared_memory, which lets processes map the same block of bytes without copying.
Exercise
A parent process starts a child that puts a 200 MB list on a Queue. The parent calls p.join() and only then calls q.get(). The program hangs. Why, and how do you fix it?
Show answer
The child cannot exit until its queued data has been written into the pipe. The pipe's buffer is far smaller than 200 MB, so the child blocks while writing, and the parent blocks in join() waiting for the child. Fix it by calling q.get() before p.join(), so the parent drains the pipe while the child is still writing. Better still, avoid sending 200 MB through a queue by sending a file path or using shared memory.