Sub topic 11
Sending data between processes: queues, pipes, and pickling costs
This chapter assumes you can start a multiprocessing.Process, know why the if __name__ == "__main__": guard matters, and understand that each process has its own memory. If those are unfamiliar, review the chapters on processes and start methods first.
Why processes need explicit data passing
Threads share one address space. A list that one thread appends to is visible to every other thread. Processes do not work this way. Each process has its own copy of the interpreter and its own objects. When a child process changes a global variable, the parent never sees it.
from multiprocessing import Process
results = []
def worker():
results.append(42)
print("child sees:", results)
if __name__ == "__main__":
p = Process(target=worker)
p.start()
p.join()
print("parent sees:", results)The child prints [42]. The parent prints []. To get data across the boundary, the operating system has to carry bytes from one process to another. Python's multiprocessing module gives you several tools for this, and all of them turn objects into bytes first.
Pickling: the price of every transfer
Python converts objects to bytes with the pickle module. This step is called serialization, or pickling. The receiving side turns the bytes back into an object, which is called unpickling. Queues, pipes, and the arguments and return values of pool functions all use pickle.
This has three consequences.
- Transfers copy data. The receiver gets a new object that is equal to the original, not the same object. Changing it does not change the sender's copy.
- Not everything can be pickled. Lambdas, nested functions, open file handles, locks, and sockets fail. Instances of classes defined inside a function also fail.
- Large objects are slow to move. Time spent pickling, copying through the operating system, and unpickling counts against any speedup you hoped to get.
You can see the failure directly:
import pickle
try:
pickle.dumps(lambda x: x + 1)
except Exception as exc:
print(type(exc).__name__, exc)
data = {"name": "job-1", "values": [1, 2, 3]}
blob = pickle.dumps(data)
print(len(blob), "bytes")
print(pickle.loads(blob) == data)The lambda raises a pickling error, because pickle stores functions by their importable name and a lambda has none. The dictionary round-trips and compares equal to the original.
Measuring the cost
Before sending data between processes, measure how long the round trip takes. This example times pickling for payloads of different sizes.
import pickle
import time
def measure(label, obj):
start = time.perf_counter()
blob = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
pickle.loads(blob)
elapsed = time.perf_counter() - start
print(f"{label:<28} {len(blob) / 1e6:8.2f} MB {elapsed * 1000:8.1f} ms")
measure("small dict", {"a": 1, "b": 2})
measure("1M ints in a list", list(range(1_000_000)))
measure("1M-char string", "x" * 1_000_000)
measure("100k small tuples", [(i, str(i)) for i in range(100_000)])Exact numbers vary by machine. The pattern is stable. A flat blob such as a long string or a bytes object pickles quickly. A large collection of many small Python objects pickles slowly, because pickle has to visit each one.
multiprocessing.Queue
multiprocessing.Queue is the most common way to move results out of a child. It is safe for several producers and several consumers. Internally, put() hands the object to a background feeder thread in the sending process. That thread pickles it and writes it to a pipe. get() reads from the pipe and unpickles.
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()The comment about reading before joining matters. A child that has put data on a queue does not exit until its feeder thread has flushed all buffered data into the pipe. The pipe has a limited buffer. If the item is large and the parent calls join() before get(), the child waits for the parent to read, and the parent waits for the child to exit. Neither moves. Always drain the queue before joining.
A producer and consumer with a sentinel
With several items, the consumer needs a way to know the producer has finished. A common pattern is a sentinel, a special value placed at the end.
from multiprocessing import Process, Queue
SENTINEL = None
def producer(q, n):
for i in range(n):
q.put({"id": i, "square": i * i})
q.put(SENTINEL)
if __name__ == "__main__":
q = Queue()
p = Process(target=producer, args=(q, 5))
p.start()
while True:
item = q.get()
if item is SENTINEL:
break
print(item)
p.join()Note that None survives pickling as None, and is works here because None is a singleton. If you use a custom sentinel object, compare with == or use a value that pickles to itself, because an unpickled object() is a different object.
Bounded queues and back pressure
Queue(maxsize=N) blocks put() once N items are waiting. This gives back pressure: a fast producer cannot fill memory while a slow consumer falls behind. Without a limit, the queue grows until memory runs out.
Queue methods to know
| Method | Behavior |
|---|---|
| `put(obj)` | Add an item. Blocks if the queue is full. |
| `get()` | Remove and return an item. Blocks if empty. |
| `get(timeout=s)` | Raises `queue.Empty` after `s` seconds. |
| `put_nowait(obj)` / `get_nowait()` | Do not block. Raise `queue.Full` or `queue.Empty`. |
| `qsize()` | Approximate size. Not implemented on some platforms (macOS). |
| `empty()` | Unreliable. Another process may change the queue immediately after. |
Do not use empty() or qsize() to make decisions. Use a sentinel or a timeout instead.
SimpleQueue and JoinableQueue
multiprocessing.SimpleQueue has no feeder thread and no size limit. It offers only put(), get(), and empty(). It is simpler, but a put() of a large item can block until a reader takes it.
multiprocessing.JoinableQueue adds task_done() and join(). A consumer calls task_done() after finishing each item. A producer calls queue.join() to wait until every item put on the queue has been processed. Use it when you need to know that work is complete, not merely that it was read.
Pipes
multiprocessing.Pipe() returns two connection objects, one for each end. By default the pipe is duplex, so both ends can send and receive. A pipe connects exactly two endpoints and is faster than a queue for that case, because there is no feeder thread and no locking for multiple users.
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())
p.join()send() pickles any picklable object and recv() unpickles it. For raw bytes, send_bytes() and recv_bytes() skip pickling.
Queue or pipe?
| Situation | Better choice |
|---|---|
| Many producers or many consumers | `Queue` |
| Exactly two processes talking back and forth | `Pipe` |
| Need to know all work was processed | `JoinableQueue` |
| Need backpressure | `Queue(maxsize=N)` |
Pool results are also pickled
When you use ProcessPoolExecutor or multiprocessing.Pool, you do not call a queue yourself, but the same rules apply. Arguments are pickled to reach the worker. Return values are pickled to come back. Exceptions raised in a worker are pickled too, which is why a custom exception class needs to be importable and constructible from its stored arguments.
The function you submit must be a top-level function in an importable module, because it is pickled by name.
from concurrent.futures import ProcessPoolExecutor
def square(n):
return n * n
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=2) as pool:
print(list(pool.map(square, range(5))))
try:
pool.submit(lambda n: n * n, 3).result()
except Exception as exc:
print(type(exc).__name__)The first call works. The lambda fails, because the executor cannot pickle it. The exact exception type depends on the Python version, so rely on the fact that it fails, not on its name.
Reducing the cost of many small tasks
Sending a thousand tiny tasks costs a thousand round trips. map accepts a chunksize argument for process pools, which groups items into batches so each pickle and each transfer carries many items.
import time
from concurrent.futures import ProcessPoolExecutor
def double(n):
return n * 2
def timed(chunksize):
start = time.perf_counter()
with ProcessPoolExecutor(max_workers=4) as pool:
total = sum(pool.map(double, range(200_000), chunksize=chunksize))
return total, time.perf_counter() - start
if __name__ == "__main__":
for size in (1, 100, 5_000):
total, seconds = timed(size)
print(f"chunksize={size:<6} total={total} time={seconds:.2f}s")On a typical machine the run with chunksize=1 is much slower than the others, even though the arithmetic is trivial. Nearly all of its time goes to moving items, not computing. For thread pools, chunksize has no effect.
Avoiding copies with shared memory
Sometimes the data is large and many processes need to read it. Pickling it for each one wastes time and memory. multiprocessing.shared_memory lets processes map the same block of memory by name, so no copy is made.
from multiprocessing import Process, shared_memory
def reader(name, size):
shm = shared_memory.SharedMemory(name=name)
print("child read:", bytes(shm.buf[:size]))
shm.close()
if __name__ == "__main__":
shm = shared_memory.SharedMemory(create=True, size=16)
shm.buf[:5] = b"hello"
p = Process(target=reader, args=(shm.name, 5))
p.start()
p.join()
shm.close()
shm.unlink() # release the block; only one process should do thisShared memory holds raw bytes, not Python objects. You must decide the layout yourself, for example with memoryview.cast or a NumPy array built on the buffer. There is no locking, so you need your own synchronization if processes write to the same region. You are also responsible for calling unlink() exactly once. If you forget, the block can outlive the program on some platforms.
Common mistakes
- Joining before reading. A large item left in a queue can deadlock
join(). Read first. - Passing unpicklable arguments. Lambdas, locks, and open files fail. Pass a path or a name and open the resource inside the child.
- Relying on
empty(). It reflects only a moment that has already passed. - Mutating after sending. Changing an object after
put()may or may not affect what the receiver gets, because pickling happens later in the feeder thread. Treat a sent object as given away. - Sending huge results from many workers. Write large outputs to a file or shared memory and send the path or name.
Summary of the decision
Move as little data as possible. Pass small inputs and small results through queues, pipes, or pool arguments, and expect a copy each time. Use chunksize to batch small tasks. Use shared memory for large read-mostly data. Always measure, because the cost of pickling can erase the gain from running in parallel.
Exercise
A parent starts a child that puts a 50 MB bytes object on a multiprocessing.Queue. The parent calls p.join() and only then calls q.get(). The program hangs. Explain why, and show the fix.
Show answer
The child cannot exit until its feeder thread has written all 50 MB into the pipe. The pipe buffer is far smaller than that, so the feeder blocks until someone reads. The parent is blocked in join() waiting for the child, so nobody reads, and both wait forever. The fix is to call q.get() first and p.join() afterwards, so the parent drains the pipe while the child is still running.
Exercise
You have a list of 1,000,000 integers and want four processes to each sum a quarter of it. Which is likely faster: passing each process its slice as an argument, or having each process build its own quarter using range bounds passed as two integers? Why?
Show answer
Passing two integers is faster. A slice of 250,000 integers must be pickled, copied through the operating system, and unpickled, and that cost scales with the data. Two integers cost almost nothing to send, and each child generates its own numbers locally. In general, send a description of the work instead of the data when the child can recreate the data cheaply.