Threads help when a program spends its time waiting, for example on downloads. They do not help much with heavy calculation, because in normal Python only one thread runs Python code at a time. To use all the cores of your CPU for number crunching, image work or big reports, run the work in several processes. The ProcessPoolExecutor class makes this nearly as easy as a loop.
In this lesson you will learn
- Why threads do not speed up CPU-heavy Python code
- Running work in parallel with
ProcessPoolExecutor - Why the
if __name__ == "__main__":guard is required submit,as_completedand errors from workers- The older
multiprocessing.PoolAPI
You should know threading and functions.
Threads vs Processes for Heavy Work
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def count_primes(limit):
"""CPU-heavy work: count primes below limit."""
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
LIMITS = [150_000, 150_000, 150_000, 150_000]
def timed(label, run):
start = time.perf_counter()
result = run()
secs = time.perf_counter() - start
print(f"{label:10} {result}")
return secs
if __name__ == "__main__": # required: child processes import this file
t_plain = timed("one by one", lambda: [count_primes(n) for n in LIMITS])
with ThreadPoolExecutor(max_workers=4) as pool:
t_threads = timed("threads", lambda: list(pool.map(count_primes, LIMITS)))
with ProcessPoolExecutor(max_workers=4) as pool:
t_procs = timed("processes", lambda: list(pool.map(count_primes, LIMITS)))
print("threads faster than one by one? ", t_threads < t_plain * 0.7)
print("processes faster than one by one?", t_procs < t_plain * 0.8)
Output
one by one [13848, 13848, 13848, 13848]
threads [13848, 13848, 13848, 13848]
processes [13848, 13848, 13848, 13848]
threads faster than one by one? False
processes faster than one by one? True
count_primeskeeps the CPU busy all the time; it never waits for anything.- With threads, the time hardly changes. Standard Python has a Global Interpreter Lock (GIL), which lets only one thread run Python code at a time. The four threads just take turns.
- With processes, each worker is a separate Python program with its own GIL, so on a machine with two or more cores they really run at the same time. The output was produced on a 2-core machine; with more cores the gain is bigger.
pool.mapworks like the built-inmap, and the results come back in the same order as the inputs.- The
if __name__ == "__main__":line is required. On Windows and macOS, each worker starts by importing your file. Without the guard, each worker would start its own pool, again and again.
submit, Errors and Pool
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import Pool
def digit_sum(n):
return n, sum(int(d) for d in str(n ** 50))
def risky(n):
if n == 3:
raise ValueError("bad input 3")
return n * n
if __name__ == "__main__":
# submit + as_completed: handle each result as soon as it is ready
with ProcessPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(digit_sum, n) for n in (7, 12, 99)]
results = sorted(f.result() for f in as_completed(futures))
for n, s in results:
print(f"digit sum of {n}**50 = {s}")
# Errors in a worker come back when you ask for the result
with ProcessPoolExecutor(max_workers=2) as pool:
for n, fut in [(n, pool.submit(risky, n)) for n in range(1, 5)]:
try:
print(n, "->", fut.result())
except ValueError as e:
print(n, "-> failed:", e)
# The older multiprocessing.Pool API does the same job
with Pool(processes=2) as pool:
print(pool.map(abs, [-3, -1, 4, -1, -5]))
print(pool.starmap(pow, [(2, 10), (3, 4), (10, 3)]))
Output
digit sum of 7**50 = 184
digit sum of 12**50 = 216
digit sum of 99**50 = 432
1 -> 1
2 -> 4
3 -> failed: bad input 3
4 -> 16
[3, 1, 4, 1, 5]
[1024, 81, 1000]
pool.submit(fn, arg)starts one task and returns aFuturestraight away.future.result()waits for the answer.as_completedgives back futures in the order they finish, which may differ from the order you submitted them. Sorting the results makes the output tidy.- If a worker raises an exception, it is sent back to the main process. It is raised again when you call
result(), so you can catch it there. multiprocessing.Poolis the older interface.mapandstarmap(for functions with several arguments) do the same job.
Rules for Process Workers
- Data is copied. Arguments and results are packed with pickle and sent between processes. Lambdas and functions defined inside other functions cannot be sent, so use normal top-level functions.
- No shared variables. A worker that changes a global list changes only its own copy. Return results instead.
- Starting processes costs time. Tiny tasks can run slower in a pool than in a loop. Give each task a decent amount of work, or use the
chunksizeargument ofmap. - Size the pool to the CPU.
os.cpu_count()tells you how many cores the computer has; by default the pool uses that number.
| Work type | Best tool |
|---|---|
| Waiting on network or files (I/O-bound) | Threads or asyncio |
| Heavy calculation (CPU-bound) | Processes |
| Large number arrays | NumPy, which does the work in fast C code |
Common Mistakes
- Leaving out the
__main__guard, which causes errors or endless new processes. - Passing a lambda to a process pool, which fails because lambdas cannot be pickled.
- Using processes for many tiny tasks, where the cost of sending data is larger than the work.
- Expecting a global variable to collect results from workers. Each process has its own memory.
Practice Exercises
Exercise 1. Use a process pool to compute the squares of the numbers 1 to 5.
Show answer
from concurrent.futures import ProcessPoolExecutor
def square(n):
return n * n
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
print(list(pool.map(square, range(1, 6)))) # [1, 4, 9, 16, 25]
Exercise 2. A program downloads 200 web pages. Should it use threads or processes?
Show answer
Threads (or asyncio). Downloading is mostly waiting for the network, and the GIL is released while a thread waits, so threads overlap the waiting well and are cheaper than processes.
Frequently Asked Questions
Will Python ever drop the GIL?
Python 3.13 added an optional “free-threaded” build without the GIL, and Python 3.14 made it officially supported. It is still a separate build, and the standard Python download keeps the GIL, so processes remain the usual way to use several cores.
How can processes share data if they cannot share variables?
The simplest way is to return results from each task. For more, the multiprocessing module offers Queue, Manager and shared memory, and many programs use a database or files.
Summary
- Threads do not speed up CPU-heavy Python code because of the GIL; processes do.
ProcessPoolExecutor.mapspreads work over several cores and keeps result order.- Always guard the start of the program with
if __name__ == "__main__":. - Workers get copies of the data, so use top-level functions and return results.
