Sub topic 6
Running CPU-bound work in parallel with threads
This chapter assumes you know the threading module and concurrent.futures, the difference between threads and processes, and what a race condition is. You should also know how to start a free-threaded interpreter such as python3.13t. The previous chapters covered that setup.
What changes when threads run in parallel
In a standard CPython build, the Global Interpreter Lock (GIL) lets only one thread execute Python bytecode at a time. A CPU-bound function split across four threads therefore runs one thread at a time, so the total time is about the same as running the function four times in sequence.
In a free-threaded build, there is no GIL to serialize bytecode execution. Each thread can run on its own core. For pure-Python CPU-bound code, the speedup can approach the number of cores you have, minus overhead.
You do not need new APIs for this. threading.Thread and ThreadPoolExecutor work as before. The difference is in how the interpreter schedules them.
A CPU-bound workload
The example below counts primes with trial division. It is pure Python, uses no I/O, and never releases the GIL voluntarily, which makes it a clean test of parallelism.
from concurrent.futures import ThreadPoolExecutor
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(limit):
return sum(1 for n in range(limit) if is_prime(n))
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(count_primes, [200_000] * 4))
print(results)The pool starts four worker threads. pool.map hands each worker one call to count_primes(200_000). The workers share no mutable state, so no locks are needed, and the output is [17984, 17984, 17984, 17984].
On a standard build, this takes roughly four times as long as a single call. On a free-threaded build with at least four idle cores, it takes close to the time of one call.
Measuring the speedup
Do not trust the claim; measure it. The script below times the same work done sequentially and with a thread pool, then prints the ratio.
import sys
import time
from concurrent.futures import ThreadPoolExecutor
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(limit):
return sum(1 for n in range(limit) if is_prime(n))
def timed(label, func):
start = time.perf_counter()
result = func()
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.2f}s")
return elapsed
if __name__ == "__main__":
gil = sys._is_gil_enabled()
print("GIL enabled:", gil)
jobs = [200_000] * 4
def sequential():
return [count_primes(n) for n in jobs]
def threaded():
with ThreadPoolExecutor(max_workers=4) as pool:
return list(pool.map(count_primes, jobs))
t_seq = timed("sequential", sequential)
t_thr = timed("4 threads ", threaded)
print(f"speedup: {t_seq / t_thr:.2f}x")Run it on both builds and compare. Typical results on a machine with four or more free cores look like this:
| Interpreter | GIL enabled | Speedup with 4 threads |
|---|---|---|
| `python3.13` (standard) | True | about 1.0x, sometimes slightly below |
| `python3.13t` (free-threaded) | False | about 2.5x to 3.8x |
The exact numbers depend on your hardware, your operating system, and what else is running. The speedup is almost never a clean 4x, for reasons covered later in this chapter.
Using threading.Thread directly
ThreadPoolExecutor is the easiest way to run jobs, but plain threads work the same way. Each thread writes to its own slot in a preallocated list, so the threads never touch the same element.
import threading
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_range(start, stop, results, index):
results[index] = sum(1 for n in range(start, stop) if is_prime(n))
if __name__ == "__main__":
limit = 800_000
workers = 4
step = limit // workers
results = [0] * workers
threads = []
for i in range(workers):
start = i * step
stop = limit if i == workers - 1 else start + step
t = threading.Thread(target=count_range, args=(start, stop, results, i))
threads.append(t)
t.start()
for t in threads:
t.join()
print(sum(results))This splits one big problem into four ranges and combines the partial results. Writing to distinct list slots is safe because each thread owns its slot. Chapter sections later in the tutorial explain what is safe on shared data.
Note that the ranges here are not equally expensive. Trial division costs more for larger numbers, so the last thread does the most work and the others finish early. Uneven chunks are a common reason for a lower-than-expected speedup.
Choosing the number of threads
For CPU-bound work, more threads than cores does not help. Extra threads compete for the same cores and add context-switch overhead.
import os
cores = os.cpu_count()
print("logical CPUs:", cores)os.cpu_count() returns logical CPUs, which includes hyperthreads. It can also overstate what your process may use inside a container or under CPU affinity limits. Python 3.13 adds os.process_cpu_count(), which respects the affinity mask, so prefer it when it exists.
import os
def usable_cpus():
func = getattr(os, "process_cpu_count", None)
return (func() if func else os.cpu_count()) or 1
print(usable_cpus())A good default is one worker per usable core. Many small tasks usually balance better than a few large ones, so split work into more chunks than workers and let the pool distribute them.
Why the speedup is below the core count
Several effects limit the gain, even when the code is perfectly parallel:
- Serial portions. Any setup, splitting, and merging done by one thread limits the total speedup (Amdahl's law).
- Single-thread overhead. The free-threaded build is somewhat slower per thread than the standard build, because its reference counting and object access are more expensive. A later chapter covers this.
- Memory bandwidth and cache contention. Cores that share a memory bus or last-level cache slow each other down on memory-heavy work.
- Contended shared objects. If all threads hit the same object, such as one shared list or dictionary, they wait on its internal lock or fight over its reference count.
- Uneven chunks. The slowest thread decides when the job finishes.
- Thermal and frequency limits. Laptops often lower clock speeds when all cores are busy.
Shared state is now your problem
Under the GIL, many small mistakes stayed hidden because only one thread ran bytecode at a time. Without it, two threads can execute counter += 1 at the same moment. That statement reads, adds, and writes as separate steps, so one thread's update can overwrite another's.
The rule for parallel threads is simple: either do not share mutable state, or protect it. The prime-counting examples above follow the first rule. When you must accumulate into a shared value, use a lock.
import threading
counter = 0
lock = threading.Lock()
def work(n):
global counter
for _ in range(n):
with lock:
counter += 1
threads = [threading.Thread(target=work, args=(100_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # 400000Without the lock, the final value can be less than 400000 on a free-threaded build. The lock makes the read-modify-write sequence one indivisible step.
This example is deliberately lock-heavy: the threads spend nearly all their time waiting for the lock, so it will not speed up. A better design lets each thread count locally and combine the totals once at the end.
import threading
def work(n, results, index):
local = 0
for _ in range(n):
local += 1
results[index] = local
results = [0] * 4
threads = [threading.Thread(target=work, args=(100_000, results, i)) for i in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(sum(results)) # 400000Later chapters go deeper on data races, locks, and thread-safe design.
Common mistakes
- Running on the wrong interpreter. If
sys._is_gil_enabled()returnsTrue, you get no parallelism. A C extension that is not marked as free-threading safe can make the interpreter turn the GIL back on at import time. Check the flag after your imports, not only at the start. - Expecting I/O-bound code to speed up. Threads already helped with I/O under the GIL, because blocking calls release it. Free-threading adds little there.
- Timing too small a job. Thread start-up and pool creation cost time. Use work that runs for at least a second.
- Sharing one hot object. A single shared list, dictionary, or counter that every thread updates removes most of the benefit.
- Using more threads than cores. This adds overhead without adding throughput for CPU-bound work.
- Forgetting
if __name__ == "__main__":. Threads do not require it, but the guard keeps the script safe if you later switch toProcessPoolExecutor, which does.
Threads versus processes for CPU-bound work
Before free-threading, ProcessPoolExecutor was the standard way to use multiple cores. It still has a role.
| Aspect | Threads (free-threaded) | Processes |
|---|---|---|
| Data sharing | Direct, shared memory | Copied or pickled between processes |
| Start-up cost | Low | Higher |
| Memory use | One copy of shared data | Each process holds its own copy |
| Crash isolation | A crash can take down the whole process | A crash affects one worker |
| Safety | You must manage races | No shared state by default |
| Compatibility | Needs a free-threaded build and compatible extensions | Works on any build |
Threads are attractive when tasks share a large read-only structure, such as a model or a lookup table, and copying it to each process would be costly. Processes remain a good choice when tasks are independent, when you need isolation, or when a required extension does not yet support free-threading.
Exercise
You run the timing script on python3.13t with four workers on an 8-core machine. The speedup is 1.0x, and sys._is_gil_enabled() prints True. Give two possible causes and say how you would check each.
Show answer
First, the GIL may have been turned on by the environment, for example PYTHON_GIL=1 set in the shell or -X gil=1 on the command line. Check with echo $PYTHON_GIL and the command used to start the script. Second, an imported C extension that does not declare free-threading support may have caused the interpreter to re-enable the GIL at import time. Check by printing sys._is_gil_enabled() before and after each import, and look for a runtime warning about the GIL being enabled. Remove or replace the extension, or force the GIL off with PYTHON_GIL=0 only if you know that the extension is safe.
Exercise
A worker function loops 1,000,000 times and each iteration does shared_list.append(x) on one list shared by eight threads. It runs no faster than with two threads. Why, and how would you restructure it?
Show answer
All eight threads contend for the same list, so they serialize on its internal lock and share cache lines, which removes most of the parallel gain. Give each thread its own local list, let it append there without contention, and merge the lists once after the threads are joined, for example with itertools.chain.