On this page
  1. multiprocessing
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Explicit Context (get_context("spawn")) & Producer/Consumer Queue
  7. 2. Zero-Copy Buffers via multiprocessing.shared_memory
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

multiprocessing

Prev: msvcrt | Up: stdlib_module | Next: netrc
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — multiprocessing
Tags: #public #python3 #stdlib


Import

import multiprocessing

Overview

Spawns separate OS Python processes to achieve true multi-core parallelism for CPU-bound Python code (bypassing the GIL), with IPC primitives (Queue, Pipe, Value, Array, shared_memory) and worker pools (Pool). For simple map/submit workflows prefer concurrent.futures.ProcessPoolExecutor; for I/O-bound work prefer asyncio or threading.

Quick Start

import multiprocessing as mp

def square(n: int) -> int:
    return n * n

if __name__ == "__main__":
    with mp.Pool(processes=2) as pool:
        assert pool.map(square, [1, 2, 3, 4]) == [1, 4, 9, 16]

Implementation Walkthrough

1. Explicit Context (get_context("spawn")) & Producer/Consumer Queue

Using an explicit start method ("spawn" or "forkserver") keeps behavior consistent across macOS, Windows, and Linux and avoids deadlocks from inheriting multithreaded locks:

import multiprocessing as mp

def worker(q: mp.Queue) -> None:
    q.put({"status": "ok"})

if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    q = ctx.Queue()
    proc = ctx.Process(target=worker, args=(q,))
    proc.start()
    result = q.get(timeout=5)
    proc.join()
    assert result == {"status": "ok"}

2. Zero-Copy Buffers via multiprocessing.shared_memory

For large byte buffers or arrays, pass a SharedMemory name instead of pickling megabytes over a Queue.

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes