Sub topic 10
Start methods: spawn, fork, forkserver, and the __main__ guard
This chapter assumes you can start a multiprocessing.Process and use ProcessPoolExecutor, and that you know processes have separate memory. It explains how a new worker process gets created, why that choice changes your program's behavior, and why many multiprocessing scripts need if __name__ == "__main__":.
What a start method is
A start method is the mechanism multiprocessing uses to create a child process. There are three:
| Method | How the child is created | Platforms | Relative startup cost |
|---|---|---|---|
| `spawn` | Launches a fresh Python interpreter, which imports your main module and receives the task by pickling | Windows, macOS, Linux | Highest (tens to hundreds of milliseconds) |
| `fork` | Calls the operating system's `fork()`, which clones the parent's memory | Unix only | Lowest |
| `forkserver` | Starts a small server process early. Each new child is forked from that server, not from your program | Unix only | Low per child, plus a one-time server start |
The defaults depend on your platform and Python version:
- Windows always uses
spawn. - macOS has used
spawnsince Python 3.8. - Linux and other POSIX systems used
forkthrough Python 3.13. Python 3.14 changed the default toforkserver.
Check the platform you are on instead of assuming:
import multiprocessing as mp
if __name__ == "__main__":
print("default: ", mp.get_start_method())
print("available:", mp.get_all_start_methods())Code that works on your Linux machine under fork may fail on a colleague's Mac or on a newer Python. Treat the start method as part of your program's contract.
How spawn works
With spawn, the child starts from nothing. The parent sends it enough information to rebuild the task, and the child imports your main script to find the functions it needs.
Three consequences follow:
- The main module is executed again in the child. Any top-level statement in your script runs once per child, unless it is protected by the guard.
- Arguments and targets are pickled. The target must be importable by name from a module. Lambdas and nested functions fail.
- Parent state is not inherited. A global changed at runtime in the parent is back at its import-time value in the child.
The __main__ guard
When the child imports your script, Python sets __name__ to "__mp_main__", not "__main__". The guard if __name__ == "__main__": is therefore false in the child, which keeps the child from starting its own children.
Here is a script without the guard, run under spawn:
import multiprocessing as mp
def work(x):
return x * x
ctx = mp.get_context("spawn")
p = ctx.Process(target=work, args=(3,))
p.start() # the child re-imports this file and reaches this line too
p.join()The child imports the file and hits p.start() during bootstrapping. Python detects this and raises a RuntimeError saying an attempt was made to start a new process before the current process finished its bootstrapping phase. The fix is to put the process-starting code behind the guard:
import multiprocessing as mp
def work(x):
print("result:", x * x)
if __name__ == "__main__":
ctx = mp.get_context("spawn")
p = ctx.Process(target=work, args=(3,))
p.start()
p.join()Definitions such as def work stay at module level, so the child can import them. Only the code that starts processes goes under the guard. A common layout is a main() function called from the guard.
Seeing the difference: inherited state
This script runs the same function under each available start method. The parent changes a global inside the guard before starting each child.
import multiprocessing as mp
CONFIG = {"mode": "default"}
def show(label):
print(f"{label:11} sees mode = {CONFIG['mode']}")
if __name__ == "__main__":
CONFIG["mode"] = "changed in parent"
for method in mp.get_all_start_methods():
ctx = mp.get_context(method)
p = ctx.Process(target=show, args=(method,))
p.start()
p.join()On Linux the output is:
fork sees mode = changed in parent
spawn sees mode = default
forkserver sees mode = defaultThe fork child is a copy of the parent's memory at the moment of the call, so it sees the change. The spawn and forkserver children import the module fresh. The assignment sits under the guard, so it never runs there.
Common consequences:
- Configuration set at runtime (loaded settings, a logging setup, a seeded random generator) does not reach
spawnworkers. Pass it as arguments, or use a pool initializer that sets it up in each worker. - Large read-only data loaded before forking is shared cheaply under
fork, because the operating system copies pages only when they are written. Underspawneach worker must load or receive its own copy. - Module-level side effects, such as opening a file or connecting to a database at import, run again in every spawned child.
Why fork is risky
fork is fast and convenient, but it copies only the thread that called it. Every other thread vanishes in the child, while the memory those threads were using stays as it was.
Suppose a background thread holds a lock, for example inside the logging module or a database driver, at the instant you fork. The child gets a copy of that lock in the locked state. The thread that would release it does not exist in the child, so the first attempt to take the lock hangs forever.
Other fork hazards:
- Network connections and file descriptors are duplicated, so parent and child can both write to the same socket.
- Some system libraries on macOS are not safe to use after a fork, which is one reason macOS moved to
spawn. - Since Python 3.12, forking a process that has several threads raises a
DeprecationWarning. Python 3.14 moved the Linux default away fromforkpartly for this reason.
forkserver
forkserver aims for fork's speed without fork's thread hazards. The first time you start a process, multiprocessing launches a small single-threaded server process. Each later child is forked from that server, not from your large, possibly multithreaded program. Children start from a clean state and see none of your runtime globals, as with spawn. The guard is required, and arguments are still pickled.
Choosing and setting a method
There are two ways to select a method:
import multiprocessing as mp
if __name__ == "__main__":
# Option 1: change the process-wide default (call at most once)
mp.set_start_method("spawn")import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor
def square(x):
return x * x
def main():
ctx = mp.get_context("spawn") # Option 2: a local context
with ProcessPoolExecutor(max_workers=2, mp_context=ctx) as pool:
print(list(pool.map(square, range(5))))
if __name__ == "__main__":
main()The second output is [0, 1, 4, 9, 16].
set_start_method changes global state and raises a RuntimeError if you call it a second time, unless you pass force=True. A library that calls it can break the application that imports it. Prefer get_context(...), which returns an object with the same API (Process, Queue, Pool) bound to one method, and pass it to ProcessPoolExecutor with mp_context.
You can mix contexts in one program, but objects from different contexts, such as a queue from fork and a process from spawn, should not be combined.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| `RuntimeError` about bootstrapping, or workers launching more workers | Missing `__main__` guard under `spawn` or `forkserver` | Move process-starting code under the guard |
| `AttributeError: Can't get attribute 'f' on <module '__main__'>` | Target defined where the child cannot import it, such as a REPL or notebook cell | Define the function in an importable module file |
| `PicklingError` on a lambda or nested function | Targets and arguments are pickled under `spawn` and `forkserver` | Use a top-level function |
| Worker sees default settings | Runtime global changed in the parent only | Pass the value as an argument or use an initializer |
| Program hangs only on Linux | `fork` after threads started left a lock held | Use `spawn` or `forkserver`, or start the pool before threads |
| `RuntimeError: context has already been set` | `set_start_method` called twice | Use `get_context`, or pass `force=True` deliberately |
Cost trade-offs
Spawn pays for a new interpreter plus imports in each child. If your script imports a heavy library such as numpy or pandas, every child pays that import time. For a pool this is a one-time cost per worker, so reuse a pool for many tasks instead of starting a process per task. For short tasks, the startup cost can exceed the work.
Measure on your own machine and Python version before deciding. The numbers vary widely with imports, platform, and Python version.
Exercise
A script defines CONFIG = {}, then under if __name__ == "__main__": sets CONFIG["db"] = "prod", then runs a ProcessPoolExecutor. Workers read CONFIG["db"] and get a KeyError on macOS, but the script works on older Linux setups. Explain why, and give two fixes.
Show answer
macOS uses spawn, so each worker imports the module fresh. The assignment is under the guard, so it never runs in the workers and CONFIG is empty there. On older Linux, fork copied the parent's memory after the assignment, so the workers saw it. Fixes: pass the value as an argument to the task function, or pass an initializer to ProcessPoolExecutor that sets CONFIG["db"] in each worker. Moving the assignment to module level also works, but only if it does not depend on runtime input.
Exercise
Why does fork risk a deadlock in a program that runs threads, and which start methods avoid the problem?
Show answer
fork copies only the calling thread. If another thread held a lock when the fork happened, the child gets the lock in its locked state with no thread to release it, so the first attempt to acquire it blocks forever. spawn and forkserver start children from a clean state instead of copying the multithreaded parent, so they avoid the problem.