Pass Small Messages across Process Boundaries
Core idea
Processes have separate ordinary memory. multiprocessing.Queue serializes Python objects and supports communication between cooperating processes; Pipe supplies connection endpoints. Use small bounded messages, explicit completion and trusted participants. recv and queue get can block; use timeouts or polling when the protocol requires them. Run the worker example as a script.
from multiprocessing import get_contextdef worker(sender): try: sender.send(('ok', 12)) finally: sender.close()if __name__ == '__main__': ctx = get_context('spawn') receiver, sender = ctx.Pipe(duplex=False) p = ctx.Process(target=worker, args=(sender,)) p.start() sender.close() try: if not receiver.poll(5): raise TimeoutError('no reply') print(receiver.recv()) finally: receiver.close() p.join() p.close()The parent closes its unused sending endpoint and receives one bounded trusted message.
Expected output:
('ok', 12)Transfer a small queue item
from multiprocessing import get_contextif __name__ == '__main__': q = get_context('spawn').Queue(maxsize=1) try: q.put({'count': 4}) print(q.get(timeout=5)) finally: q.close() q.join_thread()The queue serializes the mapping. This example uses one process to show the interface.
Expected output:
{'count': 4}Common mistake
Never unpickle untrusted messages. Joining a producer before draining large queued messages can block because its feeder thread must flush data. Close unused endpoints and define a failure protocol.
Practice
Send a second message with an explicit done marker and drain both before joining. Describe what happens if the child exits without sending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interprocess communication
Check your understanding of interprocess communication.
What is printed?
from multiprocessing import Piper,s=Pipe(False)s.send_bytes(b"ok")print(r.recv_bytes())r.close();s.close()What is printed?
from multiprocessing import Piper,s=Pipe(False)print(r.readable,s.writable)r.close();s.close()Why drain a process queue before joining its producer?
What is unsafe for object-based receive?