01C.7 Shared Memory and Inter-Process Communication

FoundationsLesson 7 of 719,370 words13 parts
Module 01C · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

Sooner or later a Python service needs more than one process. The reason is usually the one you met in 01C.5: CPU-heavy work (parsing PDFs, tokenizing, scoring embeddings) does not speed up with threads, so you start worker processes, and each worker has its own interpreter, its own GIL and, crucially, its own memory. That last part is the catch. A dictionary in one process is invisible to the next. Everything the workers need has to be sent to them, and everything they produce has to be sent back, and sending means copying. This lesson is about the ways processes talk to each other (inter-process communication, or IPC), and about the one way that avoids the copy altogether: shared memory, a block of bytes that two or more processes map into their own address spaces and read and write directly. We measure the copy tax, build the full IPC menu (pipes, queues, managers, sockets, files, databases), then go deep on multiprocessing.Value and Array, multiprocessing.shared_memory (SharedMemory, ShareableList, SharedMemoryManager), mmap, zero-copy views with memoryview and struct, pickle protocol 5, copy-on-write after fork, and the pool "initializer" pattern. We also cover what shared memory does not give you (it gives you no locking: see 01C.3), how to clean it up when processes crash, and how to share an embedding matrix between workers. Everything runs on the standard library alone: no API key, no packages, no network.

What you'll learn

  • Why separate processes cannot see each other's variables, what a process boundary really costs, and how to measure the "copy tax" of sending big data through a pipe or queue
  • fork, spawn and forkserver: what a child inherits under each, which one you get by default on Linux, macOS and Windows (it changed in Python 3.14 on Linux), and the traps of each
  • The IPC menu, compared: pipes, multiprocessing.Queue, managers, sockets, files, mmap, SharedMemory, databases and Redis, with a decision table
  • multiprocessing.Value, Array, RawValue, RawArray: C-typed shared memory with and without a built-in lock
  • multiprocessing.shared_memory.SharedMemory and ShareableList, SharedMemoryManager: the life cycle (close versus unlink), the resource tracker, the track parameter (3.13), and the leaked-segment warning
  • Reading and writing raw bytes safely and without copying: memoryview, struct.pack_into/unpack_from, typed views, NumPy over a buffer (illustrative)
  • mmap: anonymous and file-backed maps, MAP_SHARED, ACCESS_READ/ACCESS_COPY/ACCESS_WRITE, and memory-mapped vector files
  • Synchronization across processes: multiprocessing.Lock, semaphores, file locks, "partition instead of lock", and what happens when a process dies holding a lock
  • Copy-on-write after fork, why reference counts defeat it, and what that means for pre-fork servers
  • The ProcessPoolExecutor initializer pattern for large read-only data; pickle costs and protocol 5 out-of-band buffers (PEP 574)
  • Sharing an embedding matrix, a tokenizer, or a vector file between workers; cleanup and crash safety; platform differences; a failure gallery

What you don't need

  • What a process or a thread is, and the vocabulary of concurrency: 01C.1 owns it.
  • The GIL: 01C.5 explains why you reached for processes in the first place; here we only use its conclusion.
  • Race conditions and locks in depth: 01C.3 owns the theory (its 5.1 already showed Value with and without its lock). Here we apply it to memory that outlives a single interpreter.
  • Deadlock and starvation in depth: 01C.4.
  • How Python allocates objects and counts references: 01C.6 owns it; Part 8 needs only the sentence "every object has a reference count that is written when you merely look at the object".
  • Operating-system internals beyond "an address space is a private map of memory". NumPy, C, or Rust knowledge: the NumPy snippets are optional and clearly marked as illustrative.
  • An API key, a provider SDK, or any installed package.

Setup

You need Python 3.11 or newer (3.13 or 3.14 recommended; SharedMemory(track=False) needs 3.13, and the start-method defaults described in Part 1 are those of 3.14). Check your version:

bash
python3 --version
powershell
py --version

Save each snippet as a .py file and run it with python3 file.py (Windows: py file.py). No API key needed. Every Output: block came from Python 3.14.6 on macOS (a normal build with the GIL enabled). macOS defaults to the spawn start method, so nearly every example selects its start method explicitly with multiprocessing.get_context(...) and behaves the same on Linux and Windows. Where an example is POSIX-only (it uses fork, fcntl or resource), the file says so in its first lines. Timings depend on your machine: those blocks are labelled Example output (illustrative — your exact output will differ): and the text names the relationship to look for, not a number to match.


What you must be able to do after this lesson#

  • Explain why separate processes cannot share variables and measure the copy cost
  • Compare fork, spawn and forkserver
  • Choose an IPC mechanism for a given job
  • Share a NumPy-sized buffer with multiprocessing.shared_memory and clean it up
  • Read and write bytes without copying using memoryview
  • Explain why copy-on-write fails for Python objects after fork
  • Give large read-only data to a process pool with an initializer

Why this matters for an AI engineer#

AI services are full of data that is big, read by many workers and rarely changed: an embedding matrix, a vector index file, a tokenizer vocabulary, a model's lookup tables, a corpus of parsed documents. They are also full of CPU stages (parse, chunk, tokenize, score) that need more than one process to use more than one core. Put the two together and the question is unavoidable: how do eight workers see the same 2 GB without paying for it eight times, and without copying it on every task? The wrong answer (pickle it into every task, or let every worker load its own copy) shows up as a RAM bill, a slow start, or a machine that swaps. The right answers are in this lesson. You will hear:

You'll hear... You'll understand it after...
"Processes don't share memory" Part 1
"Why is my ProcessPoolExecutor slower than the loop?" 1.3 and Part 10
"It works on my Mac but hangs on Linux" (or the reverse) 1.4 and 1.5
"Use a Queue, or a Manager, or Redis?" Part 2
"Put the embeddings in shared memory" Part 4 and Part 11
"resource_tracker: There appear to be 1 leaked shared_memory objects" 4.5
"We memory-map the vector file" Part 6
"Shared memory isn't thread-safe or process-safe for free" Part 7
"Preload the model, then fork the workers" Part 8
"Load it once per worker in the initializer" Part 9

Part 1: Separate address spaces, and the copy tax#

1.1 The house and the shared kitchen#

Think of a process as a house. It has its own rooms, its own furniture and its own front door. Everything inside (your variables, your open files, your imported modules, your loaded model) belongs to that house. A thread is a person living in the house: all the people in one house share the kitchen, so if one of them moves the salt, everyone sees the salt has moved. That is cheap and convenient, and it is exactly why threads need locks (01C.3).

Two processes are two houses. The people in house A cannot open the fridge in house B. If house A wants to give house B a recipe, it has to write the recipe down, post it through the letterbox, and house B has to copy it into its own notebook. That is message passing. It is safe (nobody can scribble on your notebook), but every message costs a copy, and a big message costs a big copy.

Shared memory is a shared allotment between the two houses: a patch of ground that both houses have a gate to. There is no copying, because there is only one patch. And, like any shared ground, nothing stops two people planting in the same spot at once: you must agree rules (Part 7).

flowchart LR
    subgraph a ["Process A (own address space)"]
        a1["Python objects<br/>variables, models, caches"]
    end
    subgraph b ["Process B (own address space)"]
        b1["Python objects<br/>variables, models, caches"]
    end
    subgraph os ["Operating system"]
        pipe["pipe / socket<br/>(copy in, copy out)"]
        shm["shared pages<br/>(mapped into both)"]
    end
    a1 -- "send: pickle + copy" --> pipe
    pipe -- "receive: copy + unpickle" --> b1
    a1 <-- "read / write directly" --> shm
    b1 <-- "read / write directly" --> shm

Technically, each process has a private virtual address space: the numbers (addresses) its code uses for memory are translated by the CPU, with the operating system's help, into physical RAM pages. Two processes can use the same address number and reach different RAM. Shared memory is the operating system arranging for some of those translations to point at the same physical pages from two processes. That is all it is.

1.2 What "separate memory" means in practice#

Here is the whole idea in a dozen lines. A thread bumps a module-level dictionary and the main thread sees it. A process bumps its copy, exits, and nothing changes in the parent.

python
# e01_address_spaces.py: threads share variables, processes get their own copy.
import multiprocessing as mp
import threading

counter = {"hits": 0}          # a module-level dict, living in THIS process's memory


def bump_in_thread() -> None:
    counter["hits"] += 1       # same dict object: the main thread will see it


def bump_in_process() -> None:
    counter["hits"] += 100     # a different process: bumps ITS copy, then exits


if __name__ == "__main__":
    print("start method:", mp.get_start_method())

    t = threading.Thread(target=bump_in_thread)
    t.start()
    t.join()
    print("after a thread:   ", counter["hits"])

    p = mp.get_context("spawn").Process(target=bump_in_process)
    p.start()
    p.join()
    print("after a process:  ", counter["hits"])
Output3 lines
start method: spawn
after a thread:    1
after a process:   1

That is the whole story of "processes do not share memory". Everything else in this lesson is a way around it: send a copy deliberately (Part 2), or create a named region both processes can map (Parts 3, 4 and 6).

1.3 The copy tax: what it costs to hand data to another process#

multiprocessing.Queue, Pipe, Process(args=...) and a ProcessPoolExecutor task all use pickle: Python walks the object, writes it as bytes, pushes the bytes through an operating-system pipe, and the receiver reads the bytes and rebuilds the object. A 64 MiB blob therefore exists several times at once: in the sender's memory, in the pickle stream, in the pipe's buffer chunks, and in the receiver's memory. And the CPU work scales with the size.

Shared memory skips all of it. The next experiment hands the same 64 MiB to a worker both ways. The child is already running and idle when the clock starts, so process start-up is not measured.

python
# e03_copy_tax.py: what does it cost to hand 64 MiB to another process?
# Way 1: put it on a multiprocessing.Queue (pickle -> pipe -> unpickle).
# Way 2: write it once into shared memory and send only the NAME (a few bytes).
# The child is started and idle BEFORE the clock starts, so process start-up is not measured.
import multiprocessing as mp
import pickle
import time
from multiprocessing import shared_memory

SIZE = 64 * 1024 * 1024


def consumer(inbox, outbox) -> None:
    outbox.put("ready")
    kind, item = inbox.get()                      # a Queue get() unpickles the whole payload
    if kind == "blob":
        outbox.put(("blob", len(item), item[0], item[-1]))
    else:                                         # kind == "shm": item is only a name
        shm = shared_memory.SharedMemory(name=item)   # attach: maps the same pages, copies nothing
        outbox.put(("shm", shm.size >= SIZE, shm.buf[0], shm.buf[SIZE - 1]))
        shm.close()


