Python Processes with multiprocessing
What you will learn
- What a process is and how it differs from a thread
ProcessandPool(map,starmap,imap,apply_async)- The
if __name__ == "__main__":rule - Why data must be picklable
- Sharing data:
Queue,Value,Lock - Start-up costs, and when processes pay off
1. Processes
A process is a separate running copy of Python with its own memory. Where threads share memory and share the interpreter's single lock on Python code (lesson 20.6), processes are independent: each can run Python code at full speed on its own processor core. So processes give true parallelism for CPU-bound work (lesson 20.1).
The price:
- starting a process is slow (tens to hundreds of milliseconds);
- processes do not share variables: data must be copied to them (through "pickling", lesson 15.8) and results copied back;
- more memory is used.
import multiprocessing as mp
import os
2. The main-guard rule
On Windows and macOS, a new process starts a fresh Python that imports your script to find the function to run (the "spawn" start method; Linux traditionally "forks" a copy instead, so your program may behave differently there). If the script's top level starts processes, every child would start more children without end. So all code that creates processes must sit under the main guard (lesson 16.2):
if __name__ == "__main__":
...
The check computer used the spawn method:
print("start method:", mp.get_start_method())
start method: spawn
Everything in this lesson goes inside that guard.
Quick check: why is the main guard essential in multiprocessing code on Windows?
Each child process re-imports the script; without the guard the import would start new processes again and again.
3. A pool of workers: Pool.map
The simplest way to use several cores is a Pool: a group of worker processes. pool.map(function, items) splits the items among the workers, runs the function, and returns the results in order, like the built-in map:
def count_primes(limit):
"""CPU-bound: count the primes below limit by trial division."""
count = 0
for n in range(2, limit):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
count += 1
return count
if __name__ == "__main__":
limits = [250_000, 260_000, 270_000, 280_000]
seq = [count_primes(n) for n in limits]
with mp.Pool(4) as pool:
par = pool.map(count_primes, limits)
print(seq == par)
Timing on the check computer (8 cores):
one after another 2.09 s [22044, 22837, 23642, 24432]
pool of 4 processes 0.93 s [22044, 22837, 23642, 24432]
same answers: True
The four calculations took 2.09 s one after another and 0.93 s with four processes: more than twice as fast, though not four times (start-up cost, and the four tasks are not equal). Use the pool as a context manager (with, lesson 14.6) so it shuts down properly.
Other ways to hand out work:
| Method | Does |
|---|---|
pool.map(f, items) |
applies f to each item; results in order |
pool.starmap(f, [(a, b), ...]) |
each item is a tuple of arguments |
pool.imap(f, items) |
like map but returns results one by one as they arrive |
pool.imap_unordered(f, items) |
as they finish, in any order |
pool.apply_async(f, args) |
start one job, get a result object; .get(timeout=...) waits for it |
with mp.Pool(2) as pool:
print(pool.map(square, range(8)))
print(pool.starmap(pow, [(2, 3), (3, 2)]))
print(list(pool.imap(square, range(5))))
r = pool.apply_async(square, (9,))
print(r.get(timeout=5))
[0, 1, 4, 9, 16, 25, 36, 49]
[8, 9]
[0, 1, 4, 9, 16]
81
(Here square is def square(x): return x * x, defined at the top level of the file.) The pool also chooses how many items to send each worker (chunksize); for many tiny items, a larger chunk size reduces overhead.
4. Pickling: what can be sent
Functions, arguments and results travel between processes by pickling (lesson 15.8), so they must be picklable. Practical rules:
- The function must be defined at the top level of a module: not a
lambda, not a function defined inside another function. - Arguments and results should be plain data (numbers, text, lists, dictionaries, your own simple classes).
- Open files, locks and sockets cannot be sent.
pool.map(lambda x: x, [1])
PicklingError: Can't pickle <function <lambda> at 0x...>: attribute lookup <lambda> on __main__ failed
A function defined inside the main block used as a Process target failed in a child under spawn with AttributeError: Can't get attribute 'mutate' on <module '__mp_main__' ...>: the child could not find it.
Errors raised inside a worker are sent back and raised again in the parent:
def boom(x):
if x == 3:
raise ValueError("bad item 3")
return x
with mp.Pool(2) as pool:
try:
pool.map(boom, range(5))
except ValueError as e:
print("error from worker:", e)
error from worker: bad item 3
5. Process: the building block
A Pool is built on Process. Use Process directly when you want a long-running separate worker:
def child(q, n):
q.put((os.getpid(), cpu(n)))
if __name__ == "__main__":
q = mp.Queue()
ps = [mp.Process(target=child, args=(q, 200_000)) for _ in range(3)]
for p in ps:
p.start()
got = [q.get() for _ in ps]
for p in ps:
p.join()
print("processes", len({pid for pid, _ in got}), "exit codes", [p.exitcode for p in ps])
processes 3 exit codes [0, 0, 0]
(cpu was a simple summing loop.) The three results came from three different process ids. Notes:
start()andjoin()work as for threads (lesson 20.2);exitcodeis0when the process ended normally.mp.Queueis the process-safe queue for sending results back. Read results beforejoin(), or a full queue can block the child.- Changes a child makes to ordinary variables are not seen by the parent: each process has its own copy. In the check, a child changed
glob["x"]and the parent's dictionary stayed{'x': 1}.
6. Shared memory and locks
When processes must really share a number or array, use the shared objects mp.Value and mp.Array, and protect updates with a lock (as in lesson 20.2):
def bump(counter, lock, times):
for _ in range(times):
with lock:
counter.value += 1
if __name__ == "__main__":
counter = mp.Value("i", 0)
lock = mp.Lock()
ps = [mp.Process(target=bump, args=(counter, lock, 500)) for _ in range(4)]
for p in ps:
p.start()
for p in ps:
p.join()
print("shared counter:", counter.value)
shared counter: 2000
Four processes added 500 each and the total is exactly 2,000 ("i" means a C integer). Sharing is slower and trickier than passing messages, so prefer designs where each process works alone and returns its result.
7. Does it pay off?
Starting processes costs time, and sending data costs time, so tiny tasks get slower. On the check computer, four tiny tasks (counting primes below 10 to 40):
tiny tasks, sequential 0.00 s
tiny tasks, pool (warm) 0.14 s
tiny tasks, new pool each time 0.18 s
The pool took longer than the work itself. A rough rule: a task should take at least about a tenth of a second to justify a process, and big data should not be copied back and forth for little computing. Other points:
- The speed-up is limited by the number of cores (
mp.cpu_count()oros.cpu_count()), and the work must split into independent pieces. - Create the pool once and reuse it, rather than a new one per call.
- More processes than cores does not help CPU-bound work.
- For numeric work, libraries such as NumPy already use fast compiled code and sometimes several cores: try them first (lesson 20.1).
concurrent.futures.ProcessPoolExecutor(lesson 20.4) offers a friendlier interface to the same machinery.
Worked example: counting primes on several cores
Count the primes below four limits with trial division. Compare doing it one after another with a pool of four processes, check that the answers agree, then see what happens with tiny tasks.
import multiprocessing as mp
import os
import time
def count_primes(limit):
"""CPU-bound: count the primes below limit by trial division."""
count = 0
for n in range(2, limit):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
count += 1
return count
def timed(label, func):
start = time.perf_counter()
result = func()
print(f"{label:<28} {time.perf_counter() - start:5.2f} s {result}")
return result
if __name__ == "__main__":
limits = [250_000, 260_000, 270_000, 280_000]
print("cores:", os.cpu_count())
seq = timed("one after another", lambda: [count_primes(n) for n in limits])
with mp.Pool(4) as pool:
par = timed("pool of 4 processes", lambda: pool.map(count_primes, limits))
print("same answers:", seq == par)
tiny = [10, 20, 30, 40]
timed("tiny tasks, sequential", lambda: [count_primes(n) for n in tiny])
with mp.Pool(4) as pool:
timed("tiny tasks, pool (warm)", lambda: pool.map(count_primes, tiny))
Output on the check computer:
cores: 8
one after another 2.09 s [22044, 22837, 23642, 24432]
pool of 4 processes 0.93 s [22044, 22837, 23642, 24432]
same answers: True
tiny tasks, sequential 0.00 s [4, 8, 10, 12]
tiny tasks, pool (warm) 0.14 s [4, 8, 10, 12]
| Observation | Meaning |
|---|---|
| 2.09 s → 0.93 s | the heavy tasks ran on four cores at once: about 2.2 times faster |
| not 4 times faster | process start-up, copying, and uneven task sizes (the biggest limit decides the finish time) |
| same list of answers, in order | map returns results in input order |
| the tiny tasks are slower with the pool | start-up cost dominates: only use processes for substantial work |
everything under if __name__ == "__main__": |
required on Windows (spawn) |
The limits are chosen for the lesson, and timings differ on every computer. A smarter algorithm (the sieve of Eratosthenes) would beat this brute-force count by far, before any process is needed (lesson 18.5).
Common mistakes
- No main guard, causing an endless cascade of processes (or an error).
- Using
lambdaor nested functions as the worker. - Using processes for tiny tasks.
- Expecting changes to variables in a child to appear in the parent.
- Creating a new
Poolfor every small job. - Sending huge objects back and forth.
- More workers than cores for CPU-bound work.
- Forgetting
join()or to close the pool (usewith).
Key takeaways
- Processes have separate memory and run Python code in parallel on several cores: the tool for CPU-bound work.
with mp.Pool(n) as pool: pool.map(f, items)is the easiest way; results come back in order, and worker errors are re-raised.- Put process-creating code under
if __name__ == "__main__":; workers must be top-level functions with picklable arguments. - Use
mp.Queueto send results, andmp.Valuewith aLockonly when sharing is unavoidable. - Start-up and copying cost time: use processes for tasks of at least about a tenth of a second, and measure the gain.
Practice
1. Why can processes speed up calculations when threads cannot?
Show answer
Each process has its own interpreter and runs Python code on its own core, so several run truly in parallel.
2. What is wrong with pool.map(lambda x: x * 2, data)?
Show answer
A lambda cannot be pickled to send to the workers. Define the function with def at the top level of the module.
3. Why do changes made by a child process to a global dictionary not appear in the parent?
Show answer
Each process has its own memory, so the child modifies its own copy.
4. When would a process pool be slower than a plain loop?
Show answer
When the tasks are tiny: the start-up and data-copying costs exceed the work saved.
5. What does pool.imap_unordered return, compared with pool.map?
Show answer
Results one at a time as they finish, in any order, instead of a complete list in input order.
6. How many processes should a pool use for CPU-bound work?
Show answer
About as many as there are cores (os.cpu_count()); more adds overhead without extra speed.