Lesson · Multiprocessing
Multiprocessing Fundamentals
90 min readMultiprocessing Fundamentals
Multiprocessing uses independent processes with separate memory. It can exploit multiple CPU cores even in traditional GIL-enabled CPython, but startup, serialization, and data transfer are real costs.
Learning goals
- Explain why each process owns a separate memory space, so a write performed in a child is invisible to the parent.
- Create a child with
Process(target=..., args=...), start it, and join it before reading its outcome. - Explain why child entry code must sit behind
if __name__ == "__main__":under the spawn and forkserver start methods. - Read the pids printed by parent and child and describe how the operating system runs the two interpreters at the same time.
- Predict which target functions and arguments cannot cross a process boundary, and name the exception you expect.
Mental model
The parent and child are two interpreters, not two function calls. Data moves only at the marked points: arguments reach the child as a copy (serialized first under spawn and forkserver), and results need an explicit channel back because the child's writes never reach the parent's objects. Treat start() as "launch a worker and return immediately" and join() as the only point where the parent is guaranteed to see that the worker has finished.
Two interpreters, not two function calls
values cross only at the marked boundary
Mental model
the same mechanism as a compact list
parent process: names and objects live in its memory ↓ start(): the OS creates a second process that runs the target child process: its own memory space; no live sharing with the parent ↓ join(): the parent waits, then reads exitcode values cross only as serialized copies at explicit points
Core idea
Multiprocessing runs your code in more than one interpreter: the parent starts a child, the child executes its target in a fresh memory space, and joining makes the parent wait for it to finish. Because memory is not shared, arguments and results cross the boundary only as serialized copies (under the spawn and forkserver start methods), and anything that cannot be pickled cannot make the trip. The payoff is true CPU parallelism; the costs are process startup, data transfer, and the discipline of the __main__ guard that keeps child creation from re-running the module's top level.
Separate processes
Each process is a full Python interpreter with its own global state and address space, and the operating system schedules the processes independently, so two children can execute at the same instant on different cores. Nothing is shared by default: a name bound in the parent does not exist in the child unless it was passed when the process was created.
Independent memory
Processes do not share Python objects: each child runs against its own memory, so mutating a global or an argument inside the child leaves the parent's object unchanged. That isolation is the safety feature and the friction: every result has to be sent back over an explicit channel such as a Queue or a Pipe.
Process creation
Process startup behavior differs by platform and start method. Protect executable entry code with the __main__ guard so child creation does not recursively rerun top-level application logic.
Joining
Process.join() blocks the parent until the child process exits, or returns early when an optional timeout elapses (the child keeps running, and is_alive() stays true). After a join, Process.exitcode reports how the child ended: 0 for a clean exit, a positive code for a failure, or a negative number on POSIX when a signal terminated it.
Serialization
Serialization converts in-memory values into a representation that can cross a file, network, or process boundary. Consider compatibility, size, trust, and how much type information the format preserves.
Platform startup differences
The start method decides how a child process begins: spawn launches a fresh interpreter that imports your module and receives only pickled arguments, while fork (where available) copies the running process, and forkserver forks from a small server process on request. On Windows and macOS the default is spawn; on Linux the default changed from fork to forkserver in Python 3.14. multiprocessing.get_context("spawn") selects a method explicitly, and the choice changes what works: spawn requires the target to be importable and the arguments to be picklable, while fork inherits whatever the parent already had in memory.
Walkthrough
os.getpid()returns the id of the interpreter that calls it, so the child prints a different number than the parent: two live processes, not two function calls.Process(target=child)wraps thechildfunction without running it, andprocess.start()creates the second process and invokeschildthere; the parent continues immediately.process.join()makes the parent wait until the child exits, so the script prints both lines before it ends; without the wait the parent could finish while the child is still writing.- Predict before running: will "child pid" print before or after "parent pid", and what breaks on a spawn platform if you move the
Process(...).start()lines out of theifblock?
Experiments to try
- Run the example twice and compare pids: parent and child differ within a run, and both change between runs. Say which id a name like
os.getpid()describes in each process. - Make the child raise a
RuntimeError, join it, and printprocess.exitcode. The parent survives, and the nonzero code is the only signal the failure ever happened. - Start two children with
start(), join them in the opposite order, and run the script a few times; the two children can finish in either order, and joining only decides when the parent waits. - Ask
multiprocessing.get_start_method()andget_all_start_methods()in the REPL, then create one child throughmultiprocessing.get_context("spawn").Processand explain why the target must be defined at module level for that context.
Playable lesson
Lab: Process isolation
Visualize parent and worker memory as separate spaces and show serialization or IPC crossing process boundaries.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Process isolation
parent process
running
main interpreter, its own memory
- data[1, 2, 3]
- target<function child>
Predict first
The parent prints its pid, then starts a child that prints its own. Which line appears first?
One process is running, with two names in its memory. There is no worker yet, and the target function is only a reference in this interpreter.
Common mistakes
- Forgetting the
__main__guard: underspawnandforkserverthe child imports the main module to find its target, so top-levelstart()calls run again in every new interpreter and create processes of their own. - Assuming a child's writes are shared: an assignment to a global or a mutation of an argument lives in the child's memory space, so the parent reads the original value and needs an explicit channel to receive results.
- Passing targets or arguments that cannot be pickled, such as a lambda, a function defined inside another function, or an open file handle: under
spawnandforkserverthese are serialized before a child can run, so the failure happens at launch, not inside the worker. - Starting a process per tiny task: each launch pays interpreter startup plus serialization, and that fixed cost can exceed the work being parallelized.
Practice: Easy
- Run the worked example and record the two pid values. State which print statement must execute first and defend the claim from the code's line order.
- Change
childto accept one argument and print it; start it twice with different arguments and join both, then explain why neither child sees the other's value. - Pass an open file object in
argsundermultiprocessing.get_context("spawn")and record the exact exception; then switch the context toforkwhere available and note whether the same code launches.
Practice: Medium
- Time ten sequential calls of a CPU-heavy function against ten children started one at a time with
start()followed byjoin(), and use the difference to name the main cost the process model adds. - Mutate a module-level list inside the child (append an item before exit) and print the list in the parent after
join(); record both views and explain where the child's append landed. - Rewrite the worked example so the parent starts the child, does other work (a print and a short loop), and only then joins; compare the printed interleaving across runs and say what
join()guarantees.
Practice: Hard
- Build a bounded fan-out runner: given a list of tasks (function plus arguments) and a worker limit
W, it starts at mostWchildren at a time, joins finished ones before starting more, and reports each task'sexitcode; define what happens when a task raises. - Write a small program where the target is defined inside the
if __name__ == "__main__":block, run it underget_context("spawn"), read the exception, and fix it by moving the target to module level; explain which import the child actually performs. - Measure the startup premium: compare
time.perf_counter()around twenty trivial child processes with twenty direct calls of the same function, and explain the gap with interpreter startup and serialization.
Lesson checklist
- I can run the worked example and say which pid belongs to which process, and why they differ.
- I can explain why a child's writes to globals and arguments never reach the parent, and what carries results instead.
- I can explain why the
__main__guard is required under the spawn and forkserver start methods. - I can read
Process.exitcodeafterjoin()and state whether the child exited cleanly.
Remember
Multiprocessing gives CPython true CPU parallelism by running work in separate interpreters with separate memory. The price is explicit: values cross the boundary only as serialized copies (under spawn and forkserver), every child has to be started and joined deliberately, and entry code must sit behind the `__main__` guard. Model the parent as a coordinator that launches workers, waits on them, and reads their exit codes, never as the owner of shared state.
Interview angles
What is the main purpose of **Separate processes**?+
Each process is a full interpreter with its own global state and address space, scheduled independently of the others, so two children can run at the same instant on different cores. Nothing is shared by default: a name bound in the parent does not exist in the child unless it was passed when the process was created.
What should you pay attention to when using **Independent memory**?+
Mutations made in a child, whether to a global or to an argument, stay in the child's memory; the parent still holds the original object. Getting a value back requires an explicit channel such as a Queue or a Pipe, not a shared name.
How does **Process creation** fit into this lesson?+
Process startup behavior differs by platform and start method. Protect executable entry code with the __main__ guard so child creation does not recursively rerun top-level application logic.
Why does moving `Process(...).start()` outside the `if __name__ == "__main__":` guard break under the `spawn` start method?+
The spawned child imports the main module to find the target function, so every top-level statement runs again in each new interpreter; the start() call there creates more children, repeating until the runtime stops you with a bootstrapping error.