Multiprocessing
multiprocessing runs code in child processes, each with its own Python interpreter and GIL. It is the standard way to use multiple cores for CPU-bound Python.
Detailed Explanation
A process does not share memory with its parent by default. Starting a Process pickles the target and arguments, launches a new interpreter, and unpickles them there. Results come back the same way through a Queue, a Pipe, or a Pool return value. That isolation avoids GIL contention and most accidental races. It also means you cannot pass a lambda, a live socket, or an unpicklable object.
Start methods matter. spawn (default on Windows and macOS) starts a fresh interpreter. fork (Linux default historically) copies the parent; it is fast and unsafe if the parent has threads or a dirty state. forkserver is a compromise. Set the method in if __name__ == "__main__": before creating processes. On spawn, the main module is re-imported; work at module top level runs again in the child. The __main__ guard is required.
Pool and ProcessPoolExecutor manage a set of workers. map chunks the iterable and gathers results. A pool that never closes leaks processes. Use a context manager.
Shared memory exists: Value, Array, Manager proxies, and shared_memory (3.8+). Proxies are convenient and slow (they serialise). Shared arrays are faster and require explicit locking. Prefer passing data in and returning results for anything that fits.
Use processes for CPU-bound work and for isolating crashes. Use threads for I/O. Use asyncio for many sockets on one core. Mixing a process pool with large objects will spend more time pickling than computing if you are not careful.
Code Examples
from multiprocessing import Process, Queue
def square(n: int, out: Queue) -> None:
out.put(n * n)
if __name__ == "__main__":
q: Queue = Queue()
p = Process(target=square, args=(7, q))
p.start()
print(q.get()) # 49
p.join()from concurrent.futures import ProcessPoolExecutor
def burn(n: int) -> int:
return sum(range(n))
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
print(list(pool.map(burn, [1000, 2000])))Common Gotchas
Missing `if __name__ == "__main__"`
on spawn, children re-import the module and start more children. You fork-bomb or hang.
Passing a lambda or a local function
pickling fails. Use a top-level function.
`fork` after threads or locks
the child inherits a deadlock. Prefer `spawn` unless you know the parent is clean.
Pickling large arrays on every task dominates
use shared memory or do more work per task.