Multiprocessing
Multiprocessing runs work in several separate Python processes, each with its own interpreter and GIL, so CPU-heavy code really runs in parallel on several cores. Use concurrent.futures.ProcessPoolExecutor with map, keep the work in top-level functions, and always start pools under if __name__ == "__main__":.
A CPU-heavy task
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
print(count_primes(10_000))1229
Running it on all cores
import time
from concurrent.futures import ProcessPoolExecutor
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
if __name__ == "__main__":
limits = [200_000] * 4
start = time.perf_counter()
serial = [count_primes(x) for x in limits]
print(f"one process: {time.perf_counter() - start:.1f}s")
start = time.perf_counter()
with ProcessPoolExecutor() as pool:
parallel = list(pool.map(count_primes, limits))
print(f"process pool: {time.perf_counter() - start:.1f}s")
print(serial == parallel, parallel[0])one process: 1.2s process pool: 0.6s True 17984
This output comes from a 2-core machine, so the pool takes half the time. With 8 cores, expect it to be close to 8 times faster. The pattern holds for any heavy pure-Python function.
Rules that avoid headaches
- Always create the pool under
if __name__ == "__main__":. On Windows and macOS each worker re-imports your file, and without the guard it would start pools endlessly. - The function must be defined at the top level of a module, not inside another function or as a lambda — workers need to import it.
- Arguments and results are copied between processes (pickled). Send small inputs, return small results; don't pass huge objects back and forth.
- Processes don't share variables. Return values instead of changing globals.
Many small tasks: chunksize
from concurrent.futures import ProcessPoolExecutor
def square(n: int) -> int:
return n * n
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
results = list(pool.map(square, range(100_000), chunksize=5_000))
print(sum(results))333328333350000
Sending work to a process has a cost. For thousands of tiny tasks, chunksize sends them in groups so the overhead doesn't eat the speed-up. For truly tiny work like this, plain Python or NumPy is faster than any pool.
When processes are worth it
| Good fit | Poor fit |
|---|---|
| Each task takes at least ~0.1 s of CPU time | Tasks that finish in microseconds |
| Inputs and outputs are small | Huge data that must be copied to every worker |
| Pure Python calculations | Work already done in NumPy or pandas (they use fast C code) |
| Batch jobs: resizing images, parsing files | Waiting on networks — use threads or asyncio |
Practice
Prepare work for a process pool. Write a top-level function word_count(text: str) -> int, then use the built-in map (exactly like pool.map) to count words in docs = ["one two", "three four five", "six"]. Print the list of counts and their total.
[2, 3, 1] 6