Lesson 39 of 52Concurrency and performance
Processes, Subinterpreters and Free-Threaded Python
Use every CPU core from Python: process pools, start methods, pickling costs, subinterpreters in 3.14 and the free-threaded build, with real timings.
A reporting job scores two million rows of orders in pure Python. It takes forty minutes on a 16-core server, and top shows one core at 100% and fifteen doing nothing. You learned in Threads and the GIL that a thread pool will not help here, because the work is Python bytecode. This lesson covers the tools that do help: separate processes, subinterpreters (new in 3.14) and the free-threaded build. They all run Python on several cores, and each has its own costs. Picking the wrong one, or using the right one carelessly, is how a "parallel" job ends up slower than the loop it replaced.
ProcessPoolExecutor for CPU-bound work
A process has its own memory and its own interpreter, so it has its own GIL. Four worker processes can run Python on four cores at once. The easiest way in is concurrent.futures.ProcessPoolExecutor. It has the same API as the thread pool from the last lesson, so swapping one for the other is a one-word change.
Here is one CPU-bound function, a prime count, run eight times in four different ways. This ran on CPython 3.14 on an 18-core Mac, with the default build:
import multiprocessing as mp
import sys
import time
from concurrent.futures import (
InterpreterPoolExecutor,
ProcessPoolExecutor,
ThreadPoolExecutor,
)
def count_primes(limit: int) -> int:
count = 0
for n in range(2, limit):
if all(n % d for d in range(2, int(n ** 0.5) + 1)):
count += 1
return count
def bench(label, executor_cls, workers=4):
start = time.perf_counter()
with executor_cls(max_workers=workers) as pool:
results = list(pool.map(count_primes, [200_000] * 8))
print(f"{label:<22} {time.perf_counter() - start:5.2f}s {results[0]} primes each")
if __name__ == "__main__":
print(sys.version.split()[0], "| start method:", mp.get_start_method())
start = time.perf_counter()
for _ in range(8):
count_primes(200_000)
print(f"{'plain loop':<22} {time.perf_counter() - start:5.2f}s")
bench("4 threads", ThreadPoolExecutor)
bench("4 processes", ProcessPoolExecutor)
bench("4 interpreters", InterpreterPoolExecutor)3.14.4 | start method: spawn
plain loop 1.10s
4 threads 1.10s 17984 primes each
4 processes 0.34s 17984 primes each
4 interpreters 0.30s 17984 primes eachThreads: no gain. Processes and subinterpreters: about 3.3 times faster on four workers. It is not a full 4x because starting workers and moving data cost something. The older multiprocessing.Pool does the same job with pool.map, imap_unordered and apply_async. Prefer the executor API in new code: it matches the thread pool, and its futures re-raise worker exceptions in the same way.
The pool starts worker processes. With spawn, each one is a fresh Python that imports your main module first.
The main guard is not optional
On macOS and Windows, and now on Linux too, worker processes do not inherit your running program. They start a new interpreter and import your main module to find the function. If the code that creates the pool is at module level, each worker would create its own pool while it imports, and so on. Python stops this with an error. Here is a script with no guard, run on 3.14:
from concurrent.futures import ProcessPoolExecutor
def double(x):
return x * 2
with ProcessPoolExecutor(max_workers=2) as pool:
print(list(pool.map(double, [1, 2, 3])))RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
...
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.The fix is to put the pool code under if __name__ == "__main__":, or in a main() function called from there. A related cost: every worker re-imports your module. If importing it loads a 2 GB model or opens a database connection at the top level, each worker pays for that too. Keep import time cheap and do heavy set-up in a pool initializer= function instead.
Everything crosses by pickle
Processes do not share memory, so the function, its arguments and its results are pickled, sent through a pipe and unpickled. Functions are pickled by name: the worker looks them up again by module and qualified name. That rules out lambdas and functions defined inside other functions. Objects tied to the operating system, such as locks, sockets, open files and database connections, cannot be pickled at all.
Press Run (⌘ Enter) to see what happens.functools.partial around a module-level function is the usual way to pass extra settings. For a database connection, open one per worker in the pool's initializer, not in the parent.
What does this print?
import pickle
def top_level(x):
return x
def outer():
def nested(x):
return x
return nested
items = [top_level, outer(), lambda x: x, len, [top_level]]
ok = 0
for obj in items:
try:
pickle.dumps(obj)
ok += 1
except Exception:
pass
print(ok)Start methods: spawn, fork and forkserver
How a worker process is created is called the start method:
| Method | How it works | Default on |
|---|---|---|
spawn | Starts a fresh interpreter, imports your main module | Windows (only option), macOS since 3.8 |
fork | Copies the parent process as it is right now | Linux and other POSIX up to 3.13 |
forkserver | A clean, single-threaded server process forks each worker on request | Linux since 3.14 |
fork is fast and children inherit everything, including globals you set before creating the pool. It is also unsafe once the parent has threads. fork copies only the thread that called it. A lock held at that moment by another thread, such as the lock inside logging or a database driver, is copied in its locked state, with no thread left to release it. The child can freeze the first time it logs. Since 3.12 Python warns about this:
DeprecationWarning: This process (pid=54433) is multi-threaded, use of fork() may lead to deadlocks in the child.Since web frameworks, gRPC clients and metrics exporters all start background threads, Python 3.14 changed the Linux default to forkserver. That change broke real code. Scripts that set a global before the pool and relied on fork to copy it into children now see the original value. Lambdas that worked by luck under fork now fail to pickle. If your Linux jobs got slower or started failing after moving to 3.14, this is the first thing to check.
Do not rely on the default. Choose the method in code so your program behaves the same on a Mac laptop and a Linux server:
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor
if __name__ == "__main__":
ctx = mp.get_context("spawn")
with ProcessPoolExecutor(max_workers=4, mp_context=ctx) as pool:
...Match each statement to the start method.
What a process pool really costs
Three costs decide whether processes pay off.
Start-up. Each spawn worker is a new interpreter that imports your modules. That takes milliseconds for a small script and seconds for a big app. Create the pool once and reuse it. Do not create a pool per request.
Moving data. Pickling is not free. If the work per item is small and the data is big, you spend more time shipping than computing. Measure it:
Press Run (⌘ Enter) to see what happens.Per-task overhead. Each task is a round trip through two queues. map has a chunksize argument that sends items in batches. Its default for ProcessPoolExecutor.map is 1, which is terrible for many small items. Here are 100,000 tiny tasks on four warm workers:
import time
from concurrent.futures import ProcessPoolExecutor
def square(x: int) -> int:
return x * x
if __name__ == "__main__":
items = range(100_000)
start = time.perf_counter()
sum(square(x) for x in items)
print(f"plain loop {time.perf_counter() - start:6.3f}s")
with ProcessPoolExecutor(max_workers=4) as pool:
list(pool.map(square, range(4))) # warm up: start the workers
for chunksize in (1, 100, 10_000):
start = time.perf_counter()
sum(pool.map(square, items, chunksize=chunksize))
print(f"chunksize={chunksize:<9} {time.perf_counter() - start:6.3f}s")plain loop 0.003s
chunksize=1 6.046s
chunksize=100 0.065s
chunksize=10000 0.010sWith chunksize=1 the pool is two thousand times slower than the plain loop. Even the best chunk size loses, because squaring a number is too cheap to be worth shipping anywhere. The rule: give each task at least tens of milliseconds of real work. Split the input into a few chunks per worker, not one task per row.
pool.map(parse, lines) on 1 million lines. It is much slower than a plain loop. What is the best fix?Sharing data, and why you usually should not
When workers need the same large input, you have options:
- Pass references, not data. Send a file path, an S3 key or a row-id range, and let each worker read its own slice. This is the most common answer at work, and it is how task queues operate too.
multiprocessing.shared_memorygives a block of raw bytes that several processes can map without copying. NumPy arrays can sit on top of it. You mustclose()it in every process andunlink()it once, or it outlives your program.multiprocessing.Manager()runs a server process holding adictorlistthat others reach through proxies. It is convenient and slow: every access is a round trip. Fine for a progress counter, wrong for a hot loop.
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import shared_memory
def total(name: str, size: int) -> int:
shm = shared_memory.SharedMemory(name=name) # attach, no copy
try:
return sum(shm.buf[:size])
finally:
shm.close()
if __name__ == "__main__":
data = bytes(range(256)) * 4
shm = shared_memory.SharedMemory(create=True, size=len(data))
try:
shm.buf[: len(data)] = data
with ProcessPoolExecutor(max_workers=2) as pool:
print(pool.submit(total, shm.name, len(data)).result())
finally:
shm.close()
shm.unlink() # free it, or it outlives the process130560Subinterpreters in 3.14
Python 3.14 added concurrent.interpreters (PEP 734) and concurrent.futures.InterpreterPoolExecutor. A subinterpreter is a separate Python interpreter inside the same process, with its own modules, its own globals and, since 3.12, its own GIL. So several of them run Python in parallel, like processes, but they start faster and use less memory, because there is still only one OS process.
from concurrent import interpreters
interp = interpreters.create()
interp.exec("import sys; print('hello from interpreter', id(sys.modules))")
print("main sees", len(interpreters.list_all()), "interpreters")
interp.close()hello from interpreter 4385260608
main sees 2 interpretersIn the benchmark at the top, the interpreter pool matched the process pool. The catches are real, though:
- Isolation is strict. Interpreters share no Python objects. Data passes between them by copying, through calls or
interpreters.create_queue(). You get no shared-state shortcut. - Extension modules must opt in. A C extension has to support being loaded in several interpreters with a per-interpreter GIL. Many popular third-party ones do not yet, and importing one in a subinterpreter fails with an
ImportError. Check this first for your dependencies. - It is new. Tooling, debuggers and libraries are still catching up. For production CPU work today, a process pool is the safer default. Subinterpreters are worth trying when start-up time or memory per worker is your bottleneck.
Free-threaded CPython
PEP 703 added a build of CPython with no GIL at all. Threads in one process run Python bytecode in parallel. It is a separate build, installed next to the normal one, usually as python3.14t:
3.13 (2024)
Experimental
First free-threaded build, behind a separate binary. Large single-thread slowdown, few compatible wheels.
3.14 (2025)
Supported, still optional
PEP 779 marks it officially supported. The specialising interpreter works in it, so the single-thread cost shrank. Still a separate `t` build.
3.15 (2026)
Still not the default
A stable ABI for free-threaded builds (PEP 803) makes it easier for libraries to ship one wheel. The macOS installer adds the free-threaded binary next to the normal one.
Later
Default build?
Making it the default is a separate decision with no date. Teach both builds, and check the official docs for the current status.
Try it with uv, then check which build you are on:
uv python install 3.14tuv run --python 3.14t python -VVimport sys
import sysconfig
print("free-threaded build:", bool(sysconfig.get_config_var("Py_GIL_DISABLED")))
print("GIL enabled now:", sys._is_gil_enabled())Python 3.14.4 free-threading build (main, Apr 14 2026, 14:22:52) [Clang 22.1.3 ]
free-threaded build: True
GIL enabled now: FalseBoth checks matter. If you import a C extension that has not declared it is safe without the GIL, the free-threaded build turns the GIL back on for the whole process and prints a warning. PYTHON_GIL=0 or -X gil=0 forces it off anyway, at your own risk. Libraries publish separate free-threaded wheels, tagged cp314t. The big scientific libraries have them. Many smaller ones do not yet, because a C extension that relied on the GIL for safety has to add its own locking first. That work is why the ecosystem lags.
Here is the prime benchmark again, this time on the free-threaded build:
3.14.4 | start method: spawn
plain loop 1.17s
4 threads 0.30s 17984 primes each
4 processes 0.38s 17984 primes each
4 interpreters 0.36s 17984 primes eachNow four threads are the fastest option: no pickling and no extra interpreters. Two costs come with that. Single-threaded code ran about 8% slower in this test (0.147 s against 0.136 s, best of five), because the build needs extra bookkeeping for safe reference counting. And you still need locks. The lost-update script from the last lesson printed got 1750 out of 4,000 on this build, and a bare counter += 1 loop lost most of its increments. Removing the GIL makes races more likely, not less. Built-in containers use per-object locks so that list.append will not corrupt the list, but your own multi-step logic is yours to protect.
Where real systems put CPU work
At work, the tools in this lesson are often not the final answer:
- Task queues. A web request should not wait for a CPU-heavy job. Put the job on a queue and let worker processes on other machines run it. Task Queues with Celery covers this. A web server's own parallelism comes from running several worker processes, as Performance and Scaling explains in "Workers and processes".
- Vectorised libraries. A loop over a million numbers in Python is slow on any number of cores. The same calculation in NumPy or Polars runs in C, often tens of times faster on one core, and many of their operations release the GIL. NumPy Essentials shows why. Try this before you reach for a pool.
- Native extensions. For one hot function, Rust via PyO3 and maturin, or Cython, can give large speed-ups and release the GIL while running. The next lesson, Profiling and Making Python Fast, shows how to find which function is worth it.
- ProcessPoolExecutor
- An executor that runs functions in separate worker processes, each with its own interpreter and GIL.
- start method
- How multiprocessing creates a worker: spawn (fresh interpreter), fork (copy the parent) or forkserver (fork from a clean helper).
- pickling
- Serialising Python objects to bytes; everything sent to or from a worker process is pickled.
- chunksize
- How many items map sends to a worker in one task; larger chunks cut per-task overhead.
- subinterpreter
- A separate Python interpreter inside the same process, with its own modules and GIL (concurrent.interpreters, 3.14).
- free-threaded build
- An optional CPython build (python3.14t) with no GIL, so threads run Python bytecode in parallel.
- shared memory
- A block of bytes mapped into several processes, so they can read it without copying (multiprocessing.shared_memory).