def run(ctx, kind: str, make_item):
    inbox, outbox = ctx.Queue(), ctx.Queue()
    p = ctx.Process(target=consumer, args=(inbox, outbox))
    p.start()
    assert outbox.get() == "ready"                # the child is up and idle: start the clock
    t0 = time.perf_counter()
    inbox.put((kind, make_item()))
    reply = outbox.get()
    elapsed = time.perf_counter() - t0
    p.join()
    return reply, elapsed


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    payload = bytes(range(256)) * (SIZE // 256)
    print("payload bytes:", len(payload))
    print("pickled bytes:", len(pickle.dumps(payload, protocol=5)))   # payload + a few header bytes (protocol 5 is the default only from 3.14; 3.8-3.13 default to 4)

    reply, queue_s = run(ctx, "blob", lambda: payload)
    print("queue reply:", reply)

    shm = shared_memory.SharedMemory(create=True, size=SIZE)
    try:
        t0 = time.perf_counter()
        shm.buf[:SIZE] = payload                  # ONE copy, into the shared pages
        write_s = time.perf_counter() - t0
        reply, shm_s = run(ctx, "shm", lambda: shm.name)
        print("shm reply  :", reply)
    finally:
        shm.close()
        shm.unlink()                              # always remove the segment

    print(f"queue hand-off        : {queue_s*1000:7.1f} ms")
    print(f"shm write, once       : {write_s*1000:7.1f} ms")
    print(f"shm hand-off (name)   : {shm_s*1000:7.1f} ms")
Example output · illustrative7 lines
payload bytes: 67108864
pickled bytes: 67108873
queue reply: ('blob', 67108864, 0, 255)
shm reply  : ('shm', True, 0, 255)
queue hand-off        :    30.3 ms
shm write, once       :     3.8 ms
shm hand-off (name)   :     0.2 ms

What to read from it, on any machine:

  • The pickle stream is the payload plus a few bytes: pickling a bytes is nearly a straight copy, but it is still a copy, and the receiver then builds another one.
  • The queue hand-off costs time proportional to the size (tens of milliseconds for 64 MiB here; on a busy machine or with a more complex object it is far worse, because pickling a list of Python objects is not a memcpy: it visits every element).
  • Writing into shared memory is one copy, paid once by whoever produces the data. Handing it to a second, third or eighth worker costs a name (a dozen bytes), so the hand-off is effectively free and independent of the data size.

The conclusion is not "always use shared memory". For small messages (a ticket id, a short prompt, a result string) a queue is simpler and the copy is negligible. Shared memory pays off when the data is large (megabytes and up), read by several processes, or sent repeatedly.

1.4 How a child process is created: fork, spawn, forkserver#

What does a new worker start with? That depends on the start method, and the three methods differ in exactly the way that bites in production.

Start method How the child is made What it inherits Speed Safe with threads?
fork The OS duplicates the parent (os.fork()): the child is a copy-on-write clone with the same memory, open files and imported modules Everything, including locks in whatever state they were in Fast: no new interpreter No: only the forking thread survives; a lock held by another thread stays locked forever in the child
spawn A fresh Python interpreter is launched and told to import your main module and run the target Only what you pass (pickled) plus what an import of your module creates Slow: a fresh interpreter plus your imports (tens of milliseconds for an empty child on one machine, more with heavy imports: see the measurement below) Yes
forkserver A single clean server process is started once; to make a worker, the parent asks the server to fork itself Nothing from the parent except what you pass; the workers clone the server, which is clean One slow start, then fast Yes

A quick measurement of the cost (start and finish an empty child; illustrative, your numbers will differ; forkserver pays its one-off server start on the first child only):

python
# f06_spawn_startup.py: how long does it take to start and finish an empty child, per method?
import multiprocessing as mp
import time


def noop() -> None:
    pass


if __name__ == "__main__":
    for method in ("fork", "forkserver", "spawn"):
        ctx = mp.get_context(method)
        for label in ("first", "second"):       # forkserver pays its one-off server start on the first
            t0 = time.perf_counter()
            p = ctx.Process(target=noop)
            p.start()
            p.join()
            print(f"{method:10s} {label:6s} {(time.perf_counter() - t0) * 1000:6.1f} ms")
Example output · illustrative1 line

Run this to see what a child can see under each method on your machine:

python
# e02_start_methods.py: what does a child process inherit under each start method?
import multiprocessing as mp
import os
import sys
import warnings

CONFIG = {"model": "unset"}     # module-level state, set only under __main__
BIG = None                      # becomes a list in the parent only


def child(tag: str, q, parent_pid: int) -> None:
    # Report what this child can see. Under fork it sees what the parent had at fork time;
    # under spawn/forkserver the module is re-imported, so only import-time state exists.
    q.put((tag, CONFIG["model"], BIG is not None, os.getpid() != parent_pid))


if __name__ == "__main__":
    warnings.simplefilter("ignore")           # fork-with-threads warnings are not the point here
    CONFIG["model"] = "set-in-main"
    BIG = list(range(5))
    print("default:", mp.get_start_method(), "| available:", sorted(mp.get_all_start_methods()))
    print(f"{'method':<11}{'CONFIG seen':<14}{'BIG seen':<10}{'new pid'}")
    for method in ("fork", "spawn", "forkserver"):
        if method not in mp.get_all_start_methods():
            print(f"{method:<11}(not available on this platform)")
            continue
        ctx = mp.get_context(method)
        q = ctx.Queue()
        p = ctx.Process(target=child, args=(method, q, os.getpid()))
        p.start()
        tag, cfg, big, new = q.get()
        p.join()
        print(f"{tag:<11}{cfg:<14}{str(big):<10}{new}")
Output5 lines
default: spawn | available: ['fork', 'forkserver', 'spawn']
method     CONFIG seen   BIG seen  new pid
fork       set-in-main   True      True
spawn      unset         False     True
forkserver unset         False     True

Read the table the script prints:

  • Under fork the child saw CONFIG = "set-in-main" and BIG, both assigned under if __name__ == "__main__": after the module was imported. A forked child is a clone, so it has them.
  • Under spawn and forkserver the child re-imports the module but does not run the __main__ block, so CONFIG is still "unset" and BIG is None. Anything created only under the guard has to be passed in (as an argument, or by an initializer: Part 9).

This is the number-one source of "it works on Linux and fails on macOS" (or, since 3.14, "it worked on Linux until we upgraded Python"): code that quietly relied on a forked child inheriting a global.

Two more spawn-time rules follow from "the child re-imports your module and receives its target by pickle". Both fail loudly, which is a kindness:

python
# e22_spawn_traps.py: two classic spawn-time failures, each run in a throw-away child interpreter
# so this file itself keeps working. The bad scripts are written to a temp directory.
import os
import re
import subprocess
import sys
import tempfile
import textwrap

NO_GUARD = textwrap.dedent("""
    import multiprocessing as mp
    def work(): print("hi")
    p = mp.get_context("spawn").Process(target=work)   # no `if __name__ == "__main__":` guard
    p.start(); p.join()
""")

LAMBDA = textwrap.dedent("""
    import multiprocessing as mp
    if __name__ == "__main__":
        p = mp.get_context("spawn").Process(target=lambda: print("hi"))
        p.start(); p.join()
""")


def key_lines(text: str) -> list[str]:
    # keep only the lines that name the error, not the traceback frames or the absolute paths
    keys = ("RuntimeError", "start a new process before", "PicklingError", "Can't", "cannot pickle")
    return [re.sub(r"0x[0-9a-f]+", "0x...", line.strip()) for line in text.splitlines() if any(k in line for k in keys)][:3]


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as tmp:
        for label, code in (("missing __main__ guard", NO_GUARD), ("lambda as target", LAMBDA)):
            path = os.path.join(tmp, "bad.py")
            with open(path, "w") as f:
                f.write(code)
            r = subprocess.run([sys.executable, path], capture_output=True, text=True, timeout=60)
            print(f"--- {label}: parent exit code {r.returncode}")
            for line in key_lines(r.stderr):
                print("   ", line)
Output6 lines
--- missing __main__ guard: parent exit code 0
    raise RuntimeError('''
    RuntimeError:
    An attempt has been made to start a new process before the
--- lambda as target: parent exit code 1
    _pickle.PicklingError: Can't pickle <function <lambda> at 0x...>: it's not found as __main__.<lambda>
  1. The __main__ guard is mandatory under spawn/forkserver; otherwise importing the main module starts processes, and Python raises the RuntimeError above.
  2. The target and its arguments must be picklable. Module-level functions are (they are pickled by name); lambdas, nested functions and open file objects are not. The PicklingError above is that rule.

1.5 Which start method you get#

As of November 2026, from the multiprocessing documentation and the What's New in Python 3.14:

Platform Default before 3.14 Default in 3.14 and later Others available
Linux and other POSIX except macOS fork forkserver (3.14) fork, spawn
macOS spawn (since 3.8; fork was judged unsafe there) spawn fork, forkserver
Windows spawn spawn none: there is no fork

Two footnotes. First, the 3.14 documentation says fork "is no longer the default start method on any platform" and that code which needs it must ask explicitly, with multiprocessing.get_context("fork") (preferred, because it is local) or multiprocessing.set_start_method("fork") (global, and meant to be called once). Second, the 3.15 documentation adds (marked "3.15.1") that spawn becomes the default when there is no writable temporary directory, for example on a read-only file system, and that the default is now determined when it is first needed rather than when multiprocessing is imported. Python 3.15 was not released when this lesson was written; check the current documentation before relying on that detail.

How to choose, and how to stay in control:

python
import multiprocessing as mp

# Be explicit. Never depend on the platform default in code that must behave the same everywhere.
ctx = mp.get_context("spawn")           # works identically on Windows, macOS and Linux
queue = ctx.Queue()                     # create every primitive from the SAME context as the processes
proc = ctx.Process(target=print, args=("hello",))

Locks and queues created from one context cannot be handed to processes started by another (the documentation warns about locks created under fork). Take everything from the same ctx.

Use... When
spawn You want identical behaviour on all three platforms, you use threads, or your workers import heavy libraries and you pre-warm a pool (the cost is paid once per worker, Part 9)
forkserver Linux, you use threads in the parent, and you want faster worker creation than spawn; you can pre-import heavy modules in the server with multiprocessing.set_forkserver_preload([...])
fork You deliberately want copy-on-write sharing of a large, read-mostly structure built before the fork (Part 8), the parent has no other threads, and you accept Linux-only behaviour

Part 2: The IPC menu#

Before reaching for shared memory, look at the whole menu. Most of the time a simpler tool is the right one.

2.1 The menu in one table#

Mechanism What it is Copies data? Who can talk Survives a process crash? Best for
Pipe / Connection A two-ended channel between exactly two processes (multiprocessing.Pipe, or os.pipe) Yes (pickle, or raw with send_bytes) Two ends The pipe breaks (EOFError/BrokenPipeError) A conversation between a parent and one worker
multiprocessing.Queue / SimpleQueue A shared line: many producers, many consumers; pipe + lock + a feeder thread Yes (pickle) Any number Items in flight can be lost Job distribution, results, small and medium messages
Manager (SyncManager) A server process owning real objects; others hold proxies that send each call as a message Yes, per call Any number, even other machines Dies with the manager process Rarely-touched shared dicts, lists, namespaces; convenience over speed
Sockets (TCP, Unix domain) Byte streams or datagrams through the network stack Yes Any process, even on another host Connection breaks Talking to a different program, language or machine
Files (including tempfile) A path both processes can read and write Yes (through the page cache) Anyone with access Yes (persistent) Hand-offs, checkpoints, large read-only inputs
mmap A file (or anonymous memory) mapped into the address space No Processes mapping the same file / inheriting the map File-backed: yes Large read-mostly data, random access (Part 6)
shared_memory.SharedMemory A named block of RAM mapped into several processes No Anyone who knows the name No: owner must unlink() Large data that many workers read or fill in place (Part 4)
Value / Array Small C-typed shared memory created before the children start No Child processes (inherited) No Counters, flags, progress, small numeric arrays (Part 3)
A database (SQLite, PostgreSQL) Durable shared state with transactions Yes Any client Yes State that must survive, be queried, and be consistent
Redis / a message broker A network server holding data structures or queues Yes Any client on the network Optional persistence Cross-machine queues, caches, rate limits, locks

The two columns that decide most cases are copies data? and survives a crash?. Shared memory and mmap are the only entries that avoid the copy, and shared memory is the only fast one that does not survive a crash (a crash can even leave it behind: Part 12).

2.2 Pipes and Connection objects#

A Pipe() returns two connected Connection objects. It is duplex (two-way) by default. Use it when exactly two parties hold a conversation, such as a supervisor and one worker.

python
# e04_pipe_queue.py: two message-passing tools: Pipe (two ends) and Queue (many producers, many consumers).
import multiprocessing as mp


def pipe_worker(conn) -> None:
    # Receive jobs until the parent sends None, answer each one, then close our end.
    while (job := conn.recv()) is not None:
        conn.send({"ticket": job["ticket"], "words": len(job["text"].split())})
    conn.close()


def queue_worker(jobs, results) -> None:
    for job in iter(jobs.get, None):                 # None is the stop sentinel
        results.put((job, job * job))


if __name__ == "__main__":
    ctx = mp.get_context("spawn")

    # --- Pipe: one conversation between exactly two ends -----------------
    parent_end, child_end = ctx.Pipe()               # duplex by default
    p = ctx.Process(target=pipe_worker, args=(child_end,))
    p.start()
    child_end.close()                                # the parent must close its copy of the child's end
    for n, text in enumerate(["printer is on fire", "cannot log in", "refund please"], start=1):
        parent_end.send({"ticket": n, "text": text})
        print("pipe reply:", parent_end.recv())
    parent_end.send(None)
    p.join()

    # --- Queue: a shared line, several consumers ---------------------------
    jobs, results = ctx.Queue(), ctx.Queue()
    workers = [ctx.Process(target=queue_worker, args=(jobs, results)) for _ in range(3)]
    for w in workers:
        w.start()
    for n in range(1, 7):
        jobs.put(n)
    for _ in workers:
        jobs.put(None)                               # one sentinel per consumer
    got = sorted(results.get() for _ in range(6))    # drain results BEFORE join() (see 01C.4)
    for w in workers:
        w.join()
    print("queue results:", got)
Output4 lines
pipe reply: {'ticket': 1, 'words': 4}
pipe reply: {'ticket': 2, 'words': 3}
pipe reply: {'ticket': 3, 'words': 2}
queue results: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36)]

Three habits in that script matter in production:

  1. Close the end you do not use. After starting the child, the parent closes its copy of child_end. Otherwise, when the child exits, the parent's open copy keeps the pipe alive and parent_end.recv() would block forever instead of raising EOFError.
  2. Use an explicit stop message (None here, a "sentinel") so the worker knows when to quit; do not rely on killing it.
  3. Never let two processes read, or two write, the same end at once. The documentation warns that data may be corrupted. A Pipe is a two-party tool; for many-to-many use a Queue.

Connection objects have a second, faster face for raw bytes: send_bytes(buffer, offset, size) and recv_bytes_into(buffer). They skip pickle entirely and accept any buffer (a bytes, a bytearray, a memoryview).

python
# e16_send_bytes.py: Connection.send_bytes / recv_bytes_into skip pickling for raw binary data.
import multiprocessing as mp


def reader(conn, size: int) -> None:
    buf = bytearray(size)                       # allocated ONCE by the receiver
    got = conn.recv_bytes_into(buf)             # bytes land directly in our buffer
    conn.send(("received", got, bytes(buf[:4]), bytes(buf[-4:])))


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    size = 1_000_000
    data = bytearray(b"\x01\x02\x03\x04") * (size // 4)
    parent, child = ctx.Pipe()
    p = ctx.Process(target=reader, args=(child, size))
    p.start()
    parent.send_bytes(memoryview(data))         # no pickle, no intermediate bytes() copy of data
    print(parent.recv())
    p.join()

    # send_bytes also takes an offset and length, so one big buffer can go out in windows
    parent, child = ctx.Pipe()
    parent.send_bytes(data, 4, 8)               # bytes 4..11 only
    print("window:", child.recv_bytes())
Output2 lines
('received', 1000000, b'\x01\x02\x03\x04', b'\x01\x02\x03\x04')
window: b'\x01\x02\x03\x04\x01\x02\x03\x04'

The sender passed a memoryview, so no intermediate bytes copy was made, and the receiver read straight into a buffer it had allocated once. It is still a copy through the pipe (the kernel moves the bytes), but you control the allocations and there is no pickle.

2.3 multiprocessing.Queue#

A Queue is the standard way to distribute jobs and collect results. The second half of the script above shows it: three worker processes pull from one jobs queue and push to one results queue. Queue is "thread and process safe" and pickles every item. Under the hood it is a pipe, a lock, and a feeder thread in each producing process that moves items from an in-memory buffer into the pipe, which is why put() returns before the data has actually been sent.

The rules that save you hours:

Rule Why
Drain results before you join() a producing process A process that has put items on a queue does not exit until those items are flushed to the pipe; if nobody reads, join() waits forever. This is a deadlock (01C.4)
Send one sentinel per consumer (None, or a dedicated object) Each consumer exits when it sees its own
get(timeout=...) rather than blocking forever in a supervisor A dead worker never answers; a timeout lets you notice
Keep items small: ids, paths, short strings; put big data elsewhere Every item is pickled and copied twice (1.3)
qsize(), empty() and full() are approximate; do not branch on them By the time you act, another process has changed the queue (a check-then-act race, 01C.3)
Use SimpleQueue only when you do not need timeout, task_done or the feeder thread It is "very close to a locked Pipe"
Bound it: ctx.Queue(maxsize=100) An unbounded queue lets a fast producer pickle everything into memory faster than consumers drain it. maxsize counts items, not bytes, and put() then blocks, put(timeout=...) or put_nowait() raise queue.Full (backpressure; the same idea as the bounded queues in 01B.4 Part 3)
A producer that exits with unread data still in its queue blocks at exit The feeder thread must flush first. q.cancel_join_thread() lets the process exit without waiting, but the unflushed items may be lost; close() says "no more puts" and join_thread() waits for the flush
Use JoinableQueue when you need task_done() / join() accounting Every get() needs a matching task_done(), or join() never returns (01C.4 §3.1)

Backpressure in practice, with the output as run on Python 3.14.6:

python
# f01_backpressure.py: a bounded Queue pushes back on a fast producer.
import multiprocessing as mp
import queue

if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    jobs = ctx.Queue(maxsize=2)          # at most 2 ITEMS in flight (not bytes)
    jobs.put("a")
    jobs.put("b")
    try:
        jobs.put_nowait("c")             # no room: raises instead of growing without limit
    except queue.Full:
        print("third put_nowait: queue.Full")
    try:
        jobs.put("c", timeout=0.2)       # or wait a bounded time
    except queue.Full:
        print("put(timeout=0.2): queue.Full")
    print("got:", jobs.get(), "-> room again, put works:", jobs.put("c") is None)
    jobs.close()
    jobs.cancel_join_thread()
Output1 line

The feeder-thread hang and its escape hatch, plus JoinableQueue accounting (the hanging child is killed by the script itself after two seconds; the Output: is from Python 3.14.6):

python
# f05_queue_shutdown.py: JoinableQueue accounting, and the exit-time feeder-thread hang.
import multiprocessing as mp
import subprocess
import sys
import tempfile
import os
import textwrap


def worker(jobs) -> None:
    for n in iter(jobs.get, None):
        jobs.task_done()                  # one task_done() per get(), including the sentinel's
    jobs.task_done()


HANG = textwrap.dedent("""
    import multiprocessing as mp
    def f(q):
        q.put(b"x" * 1_000_000)           # nobody ever reads it
    if __name__ == "__main__":
        ctx = mp.get_context("spawn")
        q = ctx.Queue()
        p = ctx.Process(target=f, args=(q,))
        p.start()
        p.join(timeout=2)
        print("alive after join(timeout=2):", p.is_alive())
        p.kill(); p.join()
""")
FIX = HANG.replace("q.put(b\"x\" * 1_000_000)", "q.put(b\"x\" * 1_000_000); q.cancel_join_thread()")

if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    jobs = ctx.JoinableQueue()
    p = ctx.Process(target=worker, args=(jobs,))
    p.start()
    for n in range(5):
        jobs.put(n)
    jobs.put(None)
    jobs.join()                           # returns when every put() has a matching task_done()
    print("jobs.join() returned")
    p.join()
    with tempfile.TemporaryDirectory() as d:
        for name, src in (("hang", HANG), ("cancel_join_thread", FIX)):
            path = os.path.join(d, name + ".py")
            open(path, "w").write(src)
            out = subprocess.run([sys.executable, path], capture_output=True, text=True, timeout=30).stdout
            print(name + ":", out.strip())
Output1 line

The same idea exists one level up: Executor.map(fn, items, buffersize=n) (new in 3.14) caps how many submitted-but-unconsumed results exist, so a huge input iterable is not all submitted at once (Part 9).

The pass a name, not the data pattern is the bridge to the rest of the lesson: put a job on the queue that says {"segment": "psm_ab12cd34", "start": 0, "stop": 1000}, and let the worker attach to the shared block (4.3).

2.4 Managers: shared objects the easy way, at a price#

A Manager starts a server process that owns real Python objects (dict, list, Lock, Event, Namespace, and, since 3.14, set). Other processes get proxies: objects that look like a dict or list but forward every call to the server through a pipe. It is the most convenient way to share a dictionary, and the slowest.

python
# e05_manager.py: a Manager hands out PROXIES; every call is a message to a server process.
import multiprocessing as mp
import time


def add_ticket(shared, lock, n: int) -> None:
    with lock:
        shared["tickets"] = shared["tickets"] + [n]       # reassign: the proxy sees a SET
        shared["seen"] = shared["seen"] + 1


def append_to_nested(shared) -> None:
    shared["inbox"].append("lost")                         # mutates a COPY returned by __getitem__


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    with ctx.Manager() as manager:                         # starts a server process
        shared = manager.dict(tickets=[], seen=0, inbox=[])
        lock = manager.Lock()
        ps = [ctx.Process(target=add_ticket, args=(shared, lock, n)) for n in (1, 2, 3)]
        for p in ps:
            p.start()
        for p in ps:
            p.join()
        print("tickets:", sorted(shared["tickets"]), "seen:", shared["seen"])

        # Trap: mutating a nested list through the proxy does NOT propagate.
        p = ctx.Process(target=append_to_nested, args=(shared,))
        p.start()
        p.join()
        print("inbox after nested append:", shared["inbox"])

        # Cost: every access is a round trip to the manager process.
        t0 = time.perf_counter()
        for i in range(2000):
            shared["seen"] = i
        per_op_us = (time.perf_counter() - t0) / 2000 * 1e6
        local = {}
        t0 = time.perf_counter()
        for i in range(2000):
            local["seen"] = i
        local_us = (time.perf_counter() - t0) / 2000 * 1e6
        print(f"proxy set: ~{per_op_us:.0f} us/op   plain dict set: ~{local_us:.2f} us/op")
Example output · illustrative3 lines
tickets: [1, 2, 3] seen: 3
inbox after nested append: []
proxy set: ~11 us/op   plain dict set: ~0.03 us/op

Three lessons are in that output:

  • It works: three processes added tickets to one shared dictionary, serialized by a manager lock.
  • Nested mutation is silently lost. shared["inbox"] returns a copy of the list (pickled across), so appending to it changes the copy, not the server's object. The fix is to reassign (shared["inbox"] = items), or to create the nested object as its own proxy (manager.list()), as the exercise below does.
  • Every operation is a round trip. About ten microseconds per operation here against a few hundredths of a microsecond for a plain dictionary: a factor of several hundred. A manager is fine for a progress dictionary updated a few times a second. It is a bad fit for a hot loop.

2.5 Sockets, files, databases and Redis#

These live outside multiprocessing, and they are what you use when "the other process" is not a Python worker you started.

  • Sockets. A Unix domain socket (a socket bound to a file path, POSIX only) is the fastest local socket and gives you message framing and many clients without a shared parent. TCP on 127.0.0.1 works everywhere and extends to other machines. Use them to talk to a separate service or a differently-written program. 01C.1 Part 4 built sockets and a selector.
  • Files. The simplest IPC that survives crashes: write a temporary file and rename it into place (the atomic-rename trick is in 01C.3 §3.3), and have the reader load it. Good for hand-offs of results and checkpoints; bad for low-latency chatter. A file that many processes read can be memory-mapped for free (Part 6).
  • A database. When the shared state must be durable, queryable and consistent across crashes, use a database with transactions. SQLite handles several local processes (with its locking rules); PostgreSQL handles many machines. The lost-update and idempotency material is in 01C.3 §5.2.
  • Redis or a message broker. The default answer once workers live on more than one machine: queues, caches, counters, rate limits and distributed locks, all over the network. It copies data (twice) and adds a network hop, so it does not replace shared memory on one machine, but it is what scales beyond one. 01B.4 shows the single-process queue patterns that those systems generalize.

Listener and Client: messaging between unrelated Python processes

Between two Python processes that do not share a parent, the standard-library answer is multiprocessing.connection. A Listener binds an address (a Unix domain socket path, a ("127.0.0.1", port) pair, or a named pipe on Windows) and accept() returns a Connection, the same object Pipe() gives you, with send, recv, send_bytes and so on. A Client connects to the address. Both sides pass an authkey, and a challenge-response handshake (HMAC) checks that the peer knows it.

python
# f03_listener_client.py: unrelated-style processes talking over multiprocessing.connection.
import multiprocessing as mp
import os
import tempfile
from multiprocessing.connection import Client, Listener

AUTHKEY = b"change-me"                    # placeholder: authenticates peers, see the warning below


def client(address: str) -> None:
    with Client(address, authkey=AUTHKEY) as conn:
        conn.send({"op": "embed", "text": "hello"})
        print("client got:", conn.recv())


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    with tempfile.TemporaryDirectory() as d:
        address = os.path.join(d, "svc.sock")           # Unix domain socket (POSIX)
        with Listener(address, family="AF_UNIX", authkey=AUTHKEY) as listener:
            p = ctx.Process(target=client, args=(address,))
            p.start()
            with listener.accept() as conn:             # HMAC handshake happens here
                request = conn.recv()
                conn.send({"dims": 3, "echo": request["text"]})
            p.join()

Output (Python 3.14.6, macOS; the Unix-socket family is POSIX only, so on Windows leave family out and use a ("localhost", port) address or a named pipe):

text

2.6 Choosing#

Situation Reach for Why
Send a few jobs to a worker and read results back Queue (or a pool's map/submit) Messages are small; copies are free in practice
A supervisor talking to one long-lived worker Pipe Simplest two-party channel
A progress counter and a stop flag Value / Event A few bytes; built for it
A shared dictionary updated a few times a second Manager Convenience beats speed at low rates
500 MB array read by every worker SharedMemory (or a mmaped file) Zero copy; one copy in RAM
Large file read by every worker, already on disk mmap read-only The OS page cache is the shared memory
Large data built before the workers start, read-only fork + copy-on-write, or initializer No transfer at all (Part 8, Part 9)
Workers on different machines Redis / a broker / a database Shared memory cannot cross machines
State that must survive a crash A database or a file Shared memory dies with the machine's last reference
Another language or a separate service A socket or HTTP A protocol, not a memory layout

The same choice as a flow:

flowchart TD
    start["Data to share between processes"] --> q1{"Workers on more than one machine?"}
    q1 -- yes --> net["Redis, broker or database"]
    q1 -- no --> q2{"Small message or job description?"}
    q2 -- yes --> queue["Queue, Pipe or pool arguments"]
    q2 -- no --> q3{"Already a file on disk and read-mostly?"}
    q3 -- yes --> mm["mmap read-only"]
    q3 -- no --> q4{"Flat numeric or record data?"}
    q4 -- yes --> shm["SharedMemory or RawArray with a lock or disjoint slices"]
    q4 -- no --> q5{"Read-only Python objects?"}
    q5 -- yes --> init["Pool initializer, one copy per worker"]
    q5 -- no --> mgr["Manager at low rates, or rethink the design"]

What this means for an AI engineer. The typical AI pipeline is "many small jobs, each referring to one or two big read-only things". Jobs (a document path, a batch id) go through a queue or a pool; the big things (an embedding matrix, a tokenizer, a vector file) go through shared memory, mmap, or copy-on-write. Mixing the two the other way round (big data through the queue, small control data through shared memory) is the usual mistake.


Part 3: multiprocessing.Value and Array#

Deep-dive

3.1 Small shared C values#

Value and Array are the oldest shared-memory tools in the standard library. You create them before starting the children, from the same context, and pass them as arguments; the children share the same memory. They hold C types (ctypes): a signed 64-bit integer ('q'), a C int ('i', 32 bits), a double ('d'), and so on, or any ctypes.Structure.

python
# e06_value_array.py: multiprocessing.Value and Array: C-typed shared memory with an optional lock.
import ctypes
import multiprocessing as mp


def count_tokens(total, per_worker, idx: int, n_docs: int) -> None:
    # Each worker adds its own tally to the shared total, then records its own slot.
    tally = (idx + 1) * 1000 * n_docs
    with total.get_lock():                  # += is read-modify-write: not atomic (see 01C.3 5.1)
        total.value += tally
    per_worker[idx] = float(tally)          # a distinct slot per worker: no lock needed for THAT


class Point(ctypes.Structure):              # a C struct living in shared memory
    _fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    total = ctx.Value("q", 0)                           # 'q' = signed 64-bit; default lock=True
    per_worker = ctx.Array("d", 4, lock=False)          # raw array: no lock object at all
    ps = [ctx.Process(target=count_tokens, args=(total, per_worker, i, 3)) for i in range(4)]
    for p in ps:
        p.start()
    for p in ps:
        p.join()
    print("total:", total.value, "(expected", sum((i + 1) * 3000 for i in range(4)), ")")
    print("per worker:", list(per_worker))
    print("type of total:", type(total).__name__, "| type of per_worker:", type(per_worker).__name__)

    # Typecode matters: 'i' is a C int (32-bit); it wraps like C, silently.
    small = ctx.Value("i", 0)
    small.value = 2**31                                  # no exception: C integers silently wrap
    print("2**31 stored in an 'i' Value reads back as:", small.value)

    # A struct with a lock-free Raw object; sizes are those of the C types.
    pt = ctx.RawValue(Point, 1.5, 2.5)
    print("point:", pt.x, pt.y, "| sizeof:", ctypes.sizeof(Point), "bytes")
    pt.x += 1                                            # RawValue: no lock, you own the discipline
    print("after pt.x += 1:", pt.x)

    # The lock on Value is an RLock-style object you can reuse for a whole transaction.
    print("lock type:", type(total.get_lock()).__name__)
Output7 lines
total: 30000 (expected 30000 )
per worker: [3000.0, 6000.0, 9000.0, 12000.0]
type of total: Synchronized | type of per_worker: c_double_Array_4
2**31 stored in an 'i' Value reads back as: -2147483648
point: 1.5 2.5 | sizeof: 16 bytes
after pt.x += 1: 2.5
lock type: RLock

Read each line:

  • Value("q", 0) is a Synchronized wrapper by default: it carries a lock, available as get_lock(). The lock is an RLock. Because += is read, add, write (three steps, 01C.3), the documentation says plainly that "operations like += which involve a read and write are not atomic", and the script wraps the update in with total.get_lock():. Without it, increments are lost (a measured example is in 7.2).
  • Array("d", 4, lock=False) returned a plain c_double_Array_4: no lock at all. That is correct here because each worker writes only its own slot; no two processes touch the same element, so there is nothing to protect. This "disjoint slices" idea is the cheapest synchronization there is (7.3).
  • C integers wrap silently. Storing 2**31 into an 'i' value did not raise: it read back as -2147483648. Python integers are unbounded; C ones are not. Pick 'q' (64-bit) for counters and totals, and know the range of whatever you choose.
  • RawValue and RawArray (and lock=False) are the unsynchronized forms. They are exactly as fast as a C variable, and exactly as unsafe.
Typecode C type Size (typical) Use for
'b'/'B' signed/unsigned char 1 byte flags, small enums, raw bytes
'i'/'I' signed/unsigned int 4 bytes counts known to be small
'q'/'Q' signed/unsigned long long 8 bytes counters, offsets, timestamps in ns
'f' float 4 bytes float32 embeddings
'd' double 8 bytes float64 scores, sums

3.2 When to use them, and when to stop#

Value and Array are right for small, fixed, numeric state that exists for the lifetime of a parent that starts all the children: a progress counter, a "shutdown requested" flag, a per-worker heartbeat slot, a small histogram. They are the wrong tool when:

  • the data is large or its size is decided later (use SharedMemory, Part 4);
  • the workers are not children of the creator (you cannot pass a Value to an unrelated process, because it has no name; use a named SharedMemory or a file);
  • the data is not C-shaped (strings, nested records: use ShareableList, a struct layout, or a queue).

Part 4: multiprocessing.shared_memory#

4.1 What it is#

multiprocessing.shared_memory (added in Python 3.8) gives you a named block of bytes that any process on the machine can attach to, whether or not it is a child of the creator. Underneath, it is the operating system's shared-memory facility: POSIX shm_open plus mmap on Linux and macOS, a named file mapping on Windows. Python adds a thin class around it:

text
SharedMemory(name=None, create=False, size=0, *, track=True)
Argument Meaning
name The block's unique name. With create=True and name=None, Python invents one (it looks like psm_ab12cd34). With create=False it is the name of an existing block to attach to.
create True creates a new block; False (default) attaches to an existing one.
size Bytes to allocate when creating. Ignored when attaching. The real size may be larger than requested (platforms allocate whole memory pages).
track (3.13+) Whether to register the block with the resource tracker (4.5). Ignored on Windows.

The attributes you use are name, size and buf, a memoryview of the block's bytes. Everything you do with shared memory in Python is "read and write slices of buf".

Every segment goes through four steps. The distinction between the last two is the most-misunderstood fact about this module.

Step Call Who Effect
Create SharedMemory(create=True, size=n) The owner, once The OS allocates a named block and the owner has a handle
Attach SharedMemory(name=...) Every other process Maps the same pages; another handle
Close shm.close() Every process, when it is done Releases this process's mapping and handle. The block lives on
Unlink shm.unlink() Exactly one process, once, after everyone is finished Removes the name from the OS so the memory is freed once the last handle closes

The documentation is explicit: close() "should be called once access to the shared memory block from this instance is no longer needed", and unlink() "should be called only once per shared memory block regardless of the number of handles to it, even in other processes." On Windows, unlink() does nothing: the block disappears when the last handle is closed.

sequenceDiagram
    participant O as Owner process
    participant OS as Operating system
    participant W as Worker process
    O->>OS: SharedMemory create=True size=n
    OS-->>O: named block and handle
    O->>W: start worker, pass the NAME
    W->>OS: SharedMemory name=...
    OS-->>W: same pages, second handle
    W->>OS: read and write slices of buf
    W->>OS: close (only this handle)
    O->>O: join all workers
    O->>OS: close
    O->>OS: unlink (remove the name, once)

A mnemonic: everyone closes, one unlinks. Closing is like putting down your key; unlinking is like demolishing the room.

The next script walks the whole life cycle in a single process and shows each error you will meet:

python
# e07_shm_basics.py: the whole SharedMemory life cycle in one process (create, attach, close, unlink).
from multiprocessing import shared_memory

# 1. create: the OS allocates a named block; name=None asks Python to invent a unique one.
owner = shared_memory.SharedMemory(create=True, size=100)
print("name looks like:", owner.name[:4] + "...", "| asked 100, got size >= 100:", owner.size >= 100)
print("buf type:", type(owner.buf).__name__, "| len(buf) == size:", len(owner.buf) == owner.size)

# 2. write through the memoryview; slices must match length exactly (it is not a list)
owner.buf[:5] = b"hello"
try:
    owner.buf[:5] = b"too long!"
except ValueError as exc:
    print("ValueError:", exc)

# 3. attach by name (what another process would do): same bytes, different handle
reader = shared_memory.SharedMemory(name=owner.name)
print("reader sees:", bytes(reader.buf[:5]))
reader.buf[0] = ord("J")                     # a write through ANY handle is visible through all
print("owner sees:", bytes(owner.buf[:5]))

# 4. release views BEFORE close(): an exported memoryview pins the buffer
view = reader.buf[:5]
try:
    reader.close()
except BufferError as exc:
    print("BufferError:", exc)
view.release()
reader.close()                               # now it works

# 5. close() ends THIS handle; unlink() removes the NAME (call it once, from one owner)
owner.close()
owner.unlink()
try:
    shared_memory.SharedMemory(name=owner.name)
except FileNotFoundError:
    print("after unlink: attaching by name fails with FileNotFoundError")

# 6. creating with a name that exists fails: the name is a global, per-machine namespace
a = shared_memory.SharedMemory(name="lesson07_demo", create=True, size=8)
try:
    shared_memory.SharedMemory(name="lesson07_demo", create=True, size=8)
except FileExistsError:
    print("second create with the same name: FileExistsError")
finally:
    a.close()
    a.unlink()
Output8 lines
name looks like: psm_... | asked 100, got size >= 100: True
buf type: memoryview | len(buf) == size: True
ValueError: memoryview assignment: lvalue and rvalue have different structures
reader sees: b'hello'
owner sees: b'Jello'
BufferError: cannot close exported pointers exist
after unlink: attaching by name fails with FileNotFoundError
second create with the same name: FileExistsError

Points worth noting from that output:

  • size is a request, not a promise. Ask for 100 bytes and you get at least 100. On this macOS machine the page is 16 KiB, so the real size is 16,384 bytes; on Linux the size is usually exactly what you asked for. Never assume shm.size == requested; use len(shm.buf) or shm.size for the real bounds, and remember the slack bytes exist if you ever compute an array length from shm.size.
  • buf is a memoryview, not a list. Assigning a slice requires the same length on both sides.
  • A live view blocks close(). If you still hold reader.buf[:5] (or any NumPy array built on it), close() raises BufferError: cannot close exported pointers exist. Release views first. This is the most common cleanup bug with shared memory and NumPy.
  • Names are global to the machine. A second create=True with an existing name fails with FileExistsError. That is useful (a deliberate singleton), and a trap if two copies of your service both pick "embeddings". Generate unique names, or let Python choose.
  • After unlink(), new attaches fail with FileNotFoundError, but processes that already have it mapped keep working until they close. Accessing the memory after unlink from a process that still maps it is fine on POSIX; the documentation says to avoid depending on it ("may result in memory access errors, depending on platform").

4.3 A worked example: fixed-size records and disjoint slices#

A realistic job: a parent loads a table of a thousand invoice lines, four worker processes each compute the gross amount for a quarter of the lines, and the results come back into a second shared block. Nothing is pickled except three small arguments per worker: the names and a range.

python
# e08_shm_records.py: fixed-size binary records in shared memory, one disjoint slice per worker.
# Use case: a table of invoice lines written once by the parent, scored by four worker processes.
import multiprocessing as mp
import struct
from multiprocessing import shared_memory

RECORD = struct.Struct("<qdd")        # invoice_id (int64), net (float64), tax_rate (float64) = 24 bytes
N = 1000
WORKERS = 4


def gross_for_slice(name: str, out_name: str, start: int, stop: int) -> None:
    shm = shared_memory.SharedMemory(name=name)
    out = shared_memory.SharedMemory(name=out_name)
    try:
        for i in range(start, stop):
            _id, net, rate = RECORD.unpack_from(shm.buf, i * RECORD.size)   # reads in place, no slice copy
            struct.pack_into("<d", out.buf, i * 8, net * (1 + rate))        # worker i owns slots [start, stop)
    finally:
        shm.close()                    # close() only: the parent unlinks
        out.close()


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    table = shared_memory.SharedMemory(create=True, size=RECORD.size * N)
    result = shared_memory.SharedMemory(create=True, size=8 * N)
    try:
        for i in range(N):
            RECORD.pack_into(table.buf, i * RECORD.size, 10_000 + i, 100.0 + i, 0.2)
        step = N // WORKERS
        procs = [
            ctx.Process(target=gross_for_slice, args=(table.name, result.name, k * step, (k + 1) * step))
            for k in range(WORKERS)
        ]
        for p in procs:
            p.start()
        for p in procs:
            p.join()
        gross = struct.unpack_from(f"<{N}d", result.buf, 0)
        expected = sum((100.0 + i) * 1.2 for i in range(N))
        print("record size:", RECORD.size, "bytes | table bytes:", RECORD.size * N)
        print("first 3 gross:", [round(g, 2) for g in gross[:3]])
        print("sum matches single-process total:", abs(sum(gross) - expected) < 1e-6)
    finally:
        for seg in (table, result):
            seg.close()
            seg.unlink()
Output3 lines
record size: 24 bytes | table bytes: 24000
first 3 gross: [120.0, 121.2, 122.4]
sum matches single-process total: True

Why this is safe without a lock: worker k reads the whole input table (read-only: no conflict) and writes only the output slots [k * step, (k + 1) * step). No two processes ever write the same bytes. The parent reads the results only after join(), which is a synchronization point: a joined process has finished all its writes. That is the "partition, then join" pattern (7.3).

Other habits shown in that file:

  • Workers attach by name and only close() in a finally; the parent, which created the blocks, unlink()s them in its finally.
  • RECORD.unpack_from(shm.buf, offset) reads in place; no slice of the buffer is created. Part 5 explains struct and memoryview.
  • The record layout ("<qdd": little-endian, an int64 and two float64, 24 bytes) is an agreement between writer and reader. Shared memory has no schema; both sides must use the same layout, byte order and alignment (5.4).

4.4 Who may attach, and how they find the name#

Under multiprocessing, children inherit nothing except what you pass, so you pass the name (a short string), not the SharedMemory object. (A SharedMemory object can be pickled, and unpickling re-attaches it by name, which means passing the object works too, as a Process argument or in pool initargs (the same inheritance rule as 7.2); the documentation says the unpickled object "will still be the same shared object". The copy attaches by name with the default track setting, so it cannot re-attach once the segment has been unlinked. Passing the name is clearer and lets the worker control when to close.)

For processes that are not your children (a separate script, a different service on the same machine), publish the name through something both can read: an environment variable, a file, a config entry, or a well-known fixed name you choose ("myapp_embeddings_v3"). The version in the name is a good habit: a new matrix layout gets a new name, and old readers keep working on the old block until they restart.

4.5 The resource tracker and the leaked-segment warning#

What stops a crashed program from leaving shared memory behind forever? On POSIX, nothing in the kernel: a named segment lives until someone unlinks it or the machine reboots. So Python adds a safety net: the resource tracker, a tiny helper process started by multiprocessing. When you create or attach with track=True (the default), the tracker records the name. When the process tree finishes, the tracker unlinks anything still registered and prints a warning, so the leak is both cleaned and reported.

Forget unlink() and you see it:

python
# e09_leak.py: forget unlink() and see what the resource tracker says at interpreter exit.
from multiprocessing import shared_memory

shm = shared_memory.SharedMemory(name="lesson07_leaky", create=True, size=1024)
shm.buf[:4] = b"data"
shm.close()          # closed, but never unlinked: the NAME still exists in the OS
print("exiting without unlink()")
Example output · illustrative3 lines
exiting without unlink()
.../multiprocessing/resource_tracker.py:475: UserWarning: resource_tracker: There appear to be 1 leaked shared_memory objects to clean up at shutdown: {'/lesson07_leaky'}
  warnings.warn(

The tracker did remove the segment (a probe from a new process afterwards failed with FileNotFoundError), but you should treat the warning as a bug report: someone forgot unlink() on a normal exit. A tracker clean-up is the crash safety net, not the plan.

The shared tracker and the independent-process trap. All processes started with multiprocessing from one common ancestor share one tracker. A Python process started any other way (subprocess, a separate script, a different service) gets its own tracker when it attaches with track=True, and the documentation spells out the consequence: "This will cause the shared memory to be deleted by the resource tracker of the first process that terminates." Your reader exits and deletes the writer's segment. Python 3.13 added track=False for exactly this case: "users of subprocess or standalone Python processes should set track to False when there is already another process in place that does the bookkeeping."

The next script proves it with a throw-away subprocess attacher, once with track=True and once with track=False:

python
# e10_track.py: an UNRELATED Python process attaching to a segment (subprocess, not multiprocessing).
# With track=True (the default) its own resource tracker deletes the segment when it exits.
# With track=False (Python 3.13+) it leaves cleanup to the owner.
import subprocess
import sys
from multiprocessing import shared_memory

CHILD = """
import sys
from multiprocessing import shared_memory
shm = shared_memory.SharedMemory(name=sys.argv[1], track={track})
print("child read:", bytes(shm.buf[:5]))
shm.close()
"""

if __name__ == "__main__":
    for track in (True, False):
        owner = shared_memory.SharedMemory(create=True, size=16)
        owner.buf[:5] = b"hello"
        try:
            subprocess.run([sys.executable, "-c", CHILD.format(track=track), owner.name],
                           check=True, capture_output=True, text=True)
            try:
                probe = shared_memory.SharedMemory(name=owner.name, track=False)
                probe.close()
                alive = True
            except FileNotFoundError:
                alive = False
            print(f"child track={track!s:<5} -> segment still exists after the child exits: {alive}")
        finally:
            owner.close()
            try:
                owner.unlink()
            except FileNotFoundError:
                pass                       # the child's tracker already removed it

Output (standard output only; with track=True the parent's own tracker also prints two warnings to standard error because the segment vanished under it, which is the failure in action):

text
child track=True  -> segment still exists after the child exits: False
child track=False -> segment still exists after the child exits: True
Situation What to do
Owner and workers are all started by multiprocessing from one ancestor Leave track=True (default). The single tracker is the safety net. Workers only close(); the owner unlink()s
A separate program attaches to a segment owned by another process Attach with track=False (3.13+) and close() only; the owner unlinks
You are on Python 3.11 or 3.12 and need the independent-attacher case track does not exist. The common workaround is to call multiprocessing.resource_tracker.unregister(shm._name, "shared_memory") after attaching (it uses a private attribute, so pin your Python version and test it), or to avoid that topology
Windows track is ignored; Windows frees a block when the last handle closes

4.6 ShareableList and SharedMemoryManager#

ShareableList wraps a shared block in a list-like object for small, simple values. It supports int (signed 64-bit), float, bool, str, bytes and None, and you cannot change its length: no append, no insert, no slicing that creates new lists. Strings and bytes live in fixed slots sized from the value you create the list with.

SharedMemoryManager (in multiprocessing.managers) is a manager whose only job is to own shared blocks. When you leave its with block (or call shutdown()), it unlink()s every block it created, so you do not write the cleanup yourself.

python
# e11_shareable_list.py: ShareableList: a fixed-length, typed list that several processes can see.
# Use case: a tiny status board, one slot per worker (state, documents done, last error).
import multiprocessing as mp
from multiprocessing import shared_memory
from multiprocessing.managers import SharedMemoryManager


def worker(list_name: str, slot: int) -> None:
    board = shared_memory.ShareableList(name=list_name)        # attach by name, no sequence given
    board[slot] = f"worker-{slot}: done"
    board.shm.close()


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    # SharedMemoryManager owns the segments: leaving the `with` block unlinks everything it made.
    with SharedMemoryManager() as smm:
        board = smm.ShareableList(["idle".ljust(16)] * 3 + [0, 3.5, True, None, b"raw"])
        print("format:", board.format)                         # the struct format; each str slot is sized to its initial value
        print("types:", [type(x).__name__ for x in board])
        ps = [ctx.Process(target=worker, args=(board.shm.name, i)) for i in range(3)]
        for p in ps:
            p.start()
        for p in ps:
            p.join()
        print("slots 0-2:", [board[i] for i in range(3)])

        # limits: no append, no length change, and strings are capped at their ORIGINAL storage size
        try:
            board.append(1)
        except AttributeError as exc:
            print("AttributeError:", exc)
        try:
            board[0] = "x" * 100                                   # 100 bytes into a 16-byte slot
        except ValueError as exc:
            print("ValueError:", exc)
        # a shorter replacement fits in the same slot:
        board[0] = "ok"
        print("slot 0 now:", repr(board[0]), "| len:", len(board))
        board.shm.close()
    print("segments released by the manager on exit")
Output7 lines
format: 24s24s24sqdxxxxxxx?xxxxxx?x8s
types: ['str', 'str', 'str', 'int', 'float', 'bool', 'NoneType', 'bytes']
slots 0-2: ['worker-0: done', 'worker-1: done', 'worker-2: done']
AttributeError: 'ShareableList' object has no attribute 'append'
ValueError: bytes/str item exceeds available storage
slot 0 now: 'ok' | len: 8
segments released by the manager on exit

What the output teaches:

  • Slot sizes are fixed at creation. Each str slot is sized from its initial value rounded up to a multiple of 8 bytes: a 16-character placeholder produced a 24s slot here. A longer string raises ValueError: bytes/str item exceeds available storage. (Had this script created the list with six-character placeholders, the workers' 14-character messages would not have fit, and each child process would have died with exactly this error. Create the list with placeholders as long as the longest value you will ever store. Exercise 3 explores the rounding.)
  • The format string is a struct format. Each element has a type code and padding (x bytes); the list is a single contiguous block, so it is as fast as struct, with none of the pickling.
  • Workers attach by name with ShareableList(name=...) and need no sequence; they must close() their own handle (board.shm.close()).
  • A documented gotcha: the official page notes that strings or bytes ending in NUL characters (\x00) "may be silently stripped" when fetched, which it calls a bug (gh-106939). Do not store data that can end in a NUL byte.
  • Using a ShareableList after unlink() is not supported.

ShareableList is a convenience for small status tables (one slot per worker, a handful of flags). For real data volumes use a SharedMemory block with an explicit layout (Part 5).

4.7 Platform differences#

Linux macOS Windows
Backing POSIX shm (/dev/shm, a tmpfs) POSIX shm Named file mapping
Visible as files Yes, under /dev/shm No No
Size rounding Usually exact Rounded up to a page (16,384 bytes on this Apple-silicon machine) Page-rounded
Name length limit Long (file-name limits, typically 255) Short: a 40-character name failed here with OSError: [Errno 63] File name too long (the limit is commonly stated as 31 characters including the leading slash; Python's generated psm_xxxxxxxx names fit) Different rules
unlink() Removes the name Removes the name No effect; freed when the last handle closes
track parameter Meaningful Meaningful Ignored
Capacity limit A tmpfs: counts against RAM, capped by the /dev/shm mount size System limits on shared memory System commit limit

Only the macOS column was run for this lesson. The Linux and Windows cells describe the usual behaviour; the authoritative references are the shm_overview(7) and shm_open(3) man pages (Linux and POSIX), and Microsoft's file-mapping documentation (CreateFileMapping) for Windows. The macOS name limit is a header constant in the system's shared-memory code (commonly cited as 31 characters), which we did not look up. Where a cell matters to you, check your OS documentation and test on your deployment platform.


Part 5: Reading and writing bytes without copying: memoryview, struct and typed views#

Deep-dive

Shared memory gives you bytes. This part is the toolkit for turning bytes into numbers and records without copying them.

5.1 memoryview: a window onto a buffer#

A memoryview is a view of someone else's memory. Slicing a bytes makes a copy of the slice; slicing a memoryview makes a new, tiny view of the same bytes. For multi-megabyte buffers that is the difference between free and expensive, and it works on bytes, bytearray, array.array, mmap.mmap and SharedMemory.buf.

python
# e14_memoryview.py: slicing bytes copies; slicing a memoryview does not.
import array
import struct
import tracemalloc

blob = bytearray(b"x" * 10_000_000)            # a 10 MB buffer (say, a page image or a vector block)

tracemalloc.start()
base, _ = tracemalloc.get_traced_memory()
chunk = bytes(blob[1000:9_000_000])            # slice then bytes(): a real copy of 8 MB
_, peak_copy = tracemalloc.get_traced_memory()
del chunk
tracemalloc.reset_peak()
mv = memoryview(blob)
window = mv[1000:9_000_000]                    # a new VIEW object: 8 MB are not copied
_, peak_view = tracemalloc.get_traced_memory()
tracemalloc.stop()
print("copy allocated ~8 MB:", (peak_copy - base) > 7_000_000)
print("view allocated under 1 KB extra:", (peak_view - base) < 1000)
print("window length:", len(window), "| shares memory with blob:", window.obj is blob)

# writing through a view writes the original
window[0:3] = b"abc"
print("blob changed through the view:", bytes(blob[1000:1003]))

# typed views: reinterpret the same bytes as floats, ints... without converting
vec = array.array("f", [0.5, 1.5, 2.5, 3.5])
raw = memoryview(vec).cast("B")                # the same memory as 16 raw bytes
print("bytes:", raw.nbytes, "| back as floats:", list(raw.cast("f")))

# struct.unpack_from reads straight out of any buffer at an offset: no slicing needed
header = struct.pack("<4sHH", b"DOC1", 7, 3)    # magic, version, pages
print("unpack_from at offset 0:", struct.unpack_from("<4sHH", memoryview(header), 0))

# release views before you resize or close the owner
window.release()
mv.release()
blob.extend(b"!")                              # fine now; with a live view this raises BufferError
print("resized after releasing views:", len(blob))
Output7 lines
copy allocated ~8 MB: True
view allocated under 1 KB extra: True
window length: 8999000 | shares memory with blob: True
blob changed through the view: b'abc'
bytes: 16 | back as floats: [0.5, 1.5, 2.5, 3.5]
unpack_from at offset 0: (b'DOC1', 7, 3)
resized after releasing views: 10000001

What to take from it:

  • Copying an 8 MB slice allocated about 8 MB; making a view of it allocated well under a kilobyte (measured with tracemalloc, which is why the output prints booleans rather than exact byte counts).
  • A write through a view writes the original. That is the point, and the danger: any view of shared memory writes shared memory.
  • cast("B") and cast("f") reinterpret the same bytes as another type. Sixteen bytes became four float32s with no conversion step. (cast needs a contiguous buffer and a size that divides evenly.)
  • struct.unpack_from(fmt, buffer, offset) reads straight out of any buffer at an offset, so you do not need to slice first.
  • Release views before you resize or close the owner. A live view pins the buffer: bytearray.extend or SharedMemory.close() raises BufferError while one exists. Use with memoryview(x) as view: or call view.release().

5.2 struct: records in bytes#

struct packs Python values into bytes using a format string and unpacks them back. For shared memory you want the in-place variants: struct.pack_into(fmt, buffer, offset, *values) and struct.unpack_from(fmt, buffer, offset). Precompiled struct.Struct(fmt) objects are faster and carry .size.

Format piece Meaning
< / > / = / ! Little-endian / big-endian / native byte order, no padding / network (big-endian). Always start with < (or =) in a shared layout so the size does not depend on alignment rules
q / Q signed / unsigned 64-bit integer
i / I signed / unsigned 32-bit integer
d / f 64-bit / 32-bit float
? boolean (1 byte)
16s exactly 16 bytes; shorter values are padded with NUL
x one padding byte

Alignment matters, and the default is not what you expect. Run this:

python
# e25_struct_layout.py: how big is one record? Alignment and byte order change the answer.
import struct

for fmt in ("<qdd", "qdd", "<q3sd", "q3sd", "<q3sxd"):
    print(f"{fmt:<8} -> {struct.calcsize(fmt)} bytes")
Output5 lines
<qdd     -> 24 bytes
qdd      -> 24 bytes
<q3sd    -> 19 bytes
q3sd     -> 24 bytes
<q3sxd   -> 20 bytes

Without a leading </=, struct uses the platform's native layout and inserts alignment padding: q3sd is 24 bytes (padding after the 3-byte string so the double starts on an 8-byte boundary), while <q3sd is a packed 19. Two processes on the same machine agree either way, but a file or a segment shared between different platforms or languages must use an explicit prefix, and a layout you document is one you can version.

5.3 Typed and two-dimensional views#

memoryview.cast(format, shape=[rows, cols]) gives you a typed, multi-dimensional window, and indexing with view[r, c] works. That is enough for a small shared matrix with the standard library alone, which the AI section uses (11.1):

python
import multiprocessing.shared_memory as sm

shm = sm.SharedMemory(create=True, size=3 * 4 * 4)          # 3 rows x 4 float32 columns
try:
    matrix = shm.buf[:3 * 4 * 4].cast("f", shape=[3, 4])      # typed 2-D view, no copy
    matrix[1, 2] = 0.5
    print(matrix[1, 2], matrix.shape)
    matrix.release()                                           # before close()
finally:
    shm.close()
    shm.unlink()

Note the slice shm.buf[:n]: shm.size can be larger than you asked for, and cast requires an exact fit, so cut the view to the length you need.

NumPy over a shared buffer. If you have NumPy (it is not run in this lesson, and the snippet is illustrative) the same thing is one line, and it is what the shared-memory documentation itself demonstrates:

python
# Illustrative: requires numpy (not run in this lesson). Names are placeholders.
import numpy as np
from multiprocessing import shared_memory

rows, dim = 100_000, 1024
embeddings = np.random.default_rng(0).standard_normal((rows, dim), dtype=np.float32)

shm = shared_memory.SharedMemory(create=True, size=embeddings.nbytes)
try:
    shared = np.ndarray(embeddings.shape, dtype=embeddings.dtype, buffer=shm.buf)
    shared[:] = embeddings[:]          # the ONE copy into shared memory

    # A worker that knows (name, shape, dtype) builds the SAME array without copying:
    #   existing = shared_memory.SharedMemory(name=shm.name)
    #   view = np.ndarray((rows, dim), dtype=np.float32, buffer=existing.buf)
    #   scores = view @ query            # reads shared pages in place
    #   del view; existing.close()       # drop the array BEFORE closing
finally:
    del shared                             # an array is a live view: drop it before close()
    shm.close()
    shm.unlink()

Four rules for NumPy on shared memory: (1) tell workers the name, shape and dtype: the block does not carry them; (2) never let the array outlive close(): del it first, or you get BufferError (or a crash if you keep using it after the block is gone); (3) pass dtype explicitly, matching on both sides; (4) writing in place needs the same coordination as any shared write (Part 7).

Typed views with ctypes (no NumPy, no struct.unpack)

ctypes can lay a C structure or array directly over the buffer with from_buffer. Reads and writes are attribute and index access on the shared bytes, with no copy. Like a memoryview, each such object exports a pointer into the buffer, so you must del it before shm.close() or you get the same BufferError as in 4.2.

python
# f04_ctypes_view.py: a typed struct and array over a SharedMemory buffer with ctypes.
import ctypes
from multiprocessing import shared_memory


class Header(ctypes.Structure):
    _fields_ = [("version", ctypes.c_uint32), ("rows", ctypes.c_uint32), ("scale", ctypes.c_double)]


if __name__ == "__main__":
    shm = shared_memory.SharedMemory(create=True, size=ctypes.sizeof(Header) + 4 * 8)
    try:
        hdr = Header.from_buffer(shm.buf)                          # no copy: a view
        vec = (ctypes.c_double * 4).from_buffer(shm.buf, ctypes.sizeof(Header))
        hdr.version, hdr.rows, hdr.scale = 1, 4, 0.5
        vec[:] = [1.0, 2.0, 3.0, 4.0]
        check = Header.from_buffer_copy(bytes(shm.buf[:ctypes.sizeof(Header)]))
        print("header:", check.version, check.rows, check.scale, "vector:", list(vec))
        try:
            shm.close()                                            # views still alive
        except BufferError as exc:
            print("BufferError:", exc)
        del hdr, vec                                               # drop the exported pointers first
        shm.close()
        print("closed cleanly")
    finally:
        shm.unlink()
Output · Python 3.14.61 line

Header.from_buffer_copy(...) makes an independent copy instead of a view. For data created before you fork or spawn children, multiprocessing.sharedctypes.RawArray (and multiprocessing.sharedctypes.copy) gives the same typed access without a named segment; it is the inherited cousin of this idiom, and Part 3 already used it.

5.4 Designing a layout#

A shared block is just bytes, so you are designing a tiny binary format. A layout that survives real use:

text
offset  size  field
0       4     magic            b"EMB1"           (reject anything else)
4       2     version          1                 (bump when the layout changes)
6       2     dtype code       1 = float32
8       8     rows             int64
16      8     dim              int64
24      8     generation       int64             (bumped by the writer after each full rebuild)
32      ...   data             rows * dim * 4 bytes, row-major

Why each piece earns its place:

Field Why
Magic bytes A reader that attaches to the wrong block, or to a block from a stale deployment, fails immediately instead of reading garbage
Version Lets old readers refuse a new layout and lets you roll forward
Shape and dtype in the header The block is self-describing, so a worker needs only the name
Generation counter A reader can notice that the writer rebuilt the data. With a lock or an epoch protocol (7.5) it can switch safely
Fixed-size records, aligned Row i is at offset + i * record_size: constant-time random access with no index

Use fixed-width fields for anything the reader must find by arithmetic, and put variable-length data (long text, nested JSON) elsewhere: shared memory is for numbers and fixed records, and the strings go in a queue, a file or a database, referenced by row id.


Part 6: mmap: memory-mapped files#

Deep-dive

6.1 What a memory map is#

Memory-mapping asks the operating system to make a file (or a region of anonymous memory) appear as a range of addresses in your process. Reading those addresses reads the file; the kernel loads pages from disk on first touch ("demand paging") and keeps them in the page cache, which is RAM the kernel manages for all processes. Two properties follow, and they are why mmap matters for AI:

  1. No loading step. Opening a 20 GB vector file costs almost nothing; only the pages you touch are read.
  2. Sharing is automatic. Ten processes that map the same file read from the same physical pages in the page cache. The file is the shared memory.

Python exposes this as mmap.mmap. On Unix:

text
mmap.mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE | PROT_READ, access=ACCESS_DEFAULT, offset=0, *, trackfd=True)

(Windows has tagname in place of flags and prot.) The pieces that matter:

Parameter Meaning
fileno An open file's descriptor (f.fileno()), or -1 for anonymous memory (no file)
length Bytes to map; 0 means "the whole file as it is now" (the file must be non-empty on Windows)
access ACCESS_READ (read-only: assignment raises TypeError), ACCESS_WRITE (write-through: changes reach the file), ACCESS_COPY (copy-on-write: changes stay in this process and never reach the file), ACCESS_DEFAULT (use prot). Do not mix access with flags/prot
flags (Unix) MAP_SHARED (default: changes are shared with other mappers and the file) or MAP_PRIVATE (a private copy-on-write mapping)
offset Where in the file the map starts; must be a multiple of mmap.ALLOCATIONGRANULARITY (equal to the page size on Unix)
trackfd (3.13+, Unix) False stops mmap from duplicating the file descriptor; then size() and resize() do not work

mmap objects are context managers, behave like bytearray (slicing, find, re searches) and like a file (seek, read, write, readline), and can be wrapped in a memoryview. They cannot be pickled: you pass the path and let each process map the file for itself.

6.2 Anonymous maps and fork#

mmap.mmap(-1, size) creates anonymous memory (no file behind it). On Unix the default flags are MAP_SHARED, so a child created by fork shares it with the parent: a lock-free, name-free way to share a small block among processes you fork yourself. The same holds for a file mapped with MAP_SHARED (the default, ACCESS_WRITE) before the fork: parent and children share the same dirty pages, and those pages are written back to the file.

python
# e12_mmap_anonymous.py: anonymous mmap is shared with children created by fork(), but not by spawn.
# POSIX only for the fork half (Windows has no fork); the guard keeps the file runnable everywhere.
import mmap
import multiprocessing as mp
import struct
import warnings


def add_one_hundred(region) -> None:
    (n,) = struct.unpack_from("<q", region, 0)
    struct.pack_into("<q", region, 0, n + 100)


if __name__ == "__main__":
    warnings.simplefilter("ignore")                 # silence "fork with threads" noise; we have none
    region = mmap.mmap(-1, 4096)                    # -1 = no file; Unix default flags = MAP_SHARED
    struct.pack_into("<q", region, 0, 1)

    if "fork" in mp.get_all_start_methods():
        p = mp.get_context("fork").Process(target=add_one_hundred, args=(region,))
        p.start()
        p.join()
        print("after a forked child ran:", struct.unpack_from("<q", region, 0)[0])
    else:
        print("no fork on this platform")

    # With spawn the mmap must be pickled to reach the child, and mmap objects are not picklable:
    try:
        p = mp.get_context("spawn").Process(target=add_one_hundred, args=(region,))
        p.start()
        p.join()
    except TypeError as exc:
        print("spawn:", exc)
    region.close()
Output2 lines
after a forked child ran: 101
spawn: cannot pickle 'mmap.mmap' object

The forked child's write is visible to the parent, because the mapping is shared (MAP_SHARED), while the ordinary dictionary change in the earlier example was not. Under spawn or forkserver the child does not inherit the mapping, and mmap objects cannot be pickled to send it, which is the TypeError above. For spawn, use a file-backed mmap (each process maps the same path) or SharedMemory (each attaches the same name).

6.3 A memory-mapped vector file#

The AI use case, with the standard library only: a file of float32 vectors, one row per document chunk, mapped read-only so any number of workers can read any row without loading the file.

python
# e13_mmap_file.py: a memory-mapped file of float32 "embeddings": random access with no loading step.
import array
import math
import mmap
import multiprocessing as mp
import os
import tempfile

DIM = 4
ROWS = 1000


def dot_with_row(path: str, row: int, query: list[float], out) -> None:
    # Each process maps the SAME file read-only. The OS shares the physical pages between them.
    with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
        vec = memoryview(mm).cast("f")[row * DIM:(row + 1) * DIM]    # a float32 view, no copy
        out.put(sum(a * b for a, b in zip(vec, query)))
        vec.release()


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as tmp:
        path = os.path.join(tmp, "vectors.f32")

        # build the file: row r is [r, r+1, r+2, r+3] as float32 (the layout np.save/np.memmap would use)
        data = array.array("f", (r + c for r in range(ROWS) for c in range(DIM)))
        with open(path, "wb") as f:
            data.tofile(f)
        print("file bytes:", os.path.getsize(path), "= rows * dim * 4:", ROWS * DIM * 4)

        # 1. read row 2 without loading the file
        with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
            view = memoryview(mm).cast("f")
            print("row 2:", list(view[2 * DIM:3 * DIM]), "| float32 items:", len(view))
            print("view is backed by the mmap itself (no copy):", view.obj is mm)
            try:
                view[0] = 1.0
            except TypeError as exc:
                print("read-only map:", exc)
            view.release()

        # 2. two worker processes read different rows of the same file
        ctx = mp.get_context("spawn")
        out = ctx.Queue()
        q = [1.0, 0.0, 0.0, 1.0]
        ps = [ctx.Process(target=dot_with_row, args=(path, r, q, out)) for r in (10, 500)]
        for p in ps:
            p.start()
        got = sorted(out.get() for _ in ps)
        for p in ps:
            p.join()
        print("dot products:", got)

        # 3. ACCESS_COPY: writes are private to this mapping; the file does not change
        with open(path, "r+b") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY) as mm:
            mm[0:4] = b"\x00\x00\x80\x3f"                     # float32 1.0 at row 0, col 0
            print("copy-on-write view sees:", memoryview(mm).cast("f")[0])
        with open(path, "rb") as f:
            print("file still has:", array.array("f", f.read(4))[0])

        # 4. ACCESS_WRITE: write-through; flush() asks the OS to persist
        with open(path, "r+b") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE) as mm:
            mm[0:4] = b"\x00\x00\x80\x3f"
            mm.flush()
        with open(path, "rb") as f:
            print("after ACCESS_WRITE the file has:", array.array("f", f.read(4))[0])

        print("granularity is a multiple of the page size:",
              mmap.ALLOCATIONGRANULARITY % mmap.PAGESIZE == 0)
Output9 lines
file bytes: 16000 = rows * dim * 4: 16000
row 2: [2.0, 3.0, 4.0, 5.0] | float32 items: 4000
view is backed by the mmap itself (no copy): True
read-only map: cannot modify read-only memory
dot products: [23.0, 1003.0]
copy-on-write view sees: 1.0
file still has: 0.0
after ACCESS_WRITE the file has: 1.0
granularity is a multiple of the page size: True

Line by line:

  • The file is exactly rows * dim * 4 bytes: a flat array on disk, the layout numpy.save and numpy.memmap use for plain arrays. Row r starts at byte r * dim * 4, so a random access is arithmetic, not a search.
  • memoryview(mm).cast("f") is a float32 view of the mapped file: view.obj is mm is True, so nothing was copied. Writing to it fails because the map is ACCESS_READ.
  • Two worker processes mapped the same path and computed dot products against different rows. They share the same page-cache pages: that is the "one copy in RAM" property.
  • ACCESS_COPY: the write succeeded in memory (the view saw 1.0) but the file still held 0.0: copy-on-write at the mapping level, handy for a scratch edit that must not persist.
  • ACCESS_WRITE: the change reached the file; flush() asks the operating system to write dirty pages out, and the documentation says that without it "there is no guarantee that changes are written back before the object is destroyed".

Searching a large text file the same way needs no loading either (Exercise 9): mm.find(b"ERROR") scans mapped pages at C speed.

mmap or SharedMemory?

mmap (file-backed) SharedMemory
Data already on disk Yes: no loading, no copy Needs one copy from disk into the segment
Survives restart Yes (it is a file) No
Unrelated processes Share by path Share by name
Writable by all, fast scratch Possible, but dirty pages flush to disk Natural: pure RAM
Cleanup Delete the file unlink() and the resource tracker
Size limit Disk and address space RAM (and /dev/shm)

Rule of thumb: read-mostly data that exists as a file → mmap. Data produced at run time, or scratch results workers write into → SharedMemory.


Part 7: Synchronization across processes#

Deep-dive

7.1 Shared memory gives you no safety#

Everything in 01C.3 applies, with extra teeth. SharedMemory, mmap and RawArray are plain bytes: no locks, no atomic operations, no memory-ordering promises you can use from Python. Two processes doing buf[0] += 1 lose updates exactly as two threads do. The GIL cannot help, because there are two interpreters and two GILs. The interleaving is chosen by the kernel's scheduler, across cores, in real parallel; it is worse than threads because the code between the steps really does run at the same time.

7.2 Locks that work across processes#

The threading primitives work only within one process. For several processes, multiprocessing provides the same family, built on operating-system semaphores: Lock, RLock, Semaphore, BoundedSemaphore, Event, Condition and Barrier. Create them from the same context and pass them to the children.

python
# e17_locks.py: shared memory has no built-in synchronization. Locks that work ACROSS processes.
import multiprocessing as mp
import os
import time

N_PER_WORKER = 20_000
WORKERS = 4


def add_locked(counter, lock) -> None:
    for _ in range(N_PER_WORKER):
        with lock:
            counter.value += 1


def add_unlocked(counter) -> None:
    for _ in range(N_PER_WORKER):
        counter.value += 1                       # RawValue: read, add, write: three steps, not atomic


def hold_lock_then_die(lock, ready) -> None:
    lock.acquire()
    ready.set()
    os._exit(1)                                  # crash: no finally, no with, the lock is never released


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    expected = N_PER_WORKER * WORKERS

    # 1. with a lock: exact, every run
    counter = ctx.RawValue("q", 0)
    lock = ctx.Lock()
    ps = [ctx.Process(target=add_locked, args=(counter, lock)) for _ in range(WORKERS)]
    for p in ps:
        p.start()
    for p in ps:
        p.join()
    print("locked total correct:", counter.value == expected)

    # 2. without a lock: updates are usually lost (the exact total varies run to run)
    counter = ctx.RawValue("q", 0)
    ps = [ctx.Process(target=add_unlocked, args=(counter,)) for _ in range(WORKERS)]
    for p in ps:
        p.start()
    for p in ps:
        p.join()
    print(f"unlocked total: {counter.value} of {expected} (lost {expected - counter.value})")

    # 3. a process that dies holding a lock leaves it locked FOREVER (no owner cleanup)
    lock = ctx.Lock()
    ready = ctx.Event()
    p = ctx.Process(target=hold_lock_then_die, args=(lock, ready))
    p.start()
    ready.wait()
    p.join()
    print("holder exit code:", p.exitcode)
    print("acquire(timeout=0.5) after the holder died:", lock.acquire(timeout=0.5))

    # 4. Semaphore: limit how many PROCESSES do something at once (here: 2 at a time)
    sem = ctx.BoundedSemaphore(2)
    print("two slots taken:", sem.acquire(False), sem.acquire(False), "| a third:", sem.acquire(False))
Example output · illustrative5 lines
locked total correct: True
unlocked total: 47644 of 80000 (lost 32356)
holder exit code: 1
acquire(timeout=0.5) after the holder died: False
two slots taken: True True | a third: False

Four things to read in that output:

  1. With a lock the total is exact, every run. Eighty thousand increments from four processes, one at a time.
  2. Without a lock, a large share of the updates vanished (about 40% here; it varies, and it can be near zero on a quiet machine, which is what makes this class of bug intermittent). This is 01C.3's lost update across processes.
  3. A process that dies holding a lock leaves it locked for ever. The holder exited with code 1 through os._exit (no finally, no context manager), and the lock was still held 0.5 seconds later (acquire returned False). multiprocessing.Lock has no owner and no automatic cleanup. This is a deadlock source (01C.4): always acquire with a timeout in code that must keep running, and design so that the crash of a worker cannot leave a shared lock held (keep critical sections short, with no I/O inside).
  4. A BoundedSemaphore(2) let two processes in and refused a third: a way to cap how many processes do something at once, for example how many workers may hit a rate-limited resource.

Also from the documentation: multiprocessing.Lock is "a close analog of threading.Lock" and, unlike a thread lock, "any process or thread may release it". Primitives created under the fork context cannot be passed to children started under spawn or forkserver.

Why a pool will not take your Lock as an argument

Lock, Semaphore, Queue, Value and the other synchronized objects can only be shared through inheritance: as Process arguments at creation, or as pool initargs. A pool task is pickled and sent later through a pipe, and these objects refuse to be pickled that way. This is the commonest failure when people move from Process to ProcessPoolExecutor.

python
# f02_inheritance.py: a Lock handed to a pool as a TASK argument fails; initargs works.
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor

_lock = None


def init(lock) -> None:
    global _lock
    _lock = lock


def bad(lock) -> int:
    with lock:
        return 1


def good(_: int) -> int:
    with _lock:
        return 1


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    lock = ctx.Lock()
    with ProcessPoolExecutor(2, mp_context=ctx) as pool:
        try:
            pool.submit(bad, lock).result()
        except RuntimeError as exc:
            print("task argument:", exc)

    with ProcessPoolExecutor(2, mp_context=ctx, initializer=init, initargs=(lock,)) as pool:
        print("initargs:", sum(pool.map(good, range(4))))

    with ctx.Manager() as m:
        mlock = m.Lock()                              # a proxy: picklable
        with ProcessPoolExecutor(2, mp_context=ctx) as pool:
            print("Manager().Lock() as argument:", pool.submit(bad, mlock).result())
Output · Python 3.14.61 line

Three fixes: hand the object over in initializer= / initargs= (as 9.2 does), use a manager proxy (Manager().Lock(), Manager().Queue(), which pickle fine but cost a round trip per call), or avoid the shared primitive by partitioning the writes (7.3).

7.3 The cheapest synchronization: do not share the writes#

The most robust cure is not a faster lock; it is no contention:

Pattern How Used in
Partition by index Each worker writes only its own slice or slot; the parent reads after join() 4.3, the per-worker array in Part 3
Private first, merge once Each worker accumulates into local variables, then takes the lock once to add its totals Exercise 7
Single writer Exactly one process writes a block; everyone else only reads Read-mostly indexes, 7.5
Messages for control, memory for data Send "slice 3 is ready" through a Queue; the worker reads slice 3 from shared memory 11.1

One performance trap even without locks: several processes writing to different slots that sit on the same CPU cache line (typically 64 bytes) still slow each other down, because the line bounces between cores (false sharing). Give hot per-worker counters their own cache line of space, or accumulate privately and write once.

Each reduces the number of times a lock is taken from per element to per worker, which matters because a cross-process lock costs an operating-system call and a possible context switch (01C.1 §5.4).

7.4 File locks: coordinating unrelated processes#

multiprocessing.Lock needs a common ancestor to share it. For unrelated programs (a cron job and a service, two deployments of the same script), use a lock file. On Unix, fcntl.flock locks an open file descriptor; the operating system releases the lock if the process dies, which fixes the stuck-lock problem of the previous section.

python
# e18_file_lock.py: a cross-process mutex built on a lock FILE (Unix: fcntl.flock).
# Use case: "only one ingestion job at a time may rebuild the index", across independent programs.
# On Windows use msvcrt.locking or a library such as filelock; fcntl does not exist there.
import contextlib
import fcntl
import os
import tempfile


@contextlib.contextmanager
def file_lock(path: str, blocking: bool = True):
    fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
    try:
        flags = fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB)
        fcntl.flock(fd, flags)                   # the OS releases it if the process dies
        try:
            yield
        finally:
            fcntl.flock(fd, fcntl.LOCK_UN)
    finally:
        os.close(fd)


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as tmp:
        path = os.path.join(tmp, "reindex.lock")
        with file_lock(path):
            print("first holder: acquired")
            try:
                with file_lock(path, blocking=False):          # a second handle = a second "program"
                    print("second holder: acquired (unexpected)")
            except BlockingIOError:
                print("second holder: refused (BlockingIOError) while the first holds it")
        with file_lock(path, blocking=False):
            print("after release: acquired")
        # crash safety: close the descriptor (what the OS does when a process dies) and it is free
        fd = os.open(path, os.O_RDWR)
        fcntl.flock(fd, fcntl.LOCK_EX)
        os.close(fd)                                           # simulates the holder dying
        with file_lock(path, blocking=False):
            print("after the holder 'died': acquired")
Output4 lines
first holder: acquired
second holder: refused (BlockingIOError) while the first holds it
after release: acquired
after the holder 'died': acquired

Notes:

  • The lock lives in the kernel and is attached to the open file, not to the file's contents. Create the lock file once and never delete it while others may use it: deleting and recreating can give two programs two different files.
  • LOCK_NB makes the attempt non-blocking: BlockingIOError instead of waiting. Prefer it, or loop with a timeout, in anything that must stay responsive.
  • Windows has no fcntl. Use msvcrt.locking or a small library such as filelock (third-party; check its page). Network file systems (NFS and similar) have weaker locking semantics; do not use file locks across machines.
  • A file lock guards cooperating programs only. It is advisory: a program that does not ask for the lock is not stopped.

7.5 Single writer, many readers, and versioned blocks#

Many AI services have this shape: one process rebuilds an index or a vector table occasionally, and many workers read it constantly. The safe pattern, in order of simplicity:

  1. Write a new block, publish by name, retire the old one. The builder creates emb_v8 (a new segment or a new file), fills it completely, and only then tells readers (a queue message, a small file, an environment reload) that emb_v8 is current. Readers switch at a moment of their choosing and close() the old block; the builder unlink()s the old one when nobody uses it. A reader never sees a half-written block because the half-written block has no readers.
  2. For files, write to a temporary name and os.replace it into place. Rename is atomic on POSIX (on Windows, check the documented limits of os.replace); readers who already mapped the old file keep a consistent view of it, because the old file's pages stay alive while they hold the mapping.
  3. Only if you must update in place, use a lock (or a reader/writer protocol) around the writes, and give the block a generation counter that readers compare before and after a read to detect a concurrent rebuild. This is a hand-rolled version of the "seqlock" idea; in Python, where you cannot control memory ordering, prefer a real lock to a clever flag.

Part 8: fork and copy-on-write#

8.1 What copy-on-write means#

When a process calls fork, the operating system does not copy all of its memory. It gives the child the same physical pages, marked read-only, and copies a page only when one side writes to it: copy-on-write (CoW). A parent with a 3 GB model loaded can fork eight workers, and until they write, all nine share one 3 GB copy. This is the oldest trick for sharing a large read-only structure, and it is what pre-forking servers rely on ("load the model, then fork the workers").

The child's view is a private snapshot: a write after the fork changes only the writer's copy, and is invisible to the other side. A shared mapping (MAP_SHARED, a SharedMemory block, a Value) is the opposite: writes are visible to all.

python
# e21_fork_isolation.py: after fork the child has a PRIVATE copy of every ordinary Python object.
# Only memory deliberately mapped as shared (mmap/shared_memory/Value) is visible across.
import mmap
import multiprocessing as mp
import warnings

cache = {"model": "v1"}


def child(shared_region) -> None:
    cache["model"] = "v2-in-child"          # changes the child's copy only
    shared_region[0:5] = b"CHILD"           # changes memory both processes map


if __name__ == "__main__":
    warnings.simplefilter("ignore")
    region = mmap.mmap(-1, 16)
    region[0:5] = b"PARNT"
    p = mp.get_context("fork").Process(target=child, args=(region,))
    p.start()
    p.join()
    print("parent's dict after the child ran:", cache)
    print("parent's shared region after the child ran:", bytes(region[0:5]))
    region.close()
Output2 lines
parent's dict after the child ran: {'model': 'v1'}
parent's shared region after the child ran: b'CHILD'

The child's change to the dictionary stayed in the child. Its change to the shared mmap reached the parent.

8.2 Why Python breaks copy-on-write#

Here is the catch for Python specifically. Every Python object starts with a reference count (01C.6 explains it fully; 01C.5 §1.2 showed one). Merely reading an object (looping over a list, passing an item to a function) adds one to its count and removes one afterwards. The count lives in the object's header, in the same memory page as the object. So a child that only reads a big list of Python objects still writes to every page that holds those objects, and the kernel copies each of those pages. The "shared" gigabytes silently become private, one page at a time, and the machine's memory use climbs toward workers × size.

A raw buffer (array.array, bytes, a mmap, NumPy's data block) is different: its contents are one big object with one header. Reading its elements touches no per-element counts, so its pages stay shared. The experiment counts the child's minor page faults (each first write to a shared page is one) while it reads two structures holding the same two million numbers:

python
# e20_fork_cow.py: copy-on-write after fork(). A child that merely READS Python objects still writes
# to their pages (reference counts), forcing copies. Raw buffers (array, bytes, mmap) have no such counts.
# POSIX only. We count minor page faults in the child: each first write to a shared page is one fault.
import array
import multiprocessing as mp
import resource
import warnings

N = 2_000_000
objects = None          # list of distinct int objects (each has a refcount in its header)
raw = None              # the same numbers in one flat array of C ints


def touch_objects(q) -> None:
    before = resource.getrusage(resource.RUSAGE_SELF).ru_minflt
    total = 0
    for x in objects:                    # read-only in intent: but every x gets INCREF/DECREF
        total += x
    q.put(("list of int objects", resource.getrusage(resource.RUSAGE_SELF).ru_minflt - before, total))


def touch_array(q) -> None:
    before = resource.getrusage(resource.RUSAGE_SELF).ru_minflt
    total = sum(raw)                     # reads bytes inside one buffer; no per-element refcount writes to it
    q.put(("array('q')", resource.getrusage(resource.RUSAGE_SELF).ru_minflt - before, total))


if __name__ == "__main__":
    warnings.simplefilter("ignore")
    objects = [1_000_000 + i for i in range(N)]
    raw = array.array("q", objects)
    ctx = mp.get_context("fork")
    faults = {}
    for fn in (touch_objects, touch_array):
        q = ctx.Queue()
        p = ctx.Process(target=fn, args=(q,))
        p.start()
        name, f, total = q.get()
        p.join()
        faults[name] = f
        print(f"{name:<22} sum ok: {total == sum(objects)}")
    ratio = faults["list of int objects"] / max(1, faults["array('q')"])
    print("page faults in the child, list vs array: list is more than 3x higher:", ratio > 3)
    print("raw numbers (machine-specific):", faults)
Output · booleans only; the underlying fault counts are machine-specific3 lines
list of int objects    sum ok: True
array('q')             sum ok: True
page faults in the child, list vs array: list is more than 3x higher: True

On this machine the list case produced roughly nine times as many page faults as the array case (about 8,800 against about 1,000, of which most of the thousand is the interpreter's own baseline); your counts differ with page size and platform. The direction does not: reading Python objects after a fork dirties their pages; reading a flat buffer does not.

8.3 What this means in practice#

Goal Do this
Share a big read-only numeric array with forked workers Build it in the parent as array, NumPy, or a memoryview of a mmap/SharedMemory; fork afterwards. It stays shared
Share a big read-only dict or list of Python objects Expect it to be copied as children touch it. Convert it to a compact form (arrays, a sqlite3 file, a memory-mapped index) or accept workers × size
Pre-fork web servers with a loaded model Load the model before forking (for example gunicorn --preload), call gc.freeze(), and prefer native model runtimes whose weights live outside the Python heap
Linux with threads in the parent Do not fork at all (1.4); use forkserver/spawn plus shared memory or initializer
macOS or Windows fork is unsafe or absent; use spawn plus shared memory, mmap, or the initializer pattern

Re-initialise per-process state after a fork

A forked child inherits copies of everything in the parent: random-number state (every child then repeats the same "random" stream unless reseeded), locks, and open connections. A database connection or an LLM HTTP client created before the fork must not be reused in the child: parent and child would share one socket and interleave bytes on it. os.register_at_fork runs your hooks at the right moment (use after_in_child to reset or recreate per-process state; the library or initializer that owns the client is the better place to do it under spawn).

python
# f07_at_fork.py: os.register_at_fork re-initialises per-process state in a fork child.
import multiprocessing as mp
import os
import random

state = {"conn": "client-created-in-parent"}


def reset_in_child() -> None:
    state["conn"] = None                    # a connection made before fork must not be reused
    random.seed(os.getpid())                # otherwise every child repeats the same random stream


os.register_at_fork(after_in_child=reset_in_child)


def show() -> None:
    print("child sees conn:", state["conn"])


if __name__ == "__main__":
    p = mp.get_context("fork").Process(target=show)
    p.start()
    p.join()
    print("parent still has:", state["conn"])
Output · Python 3.14.61 line

Part 9: Process pools and big read-only data#

9.1 The problem#

You write a ProcessPoolExecutor job that scores documents against a big read-only structure: a tokenizer vocabulary, a model's lookup table, a set of banned phrases. The naive version passes the structure with every task:

python
# The anti-pattern: the whole vocabulary is pickled for EVERY task.
pool.map(score, [(doc, vocab) for doc in docs])

For each task Python pickles vocab, ships it, and unpickles it in the worker. A 3.5 MB vocabulary and a thousand documents means roughly 3.5 GB of pickling just to look up a thousand words. Plain pool.map(score, docs) with the structure as a module global does not work under spawn/forkserver: the worker does not have it (1.4).

9.2 Three ways, measured#

The cure is to deliver the data to each worker once, not to each task: through the pool's initializer, which runs once at the start of each worker process, or by attaching to shared memory there.

python
# e19_pool_initializer.py: a big READ-ONLY object and a process pool. Three ways to get it to the workers.
#   A. pass it with every task        -> pickled once per task
#   B. load it in `initializer`       -> built once per worker, tasks carry only small arguments
#   C. attach shared memory in the initializer -> one copy for the whole machine
import multiprocessing as mp
import pickle
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import shared_memory

VOCAB_SIZE = 200_000
_vocab: dict[str, int] | None = None                  # per-worker global, filled by an initializer
_shm: shared_memory.SharedMemory | None = None
LOADS = None                                          # a shared counter handed to the initializer


def build_vocab() -> dict[str, int]:
    return {f"token{i}": i for i in range(VOCAB_SIZE)}   # stands in for "load a tokenizer"


def init_private(loads) -> None:
    global _vocab
    _vocab = build_vocab()                             # runs ONCE in each worker process
    with loads.get_lock():
        loads.value += 1


def lookup_private(word: str) -> int:
    return _vocab.get(word, -1)                        # tasks carry a string, not a dictionary


def lookup_with_payload(args) -> int:
    word, vocab = args                                 # the whole dict was pickled for this task
    return vocab.get(word, -1)


def init_shared(name: str) -> None:
    global _shm
    _shm = shared_memory.SharedMemory(name=name)       # attach: no copy, no rebuild


def read_shared(index: int) -> int:
    # In real code: np.frombuffer(_shm.buf, dtype=np.float32) and index into it.
    return _shm.buf[index]


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    words = [f"token{i}" for i in range(0, 40_000, 5000)]      # 8 lookups

    # A: how heavy is one task's payload?
    vocab = build_vocab()
    per_task = len(pickle.dumps((words[0], vocab), protocol=5))
    print(f"A. bytes pickled PER TASK when the vocab travels with it: {per_task:,}")

    # B: the initializer pattern
    loads = ctx.Value("i", 0)
    with ProcessPoolExecutor(max_workers=3, mp_context=ctx,
                             initializer=init_private, initargs=(loads,)) as pool:
        results = list(pool.map(lookup_private, words))
    print("B. results:", results)
    # the pool starts workers on demand, so builds is between 1 and max_workers: never one per task
    print("B. vocab builds <= workers (3) < tasks (8):", 1 <= loads.value <= 3 < len(words))
    print("B. bytes pickled per task now:", len(pickle.dumps(words[0], protocol=5)))

    # C: shared memory (a flat byte table here: index -> value)
    shm = shared_memory.SharedMemory(create=True, size=256)
    try:
        for i in range(256):
            shm.buf[i] = (i * 7) % 256
        with ProcessPoolExecutor(max_workers=3, mp_context=ctx,
                                 initializer=init_shared, initargs=(shm.name,)) as pool:
            print("C. values:", list(pool.map(read_shared, [1, 2, 3, 100])))
    finally:
        shm.close()
        shm.unlink()
Output5 lines
A. bytes pickled PER TASK when the vocab travels with it: 3,558,475
B. results: [0, 5000, 10000, 15000, 20000, 25000, 30000, 35000]
B. vocab builds <= workers (3) < tasks (8): True
B. bytes pickled per task now: 21
C. values: [7, 14, 21, 188]
Way What travels per task What each worker holds Cost
A. Pass it with the task The whole structure (3.5 MB here) A temporary copy per task Pickle + copy per task; usually the slowest
B. initializer builds or loads it A short string (21 bytes) One private copy per worker Build/load time and RAM once per worker (so workers × size RAM, but no per-task cost)
C. initializer attaches shared memory An index (a few bytes) A mapping of the shared pages One copy for the whole machine; the best for large, numeric, read-only data

Observations from the output:

  • The pool reported at most as many vocabulary builds as workers and fewer than tasks: the initializer runs once per worker process, not once per task. (The pool starts workers on demand, so with few tasks you can see fewer builds than max_workers.)
  • The per-task payload dropped from megabytes to a couple of dozen bytes.
  • The shared-memory variant needs the data in a flat, typed form (bytes, floats, a record layout), not a Python dictionary. If your structure is a dict of strings, B is the honest choice (and consider whether a real database file is better).

Production details the example leaves out:

  • Initializer failures. If the initializer raises, the pool breaks: "all currently pending jobs will raise a BrokenProcessPool, as well as any attempt to submit more jobs". Make the initializer fail loudly and early (and log inside it).
  • Cleanup. Workers that attach shared memory in an initializer should close() it when they exit; the simplest approach is to let the owner unlink() after the pool shuts down, in a finally, as the example does.
  • Chunking. pool.map(fn, items, chunksize=N) sends tasks in batches of N; for many small items a bigger chunksize cuts the per-message overhead dramatically (the documentation notes it "can significantly improve performance compared to the default size of 1").
  • Memory growth and recycling. max_tasks_per_child=N (3.11+) replaces a worker after N tasks, which is a blunt but effective fix for workers that leak (see 01C.6). The documentation notes that setting it makes spawn the default start method for that pool and that it is incompatible with fork.
  • __main__ must be importable by workers, so ProcessPoolExecutor does not work in an interactive REPL or in a notebook cell that defines the worker function (01C.5 §5.1 shows a working pool).
  • Never call Future or Executor methods from inside a task submitted to a ProcessPoolExecutor: the documentation warns this results in deadlock.

Part 10: Pickle costs and protocol 5#

Deep-dive

10.1 What pickle costs#

Everything that crosses a multiprocessing boundary by Queue, Pipe.send, Process(args=...), pool tasks and pool results is pickled. Three costs add up:

Cost Why Remedy
CPU Pickle walks the object graph; a list of a million small objects is a million visits (a bytes or an array is one) Send flat buffers, not graphs of objects; send ids, not objects
Memory The data exists in the sender, as the pickle stream, and in the receiver (a transient 2-3x of the data) Out-of-band buffers (below); shared memory; chunk the work
Latency The consumer cannot start until the whole message has arrived and been rebuilt Smaller messages; stream results as they are ready; shared memory

Two more things to know. Return values pay the same tax in reverse: a task that returns a large array pickles it back through the result pipe, so a worker should write results into shared memory and return a small acknowledgement when output is big. And never unpickle data you did not produce: the pickle documentation warns that unpickling can "execute arbitrary code". Pickle between your own trusted processes is fine; pickle read from a shared block, a file or a socket that anyone else can write is a remote-code-execution hole (see Module 12).

10.2 Protocol 5 and out-of-band buffers (PEP 574)#

Pickle protocol 5 was added in Python 3.8 by PEP 574 and became the default protocol in Python 3.14 (protocol 4 was the default from 3.8 to 3.13, as the pickle documentation states). Its feature is out-of-band data: large buffers (anything exposing the buffer protocol: bytes, bytearray, array, a NumPy array's data) can be pulled out of the pickle stream and handed over separately, so the stream holds only a small marker, and the transport can move the buffer without an extra serialization copy.

python
# e15_pickle5.py: pickle protocol 5 can leave big buffers OUT of the byte stream (PEP 574).
import pickle

payload = bytearray(b"v" * 5_000_000)          # pretend: one big embedding block

# in-band (protocol 4 and the usual habit): the stream CONTAINS a full copy of the data
in_band = pickle.dumps(payload, protocol=4)
print("protocol 4 stream size:", len(in_band))

# out-of-band (protocol 5): wrap the data in a PickleBuffer; the buffer goes to buffer_callback
# and the stream keeps only a marker. (A plain bytearray is still pickled in-band.)
plain = pickle.dumps(payload, protocol=5)
print("protocol 5, plain bytearray, stream size:", len(plain))

message = {"batch": 7, "vectors": pickle.PickleBuffer(payload)}
buffers: list[pickle.PickleBuffer] = []
stream = pickle.dumps(message, protocol=5, buffer_callback=buffers.append)
print("protocol 5, PickleBuffer, stream size:", len(stream), "| out-of-band buffers:", len(buffers))
print("the buffer IS the sender's memory (no copy made):", buffers[0].raw().obj is payload)

# the receiver needs the small stream AND the buffers, in the same order
rebuilt = pickle.loads(stream, buffers=buffers)
print("rebuilt batch:", rebuilt["batch"], "| vectors type:", type(rebuilt["vectors"]).__name__)
print("receiver's view is still the same memory:", rebuilt["vectors"].raw().obj is payload)


# A class can opt in to rebuilding WITHOUT any copy (this is the pattern from the pickle docs):
class ZeroCopyBytes(bytearray):
    def __reduce_ex__(self, protocol: int):
        if protocol >= 5:
            return type(self)._rebuild, (pickle.PickleBuffer(self),), None
        return type(self)._rebuild, (bytearray(self),), None

    @classmethod
    def _rebuild(cls, obj):
        with memoryview(obj) as view:
            underlying = view.obj               # the object the buffer came from
        if type(underlying) is cls:
            return underlying                   # same object: no copy at all
        return cls(underlying)                  # anything else: one copy


zc = ZeroCopyBytes(b"abc")
bufs: list[pickle.PickleBuffer] = []
data = pickle.dumps(zc, protocol=5, buffer_callback=bufs.append)
print("zero-copy rebuild returned the same object:", pickle.loads(data, buffers=bufs) is zc)

# a buffer_callback needs protocol 5
try:
    pickle.dumps(payload, protocol=4, buffer_callback=buffers.append)
except ValueError as exc:
    print("ValueError:", exc)
print("pickle.DEFAULT_PROTOCOL on this Python:", pickle.DEFAULT_PROTOCOL)
Output9 lines
protocol 4 stream size: 5000056
protocol 5, plain bytearray, stream size: 5000013
protocol 5, PickleBuffer, stream size: 37 | out-of-band buffers: 1
the buffer IS the sender's memory (no copy made): True
rebuilt batch: 7 | vectors type: PickleBuffer
receiver's view is still the same memory: True
zero-copy rebuild returned the same object: True
ValueError: buffer_callback needs protocol >= 5
pickle.DEFAULT_PROTOCOL on this Python: 5

How to read it:

  • With protocol 4 the stream contained all five million bytes (5,000,056). A plain bytearray is still pickled in-band under protocol 5 (stream size 5,000,013): protocol 5 only helps when the data is wrapped in a PickleBuffer or inside a class whose __reduce_ex__ hands out a PickleBuffer. NumPy arrays and other libraries that adopted PEP 574 do this for you.
  • With a PickleBuffer, the stream was 37 bytes; the five million bytes went to buffer_callback as the original memory (buffers[0].raw().obj is payload): no copy at pickling time.
  • On load you pass the same buffers back, in order, with pickle.loads(stream, buffers=buffers).
  • The ZeroCopyBytes class is the pattern from the pickle documentation: in the same process the rebuild returns the very same object (no copy at all). Across a real boundary the receiver still gets one copy (the transport moves the bytes once), but not the extra stream copy on each side.
  • buffer_callback with protocol 4 or lower is an error.

Where does the buffer physically go? Between processes, it still has to be moved: protocol 5 removes the extra copies inside the serializer; it does not make a pipe free. The combination that gives a true zero-copy path is out-of-band pickling plus shared memory: the sender places the buffer in a SharedMemory block, the "pickle" carries the name, shape and dtype, and the receiver maps the block (some distributed-computing libraries are built around this idea; check their documentation for how). Plain multiprocessing does not do this for you; you build it with the pieces in Parts 4 and 5.


Part 11: Shared memory in AI workloads#

Deep-dive

11.1 An embedding matrix shared by search workers#

Brute-force similarity search is memory-bandwidth-bound and parallelizes by splitting the rows: each worker scores its slice and returns its best candidates. The matrix is large and read-only, which is the textbook shared-memory case. This version uses only the standard library (a 2-D memoryview cast) to show the shape of the code; with NumPy the inner loop becomes one matrix-vector product that releases the GIL (01C.5).

python
# e23_embedding_search.py: an embedding matrix in shared memory, searched by several worker processes.
# Stdlib only: memoryview.cast gives a typed, 2-D float32 view; NumPy would be np.ndarray(..., buffer=shm.buf).
import math
import multiprocessing as mp
import struct
from multiprocessing import shared_memory

ROWS, DIM, WORKERS = 6000, 8, 3


def vector_for(row: int) -> list[float]:
    # deterministic fake "embedding": a point on a spiral, unit length
    angle = row * 0.01
    v = [math.cos(angle), math.sin(angle)] + [0.1 * ((row + k) % 5) for k in range(DIM - 2)]
    norm = math.sqrt(sum(x * x for x in v))
    return [x / norm for x in v]


def search_slice(name: str, query: list[float], start: int, stop: int, out) -> None:
    shm = shared_memory.SharedMemory(name=name)
    try:
        # typed 2-D view over the shared bytes: no copy, nothing pickled but the arguments
        matrix = shm.buf[: ROWS * DIM * 4].cast("f", shape=[ROWS, DIM])
        best_row, best_score = -1, -2.0
        for r in range(start, stop):
            score = sum(matrix[r, c] * query[c] for c in range(DIM))
            if score > best_score:
                best_row, best_score = r, score
        matrix.release()                       # release the view before close(), or BufferError
        out.put((best_row, best_score))
    finally:
        shm.close()


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    shm = shared_memory.SharedMemory(create=True, size=ROWS * DIM * 4)
    try:
        for r in range(ROWS):
            struct.pack_into(f"<{DIM}f", shm.buf, r * DIM * 4, *vector_for(r))
        query = vector_for(4321)               # the nearest row to this query is row 4321 itself
        out = ctx.Queue()
        step = ROWS // WORKERS
        ps = [ctx.Process(target=search_slice, args=(shm.name, query, k * step, (k + 1) * step, out))
              for k in range(WORKERS)]
        for p in ps:
            p.start()
        winners = [out.get() for _ in ps]
        for p in ps:
            p.join()
        row, score = max(winners, key=lambda t: t[1])
        print("matrix bytes shared:", ROWS * DIM * 4, "| slices searched:", WORKERS)
        print("best row:", row, "| cosine ~", round(score, 4))
    finally:
        shm.close()
        shm.unlink()
Output2 lines
matrix bytes shared: 192000 | slices searched: 3
best row: 4321 | cosine ~ 1.0

What the structure shows:

  • The parent wrote the matrix once into shared memory. Each worker received only a name, a query vector and a row range (kilobytes), not the matrix.
  • Workers return (row, score), a tiny result. If the result were big, it would go into a second shared block, as in 4.3.
  • The finally blocks release() the view and close() the handle in the worker, and unlink() in the parent. Skipping matrix.release() before close() is the bug you will hit first.
  • The parent merges per-slice winners with max. A top-k search merges k winners per slice with a heap: the same shape.

How to size and decide. A million 1,024-dimensional float32 vectors is about 4 GB; as float16 or quantized int8, 2 GB or 1 GB (06.4 §4.7). Eight workers that each load their own copy need 32 GB of RAM; eight workers sharing one segment need 4 GB. That is the entire argument for this lesson in one line of arithmetic. In practice most teams use a vector database or an ANN library rather than a hand-written scan (06.5); you still meet shared memory inside them and whenever you build the pipeline around them (batch scoring, evaluation, offline re-ranking).

11.2 A tokenizer or vocabulary#

A tokenizer is usually a big structure of Python objects (a dict from strings to ids), which is the worst shape for sharing: it cannot live in shared memory as is, and after fork it gets copied as children touch it (8.2). Your options, from simplest:

  1. Load it once per worker in the pool initializer (Part 9, way B). Memory is workers × size, so this is fine for tens of megabytes and painful for gigabytes.
  2. Use a tokenizer implemented in native code that releases the GIL and use threads instead of processes: then there is only one copy and no IPC. Many modern tokenizer libraries are written in Rust or C for exactly this reason; check your library's documentation for whether its encode calls release the GIL, and measure with the harness in 01C.5 §9.1.
  3. Encode the vocabulary in a flat form (a sorted byte table or a memory-mapped file) that all workers map. This is real engineering work: choose it only if the vocabulary is huge and option 2 is unavailable.

11.3 Memory-mapped vector files and indexes#

The most common production use of mmap in AI is invisible: libraries map index and weight files. ANN indexes such as Annoy are documented to produce static files that every process which loads them can memory-map (06.4 §7.1); NumPy's .npy format supports memory-mapped loading, and Module 06 lists it among its storage formats (06.2 §9.2); and the safetensors weight format memory-maps tensors without executing code on load (12.7 §4.1). The pattern in 6.3 is what they do under the hood. Illustrative NumPy:

python
# Illustrative: requires numpy (not run in this lesson).
import numpy as np

# One file on disk, produced once by the ingestion job:
#   np.save("embeddings.npy", matrix)            # float32, shape (rows, dim)
# Every worker (any process, any start method) maps it read-only: no load, no copy.
matrix = np.load("embeddings.npy", mmap_mode="r")
scores = matrix[1_000:2_000] @ query            # only the touched pages are read from disk

Ops notes: warm the cache at start-up if latency matters (6.3); keep mapped files immutable and swap them by atomic rename; and remember that "memory used" for such a service is mostly page cache, which the operating system can reclaim, so monitor it as such.

11.4 DataLoader-style workers#

Machine-learning data loaders (PyTorch's DataLoader(num_workers=N) is the well-known one) run worker processes that prepare batches and hand tensors back, and they move tensors between processes through shared memory rather than pickling the data. You will meet this if you do any local model work. Two practical consequences follow from this lesson. First, a container with a small /dev/shm makes such loaders fail in confusing ways (4.7). Second, workers that hold large Python objects (a list of file paths, a metadata dict) pay the copy-on-write cost of Part 8, so keep per-sample metadata in compact arrays. This lesson does not teach PyTorch; check its documentation for the details of its multiprocessing behaviour and start methods.

11.5 Web-service workers and duplicated state#

A FastAPI or Gunicorn service with several worker processes gives each worker its own memory, so every process-local cache, counter, rate limiter and model copy is multiplied by the worker count. 11C.1 §2.13 makes the same point: "per-process state multiplies". The choices in order of effort: keep per-worker state and accept it (a per-worker cache is fine); put shared mutable state in Redis or a database (the right answer once you scale beyond one machine anyway); share a read-only matrix or file by mmap/SharedMemory; or use fewer processes with more threads or asyncio, which the I/O-bound shape of an LLM gateway usually allows (11C.1 §5.2).

11.6 If you can use threads: free-threaded builds#

All of this exists because processes are the way to get parallelism and isolation on the default build. On the free-threaded build (01C.5 Part 7), threads run Python code in parallel and share memory by default, so for compute-bound work whose dependencies support it, threads can replace worker processes and the whole machinery of this lesson. The trade-offs are the ones in 01C.5: ecosystem support, a single-thread cost, and the full return of every race condition in 01C.3, because shared memory with parallelism needs locks. Processes plus shared memory remain the right answer when you want crash isolation, run untrusted code, or cannot yet use a free-threaded build.


Part 12: Cleanup and crash safety#

12.1 The rules#

  1. One owner creates; one owner unlinks. Decide in the design which process is the owner. Everyone else attaches, close()s and never unlinks.
  2. Every segment is created inside try/finally (or a context manager) that closes and unlinks. Cleanup must run on exceptions, not just the happy path.
  3. Convert signals into exceptions. A SIGTERM (what kill, systemd, Docker and Kubernetes send) terminates Python without running finally blocks by default. Install a handler that raises SystemExit so cleanup runs. Ctrl+C already raises KeyboardInterrupt.
  4. Use unique, versioned names, or let Python choose. A fixed name collides after a crash left a stale segment; a unique name never does. If you do use a fixed name, handle FileExistsError deliberately (attach and verify, or unlink the stale one if you own it).
  5. Release views before close(); delete NumPy arrays first.
  6. Prefer SharedMemoryManager when one process owns many segments and you want a guaranteed single cleanup point.
  7. Watch for the resource-tracker warning in logs and CI: any leaked shared_memory objects line is a bug to fix.

A reusable pattern, tested against a real SIGTERM:

python
# e24_owned_segment.py: one owner creates and unlinks; everyone else attaches and closes.
# Handles Ctrl+C and `kill` (SIGTERM) by turning them into normal exceptions, so `finally` runs.
import contextlib
import os
import signal
import subprocess
import sys
import time
from multiprocessing import shared_memory


@contextlib.contextmanager
def owned_segment(size: int, name: str | None = None):
    """Create a segment, give it to the caller, and ALWAYS close + unlink it."""
    def _raise_exit(signum, frame):          # SIGTERM kills Python without running `finally`; this fixes it
        raise SystemExit(128 + signum)

    previous = signal.signal(signal.SIGTERM, _raise_exit)
    shm = shared_memory.SharedMemory(name=name, create=True, size=size)
    try:
        yield shm
    finally:
        shm.close()
        with contextlib.suppress(FileNotFoundError):    # already removed (e.g. by another tracker)
            shm.unlink()
        signal.signal(signal.SIGTERM, previous)


@contextlib.contextmanager
def attached_segment(name: str):
    """Attach to someone else's segment; only close, never unlink."""
    # Not started by multiprocessing from the owner => it would get its OWN resource tracker, which
    # would delete the segment when we exit. track=False (3.13+) prevents that.
    extra = {"track": False} if sys.version_info >= (3, 13) else {}
    shm = shared_memory.SharedMemory(name=name, **extra)
    try:
        yield shm
    finally:
        shm.close()


def exists(name: str) -> bool:
    try:
        probe = shared_memory.SharedMemory(name=name, track=False)
    except FileNotFoundError:
        return False
    probe.close()
    return True


OWNER = """
import sys, time
from e24_owned_segment import owned_segment
with owned_segment(64, name="lesson07_owned") as shm:
    print("created", flush=True)
    time.sleep(30)
"""

if __name__ == "__main__":
    here = os.path.dirname(os.path.abspath(__file__))
    child = subprocess.Popen([sys.executable, "-c", OWNER], cwd=here, stdout=subprocess.PIPE, text=True,
                             stderr=subprocess.DEVNULL)
    assert child.stdout.readline().strip() == "created"
    print("segment exists while the owner runs:", exists("lesson07_owned"))
    with attached_segment("lesson07_owned") as seg:
        seg.buf[0] = 7
        print("attached, wrote a byte, closing without unlink")
    child.send_signal(signal.SIGTERM)                 # like `kill <pid>` or a container stop
    child.wait(timeout=10)
    time.sleep(0.2)
    print("owner exit code:", child.returncode, "(143 = 128 + SIGTERM)")
    print("segment exists after SIGTERM:", exists("lesson07_owned"))
Output4 lines
segment exists while the owner runs: True
attached, wrote a byte, closing without unlink
owner exit code: 143 (143 = 128 + SIGTERM)
segment exists after SIGTERM: False

What the run demonstrates: the owner exited with code 143 (128 plus signal 15, the shell convention for "killed by SIGTERM") and the segment was gone afterwards, because the handler turned the signal into SystemExit and the finally block ran. The attacher used track=False so its exit could not delete the owner's segment (4.5). A kill -9 (SIGKILL) cannot be caught: nothing runs, and only the resource tracker (when the process tree shares one) or a reboot reclaims the segment. That is why the safety net exists, and why unique names matter.

12.2 When things go wrong anyway#

Symptom Likely cause What to do
FileExistsError on create=True A stale segment with that name from a crash Use unique names; or attach with create=False and unlink() it if you own the name
resource_tracker: ... leaked shared_memory objects at exit unlink() was never called on a normal exit Fix the code path; do not silence the warning
Segment vanishes under a running reader A separate Python process attached with track=True and exited, and its own tracker unlinked it track=False for unrelated attachers (3.13+), 4.5
OSError/SIGBUS when creating or touching a big segment in a container /dev/shm too small Raise the container's shared-memory size; test with the real size
BufferError: cannot close exported pointers exist A memoryview or NumPy array still alive release() / del before close()
ValueError: bytes/str item exceeds available storage A ShareableList slot too small Size slots for the longest value (4.6)
A worker hangs forever A dead peer left a multiprocessing.Lock held, or a queue nobody reads acquire(timeout=...); drain queues before join() (01C.4)
Memory is full but no process seems to use it Orphaned /dev/shm segments (Linux) List /dev/shm, identify yours by prefix, delete after confirming nothing uses them

Reference
# What you see Cause Fix
1 Works on Linux (before 3.14) and fails on macOS or Windows: AttributeError/NameError in workers Code relied on fork inheriting globals set after import Pass data as arguments or build it in an initializer (1.4)
2 RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase No if __name__ == "__main__": guard under spawn Add the guard (1.4)
3 PicklingError / Can't pickle <function <lambda>> when starting a process or submitting a task A lambda, nested function or open handle as target or argument Module-level functions; pass paths and names, not handles
4 Parallel job slower than the loop Tasks carry big payloads; pickle dominates (1.3) Shared memory, initializer, bigger chunksize
5 Child hangs the first time it logs (Linux, fork start method) fork copied a lock held by another thread Do not fork with threads; use spawn/forkserver (01C.4)
6 Shared counter total is wrong, intermittently += on a raw shared value without a lock (7.2) Lock the read-modify-write, or partition the writes
7 A shared integer wrapped to a negative number 32-bit 'i' typecode Use 'q'; know the range (3.1)
8 Nested manager.dict()["k"].append(...) has no effect The proxy returned a copy (2.4) Reassign, or use manager.list()
9 leaked shared_memory objects warning at exit unlink() skipped (4.5) Owner unlinks in finally, or use SharedMemoryManager
10 The segment disappears while workers still use it An unrelated process attached with track=True and exited track=False (3.13+)
11 BufferError: cannot close exported pointers exist A live memoryview / array Release views first (5.1)
12 Container crashes creating or using a big segment Small /dev/shm (4.7) Raise the shared-memory size
13 RAM grows to workers × size after fork Reference counts dirtied copy-on-write pages (8.2) Flat buffers; gc.freeze(); or shared memory
14 Sums of per-process RSS exceed machine RAM Shared pages counted once per process Use PSS or the system "shared" figure
15 Reader sees a half-written table In-place rebuild without coordination (7.5) Write a new block, publish by name; or lock
16 The whole pool hangs on shutdown A queue nobody drained, or a lock held by a dead worker get(timeout), drain before join, acquire(timeout)
17 ProcessPoolExecutor raises BrokenProcessPool right away The initializer raised, or a worker was killed (OOM) Log in the initializer; check the kernel's OOM kills
18 RuntimeError: Lock objects should only be shared between processes through inheritance A Lock, Queue or Value passed as a pool task argument (7.2) initializer=/initargs=, or a Manager() proxy
19 Memory grows without limit while consumers are busy An unbounded Queue (2.3) Queue(maxsize=...), put(timeout=) and handle queue.Full
20 A producer process never exits although its work is done Items still in the queue's feeder buffer, nobody reading (2.3) Drain before join(); cancel_join_thread() only if losing the items is acceptable

Common misconceptions#

Misconception Reality
"Processes can't share memory" They can, by explicit arrangement: SharedMemory, mmap, Value/Array, and copy-on-write after fork. They just do not share by default (Part 1)
"manager.dict() is shared memory" It is a server process and a proxy: every operation is a message, hundreds of times slower than a dict (2.4)
"close() frees the shared memory" close() ends your handle; unlink() removes the segment, once, by one owner (4.2)
"Shared memory is thread-safe and process-safe" It is raw bytes: no locks, no atomicity. You supply synchronization (Part 7)
"fork is always the fast, safe choice" It is fast, but unsafe with threads, absent on Windows, unreliable on macOS, and no longer the default anywhere since 3.14 (1.5)
"Copy-on-write means forked workers cost nothing" Python reference counts write to objects on read, so the pages get copied anyway (8.2)
"A Queue is a free way to move big arrays" Every item is pickled and copied; send names and ids, not data (2.3)
"SharedMemory(size=n) gives exactly n bytes" It gives at least n; macOS rounded 100 to 16,384 here (4.2)
"mmap loads the file into RAM" It maps it; pages load on first touch and live in the page cache, shared by all processes (6.1)
"Protocol 5 makes pickling zero-copy" It lets big buffers travel out-of-band; a plain bytearray still pickles in-band, and a pipe still moves the bytes (10.2)
"Python 3.14 changed fork to spawn on Linux" It changed to forkserver on Linux; spawn was already the default on macOS and Windows (1.5)
"A process crash cleans up its shared memory" On POSIX nothing does, except the resource tracker's safety net; a SIGKILL'd tree can leave segments behind (12.1)

Key takeaways#

  1. Processes have separate address spaces. Anything that crosses the boundary is copied (pickled) unless you deliberately map shared pages.
  2. The copy tax is real and scales with size and with the number of workers. Pass names and ids through queues; put big data in shared memory, an mmaped file, or the pool initializer.
  3. Know your start method. fork, spawn, forkserver: different inheritance, different safety. Linux moved to forkserver in 3.14; macOS and Windows use spawn. Always use the __main__ guard and create primitives from one explicit context.
  4. Value/Array are for small numeric state; SharedMemory for bulk bytes; mmap for files; a Manager for convenience at low rates. Pick by size, by who must attach, and by whether it must survive a crash.
  5. Everyone closes, one unlinks. Create in try/finally, convert SIGTERM into an exception, use unique names, and treat the resource-tracker warning as a bug.
  6. Unrelated Python processes must attach with track=False (3.13+), or their own tracker will delete the segment.
  7. Zero-copy is memoryview, struct.unpack_from, typed cast and NumPy over a buffer: and every view must be released before close().
  8. Shared memory has no locking. Partition the writes, merge privately, use a single writer and publish new blocks by name; use real locks (with timeouts) when you must share writes; a lock held by a dead process stays held.
  9. Copy-on-write is defeated by reference counts for Python objects, not for flat buffers. Big read-only data belongs in a flat buffer.
  10. Match the tool to the data. Small messages: queue. Big read-only data: shared memory, mmap or initializer. Cross-machine or durable state: a database or Redis. If your stack supports free-threaded Python, threads may remove the need altogether.

Where you'll use this in the AI path#

Where What you use from this lesson
01B.4 §8.6, CPU-bound work and multiprocessing The one-paragraph version of processes; this lesson explains what crosses the boundary and how to avoid the copy
03.9 §4.8, threads for code that isn't async The case where you do not need processes: waiting work shares memory in threads
05.2 §10.3, scale and robustness (PDF parsing) Bulk parsing shards across processes: send paths through the queue, results through files or shared blocks
05.9 §1.3, checkpointing, resumability and backpressure Ingestion workers need crash-safe hand-offs: files and atomic renames, not shared memory that dies with the process
06.2 §9.2, storage formats and 06.4 §7.1, Annoy and mmap Memory-mapped embeddings and indexes (6.3)
06.4 §4.7, compression ratios and index memory Why a shared matrix's size, and therefore its dtype, decides whether sharing is needed
11C.1 §2.13, running it: uvicorn, gunicorn, workers Per-process state multiplies with workers (11.5)
12.7 §4.1, file formats decide your risk Why you never unpickle untrusted bytes (10.1) and why memory-mapped weight formats are safer
01C.6, Python Memory Management Reference counts, RSS versus PSS, and why a forked heap gets copied

Terms introduced in this lesson#

Term Meaning
Inter-process communication (IPC) Any mechanism for separate processes to exchange data: pipes, queues, sockets, files, shared memory
Address space The private map from a process's memory addresses to physical RAM
Copy tax The CPU time and extra memory spent serializing and copying data to hand it to another process
Start method How multiprocessing creates a child: fork, spawn or forkserver
fork Clone the parent, including memory and locks; fast, unsafe with threads
spawn Start a fresh interpreter that re-imports the main module; the default on Windows and macOS
forkserver Fork workers from a clean server process; the default on Linux since Python 3.14
Pipe / Connection A two-ended channel between two processes
Sentinel A special message (such as None) that tells a consumer to stop
Manager / proxy A server process that owns objects, and the stand-ins other processes use; every call is a message
Shared memory A block of RAM mapped into the address spaces of several processes
SharedMemory The standard-library class for a named shared block (multiprocessing.shared_memory, 3.8+)
ShareableList A fixed-length, typed list stored in a shared block
SharedMemoryManager A manager that owns shared blocks and unlinks them all when it shuts down
close() versus unlink() close() releases one process's handle; unlink() removes the segment's name, once
Resource tracker A helper process that unlinks shared-memory segments left registered at exit, and warns
track The SharedMemory parameter (3.13+) that controls resource-tracker registration
mmap Map a file or anonymous memory into the address space; reads and writes go to the page cache
Page cache Kernel-managed RAM that holds file pages, shared by every process that reads them
MAP_SHARED / MAP_PRIVATE Whether writes to a mapping are visible to others (and the file) or private copy-on-write
memoryview A zero-copy window onto another object's bytes
Zero-copy Passing or slicing data without duplicating it in memory
struct The standard module that packs and unpacks values to bytes using format strings
Copy-on-write (CoW) Sharing pages until one side writes, then copying only that page
Initializer A function a ProcessPoolExecutor runs once per worker at start-up
Out-of-band buffer Pickle protocol 5 feature that sends large buffers outside the pickle stream (PEP 574)
File lock An operating-system lock on a file that coordinates unrelated programs (fcntl.flock on Unix)

Exercises#

Each exercise uses the standard library only. Run the code, then open the solution. Outputs shown were produced with Python 3.14.6 on macOS unless labelled illustrative.

Exercise 1: Which start method is yours?#

Print your Python version, platform, default start method and the available methods. Then say which of the three the default is on Linux with Python 3.12, and with Python 3.14.

Solution
python
# ex01_default_method.py: which start method will your code get, and which exist here?
import multiprocessing as mp
import sys

if __name__ == "__main__":
    print("python:", sys.version.split()[0], "| platform:", sys.platform)
    print("default start method:", mp.get_start_method())
    print("available:", sorted(mp.get_all_start_methods()))
Example output · illustrative3 lines
python: 3.14.6 | platform: darwin
default start method: spawn
available: ['fork', 'forkserver', 'spawn']

On Linux with Python 3.12 the default is fork; with 3.14 it is forkserver. On macOS and Windows it is spawn in both (macOS since Python 3.8).

Exercise 2: Size a shared vector table#

You will store 50,000 chunks. Each row is an 8-byte chunk id followed by a 768-dimension float32 vector; the block starts with a 32-byte header (magic, version, dtype, rows, dim, generation). Compute the row size, the total size in MiB, and the byte offset of the last row. Why use < in the format?

Solution
python
# ex02_layout_size.py: size a shared block for a vector table: 32-byte header + rows of (id, vector).
import struct

HEADER = struct.Struct("<4sHHqqq")          # magic, version, dtype, rows, dim, generation
DIM, ROWS = 768, 50_000
ROW = struct.Struct(f"<q{DIM}f")            # int64 chunk id + 768 float32
print("header bytes:", HEADER.size)
print("row bytes:", ROW.size)
total = HEADER.size + ROWS * ROW.size
print("total bytes:", total, "=", round(total / 1024**2, 1), "MiB")
print("row 49,999 starts at offset:", HEADER.size + 49_999 * ROW.size)
Output4 lines
header bytes: 32
row bytes: 3080
total bytes: 154000032 = 146.9 MiB
row 49,999 starts at offset: 153996952

< fixes little-endian byte order and no alignment padding, so the sizes are exactly what you computed on paper and are the same on every platform; without it struct would use native sizes and alignment. About 147 MiB is what each worker would copy if you pickled it, and what the whole machine uses once if you share it. Row i starts at 32 + i * 3080: constant-time access.

Exercise 3: How big is a ShareableList slot?#

A status board is created with the placeholder "idle". Workers later write "processing doc 12" (17 characters). Will it fit? Find out empirically for placeholders of 4, 8, 15 and 16 characters.

Solution
python
# ex03_slot_capacity.py: how long a string fits into a ShareableList slot?
from multiprocessing.managers import SharedMemoryManager

if __name__ == "__main__":                      # the manager starts a process: the guard is required
    with SharedMemoryManager() as smm:
        for seed in ("idle", "idle".ljust(8), "idle".ljust(15), "idle".ljust(16)):
            board = smm.ShareableList([seed])
            longest = 0
            for n in range(1, 41):              # grow the replacement until the slot refuses it
                try:
                    board[0] = "x" * n
                    longest = n
                except ValueError:
                    break
            print(f"created from {len(seed):>2} chars -> format {board.format} -> longest that fits: {longest}")
            board.shm.close()
Output4 lines
created from  4 chars -> format 8s -> longest that fits: 8
created from  8 chars -> format 16s -> longest that fits: 16
created from 15 chars -> format 16s -> longest that fits: 16
created from 16 chars -> format 24s -> longest that fits: 24

The slot size is the initial value's encoded length rounded up to the next multiple of 8 that is strictly greater than the length (4 became 8, 8 became 16, 15 became 16, 16 became 24). A 4-character placeholder gives an 8-byte slot, so the 17-character message raises ValueError. Create the list with placeholders as long as the longest value you will ever store (here: "x" * 32 or more), and count bytes, not characters, for non-ASCII text. The rounding rule is what this run observed on 3.14.6, not something the documentation promises: it is an implementation detail, so size slots generously rather than to the byte.

Exercise 4: Close the leak#

A function creates a segment, does some work and raises before it reaches unlink(). Rewrite it so the segment is always removed, and prove it.

Solution
python
# ex04_segment_guard.py: the leak from e09, fixed with try/finally, and proof that nothing is left.
from multiprocessing import shared_memory

name = "lesson07_ex04"
shm = shared_memory.SharedMemory(name=name, create=True, size=1024)
try:
    shm.buf[:4] = b"data"
    raise RuntimeError("worker crashed halfway")        # simulate a failure after allocation
except RuntimeError as exc:
    print("handled:", exc)
finally:
    shm.close()
    shm.unlink()

try:
    shared_memory.SharedMemory(name=name)
except FileNotFoundError:
    print("segment gone: no leak, no resource-tracker warning")
Output2 lines
handled: worker crashed halfway
segment gone: no leak, no resource-tracker warning

try/finally runs on the exception path as well as on success, so close() and unlink() always happen and the resource tracker has nothing to warn about. A context manager that wraps this (12.1) removes the chance of forgetting.

Exercise 5: Checksum windows without copies#

Compute a CRC-32 of a 1 MiB buffer in four 256 KiB windows without creating any intermediate bytes objects, and show that chaining the windows gives the same checksum as hashing the whole buffer at once.

Solution
python
# ex05_crc_windows.py: checksum a 1 MiB buffer in 256 KiB windows WITHOUT copying any window.
import zlib

data = bytes(range(256)) * 4096                          # 1 MiB, deterministic
view = memoryview(data)
window = 256 * 1024
crcs = [zlib.crc32(view[i:i + window]) for i in range(0, len(view), window)]   # slices of a view: no copies
print("windows:", len(crcs))
print("first crc:", hex(crcs[0]))
# chaining the running value over all windows equals one pass over the whole buffer:
running = 0
for i in range(0, len(view), window):
    running = zlib.crc32(view[i:i + window], running)
print("chained equals whole:", running == zlib.crc32(data))
Output3 lines
windows: 4
first crc: 0xc790bff6
chained equals whole: True

view[i:i + window] makes a view, not a copy, and zlib.crc32 accepts any buffer. Its second argument is the running checksum, so the windows chain. The same technique lets a worker verify a segment it was handed, window by window, without allocating.

Exercise 6: Make a message out-of-band#

A job message is {"job": 42, "vectors": <1 MB float32 array>}. Show how large the pickle is in-band and out-of-band, and confirm the receiver's buffer is the sender's memory.

Solution
python
# ex06_oob_message.py: a job message with a big array: how large is the pickle stream with and without PickleBuffer?
import pickle

import array

vectors = array.array("f", [0.25] * 250_000)              # 1,000,000 bytes of float32

plain = pickle.dumps({"job": 42, "vectors": vectors}, protocol=5)
print("plain stream bytes >= 1,000,000:", len(plain) >= 1_000_000)

parts: list[pickle.PickleBuffer] = []
oob = pickle.dumps({"job": 42, "vectors": pickle.PickleBuffer(vectors)}, protocol=5, buffer_callback=parts.append)
print("out-of-band stream bytes < 100:", len(oob) < 100, "| buffers:", len(parts), "| buffer bytes:", parts[0].raw().nbytes)
back = pickle.loads(oob, buffers=parts)
print("job:", back["job"], "| vectors are the sender's memory:", back["vectors"].raw().obj is vectors)
Output3 lines
plain stream bytes >= 1,000,000: True
out-of-band stream bytes < 100: True | buffers: 1 | buffer bytes: 1000000
job: 42 | vectors are the sender's memory: True

Wrapping the array in a PickleBuffer moves its bytes into buffer_callback; the stream shrinks to a few dozen bytes. Across a real process boundary you still need to transport the buffers (a pipe with send_bytes, or shared memory); the saving is the serializer's extra copies.

Exercise 7: A shared word-length histogram#

Three workers each take every third document and count word lengths (1 to 7, with 8 meaning "8 or more"). Combine into one shared array without losing counts, and without taking the lock once per word.

Solution
python
# ex07_histogram.py: three workers build a word-length histogram into ONE shared array, safely.
import multiprocessing as mp

DOCS = [
    "the printer is on fire",
    "cannot log in to my account",
    "please refund the duplicate invoice",
    "app crashes when I upload a pdf",
    "thanks",
    "where is my parcel",
]


def count_lengths(hist, lock, docs: list[str]) -> None:
    local = [0] * len(hist)                        # count privately first: no lock traffic per word
    for doc in docs:
        for word in doc.split():
            local[min(len(word), len(hist) - 1)] += 1      # last bucket = "that long or longer"
    with lock:                                     # ONE short critical section per worker
        for i, n in enumerate(local):
            hist[i] += n


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    hist = ctx.Array("q", 9, lock=False)           # raw array: we bring our own lock
    lock = ctx.Lock()
    ps = [ctx.Process(target=count_lengths, args=(hist, lock, DOCS[i::3])) for i in range(3)]
    for p in ps:
        p.start()
    for p in ps:
        p.join()
    serial = [0] * 9
    for doc in DOCS:
        for word in doc.split():
            serial[min(len(word), 8)] += 1
    print("histogram:", list(hist))
    print("matches serial count:", list(hist) == serial)
Output2 lines
histogram: [0, 2, 7, 5, 2, 1, 6, 4, 1]
matches serial count: True

Each worker counts into a private list (no contention at all), then takes the shared lock once to add its totals into the raw array. The result equals the serial count. This is the "private first, merge once" pattern from 7.3: the lock is held for nine additions per worker instead of one per word.

Exercise 8: Fix the manager#

A worker appends to a list stored inside a manager.dict() and nothing happens. Show the bug and two fixes.

Solution
python
# ex08_manager_fix.py: nested mutation through a Manager proxy: the bug and two fixes.
import multiprocessing as mp


def broken(shared) -> None:
    shared["inbox"].append("ticket-1")                 # mutates a temporary copy: lost


def fix_reassign(shared) -> None:
    items = shared["inbox"]                            # copy out
    items.append("ticket-2")                           # change the copy
    shared["inbox"] = items                            # copy back (still needs a lock if many writers)


def fix_proxy(inbox) -> None:
    inbox.append("ticket-3")                           # a ListProxy: append is a message to the server


if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    with ctx.Manager() as m:
        shared = m.dict(inbox=[])
        proxy_list = m.list()
        for target, arg in ((broken, shared), (fix_reassign, shared), (fix_proxy, proxy_list)):
            p = ctx.Process(target=target, args=(arg,))
            p.start()
            p.join()
        print("dict['inbox'] after broken + fix_reassign:", shared["inbox"])
        print("manager.list() after fix_proxy:", list(proxy_list))
Output2 lines
dict['inbox'] after broken + fix_reassign: ['ticket-2']
manager.list() after fix_proxy: ['ticket-3']

shared["inbox"] returns a pickled copy of the list, so broken modified a temporary. fix_reassign copies out, changes, and assigns back (use a lock if several processes do this). fix_proxy creates the list as its own manager proxy, so append is a message to the server. Both work; the proxy is simpler, the reassignment avoids a second manager object.

Exercise 9: Search a big log without loading it#

Create a 4.6 MB log file with a single ERROR line near the end. Find it, print the line and count the lines after it, without reading the file into a string.

Solution
python
# ex09_mmap_find.py: find a marker in a large file without reading the file into memory.
import mmap
import os
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "log.txt")
    with open(path, "wb") as f:
        for i in range(200_000):
            f.write(b"INFO request %06d ok\n" % i)
        f.write(b"ERROR request 999999 failed\n")
        f.write(b"INFO request 000000 ok\n")
    print("file bytes:", os.path.getsize(path))
    with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
        pos = mm.find(b"ERROR")                     # a C-level search over the mapped pages
        mm.seek(pos)
        print("first ERROR at offset:", pos)
        print("that line:", mm.readline().decode().strip())
        print("lines after it:", mm.read().count(b"\n"))
Output4 lines
file bytes: 4600051
first ERROR at offset: 4600000
that line: ERROR request 999999 failed
lines after it: 1

mm.find scans the mapped pages in C; seek and readline then read just that line. For a file larger than RAM this still works, because pages are loaded on demand and evicted by the kernel.

Exercise 10: Choose the mechanism#

For each case, pick the best tool and say why: (a) a supervisor sends "stop" to one worker; (b) 16 workers all read a 6 GB read-only float32 file; (c) workers share a progress counter updated once per document; (d) a 2 MB lookup dict, 8 pool workers; (e) a result cache shared by two machines; (f) workers write 50,000 float scores, one per index.

Solution

(a) A Pipe or an Event: two parties, a few bytes. (b) mmap read-only on the file: no loading, one copy in the page cache (6.3). (c) A Value('q') with its lock (or one slot per worker in an Array and sum at the end, with no lock). (d) The pool initializer: 16 MB across 8 workers is cheap, and a dict of Python objects cannot live in shared memory as is (9.2). (e) Redis or a database: shared memory cannot cross machines. (f) A RawArray('d', 50_000) or a SharedMemory block with one slot per index: disjoint writes need no lock (7.3).

Exercise 11: Why does this hang?#

python
# A parent starts 3 workers, each puts 100,000 results on a result queue, then the parent
# calls join() on all three workers BEFORE reading the queue. It hangs.

Explain, and give the fix.

Solution

A process that has put items on a multiprocessing.Queue does not exit until its feeder thread has flushed them into the pipe, and the pipe has a finite buffer: with 300,000 items nobody is reading, the pipe fills, the workers block inside their exit, and join() waits for them: a circular wait (01C.4). The fix is to drain the result queue before joining (read exactly as many results as you expect, or until each worker's sentinel arrives), as the queue half of 2.2 does (results.get() six times, then join()).


Check yourself#

  1. Why can't two processes see each other's variables, and why can two threads?
  2. Name the three start methods and say what each inherits from the parent.
  3. What is the default start method on Linux in Python 3.14, on macOS, and on Windows?
  4. Give two ways a script that works under fork can fail under spawn.
  5. Why is putting a 64 MiB array on a multiprocessing.Queue slower than handing over a shared-memory name?
  6. What is the difference between shm.close() and shm.unlink(), and who should call each?
  7. What does the resource tracker do, and what does the warning "leaked shared_memory objects" tell you?
  8. When must you attach with track=False, and from which Python version?
  9. Why does manager.dict()["k"].append(x) appear to do nothing?
  10. Name three ways to avoid taking a lock when several processes write shared memory.
  11. What happens to a multiprocessing.Lock held by a process that is killed?
  12. Why does fork not give you free sharing of a big Python list, but does for a big array?
  13. What does mmap share between processes, and what does ACCESS_COPY do?
  14. What does pickle protocol 5 add, and when did it become the default?
  15. Why does the pool initializer pattern beat passing the data with every task?

Further resources#


← 01C.6: Python Memory Management | Module 01C overview | Module 02: How LLMs Work →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close