Stop 14 · Advanced PythonTopics · 2/8

Threads vs Processes

Part of the Python Roadmap

In short

Your program can do several things at once in two very different ways. Picking the wrong one can make your code slower instead of faster, so this choice matters before you write any concurrent code.

Threads run inside one process and share memory, which suits waiting on networks or disks. Processes have separate memory and can use several CPU cores at once, which suits heavy calculations.

The jaadu peeks between two scenes: three cooks squeezing past each other in one small kitchen, and three separate tidy kitchens side by side each with a single busy cook.

Think of it like this

One kitchen or many kitchens

Threads are several cooks in one kitchen sharing the same fridge and counter. Great while they wait for the oven or a delivery, but they bump into each other over shared things. Processes are separate kitchens, each with its own fridge. More setup and harder to share ingredients, but every kitchen can cook at full speed at the same time.

Watch it happen

Threads or processes?

Threads

  • Live inside one process and share memory
  • Cheap to start, easy to share data
  • In CPython only one runs Python code at a time
  • Best for I/O: network calls, file reads, database queries

Processes

  • Each has its own memory and its own interpreter
  • Slower to start, data must be pickled to share
  • Truly run in parallel on different CPU cores
  • Best for CPU work: number crunching, image processing

Waiting on something? Use threads or asyncio. Calculating something heavy? Use processes.

The big ideas

What you need to know

I/O-bound work

The program mostly waits: for a website, a disk or a database. Overlapping the waits gives big speedups, and threads do that well.

CPU-bound work

The program is busy calculating the whole time. Only more CPU cores help, which in CPython means more processes.

Shared vs separate memory

Threads see the same variables, which is convenient but needs locks. Processes don't, so you pass data in and get results back.

Same interface

concurrent.futures gives ThreadPoolExecutor and ProcessPoolExecutor the same API, so switching is often a one-word change.

See it in code

Walk through the code

python
1import time2from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor3 4def count_primes(limit: int) -> int:5    count = 06    for n in range(2, limit):7        if all(n % d for d in range(2, int(n ** 0.5) + 1)):8            count += 19    return count10 11def timed(executor_cls, jobs: list[int]) -> float:12    start = time.perf_counter()13    with executor_cls(max_workers=4) as pool:14        list(pool.map(count_primes, jobs))15    return time.perf_counter() - start16 17if __name__ == "__main__":18    jobs = [200_000] * 419    print(f"threads:   {timed(ThreadPoolExecutor, jobs):.2f}s")20    print(f"processes: {timed(ProcessPoolExecutor, jobs):.2f}s")

1/4Pure Python maths with no waiting. This is CPU-bound work.

A CPU-heavy job run with four threads and then four processes. On a multi-core laptop the processes version finishes much faster. Try it and compare your own numbers.

Save yourself the pain

Common mistakes

Oops

Using threads to speed up heavy calculations in CPython.

Do this instead

Threads take turns running Python code. Use ProcessPoolExecutor or a library like NumPy that does the heavy work in C.

Oops

Starting one process per tiny task, like one per number.

Do this instead

Process start-up and data transfer cost time. Send bigger chunks of work to each process.

Your mission

Measure, don't guess

~25 min

Quick check

You need to resize 5,000 photos using pure Python code. Which is likely fastest in CPython?

Go deeper

  1. 1Classify five tasks as I/O-bound or CPU-bound.
  2. 2Open your task manager and see processes and threads for a running program.
  3. 3Write down the trade-offs of shared memory versus separate memory.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge