Sub topic 1
Concurrency and parallelism: what you are actually asking for
Prerequisites
This chapter assumes you can:
- Write and run Python functions and scripts.
- Use context managers (
withstatements) and the standard library. - Picture a program doing several things at once, even if you have not written one.
No threading code appears yet. This chapter fixes the vocabulary that the rest of the tutorial relies on.
Two different requests
People often say "make it concurrent" when they mean "make it faster". These are different requests.
- Concurrency means structuring a program so that several tasks are in progress at the same time. Their lifetimes overlap, but only one may be running at any instant.
- Parallelism means several tasks are executing at the same instant, on separate CPU cores.
Concurrency is about how you organize the work. Parallelism is about how the hardware runs it. You can have concurrency without parallelism, as in one cook who switches between three pots. You can also have parallelism without much concurrency in the design, as in a vectorized operation that splits one array across cores.
Concurrency on a single thread
The following program interleaves two tasks on one thread. Each yield pauses a task and hands control back to a loop that runs the next one.
def task(name, steps):
for i in range(1, steps + 1):
print(f"{name} step {i}")
yield # pause here and let another task run
def run_round_robin(tasks):
while tasks:
current = tasks.pop(0)
try:
next(current)
tasks.append(current)
except StopIteration:
pass # this task is finished, so drop it
run_round_robin([task("A", 3), task("B", 3)])The output alternates:
A step 1
B step 1
A step 2
B step 2
A step 3
B step 3Both tasks are in progress together, so the program is concurrent. Only one line of Python runs at a time, so nothing is parallel. This program finishes no faster than running A and then B. Concurrency pays off only when a task spends time waiting, because the waiting time can go to another task.
What you are really asking for
Before you pick a tool, decide which goal you have.
| Goal | What you need | Typical situation |
|---|---|---|
| Stay responsive while waiting | Concurrency | Many network requests, a UI that must not freeze |
| Finish computation sooner | Parallelism | Image processing, number crunching |
| Both | Concurrency and parallelism | A server that also does heavy computation |
The tree is a simplification. The next chapter defines "waiting" and "computing" precisely, and later chapters explain why CPython's Global Interpreter Lock (GIL) changes the answer for threads.
How Python names these tools
Python gives you three main ways to run tasks at the same time. Later chapters cover each in turn.
threadingruns several threads inside one process. They share memory.multiprocessingruns several processes. Each has its own memory and its own interpreter.asyncioruns many tasks on one thread by switching only at points the code marks.
You can check how much parallelism your machine can offer with os.cpu_count():
import os
print(os.cpu_count())This number is an upper bound on useful parallelism for CPU-heavy work. It does not tell you what Python threads will achieve.
Common mistakes at this stage
- Using "concurrent" and "parallel" as synonyms, then choosing a tool that fits the wrong one.
- Adding concurrency to code that is slow because it computes, not because it waits.
- Measuring nothing. Always time a change before and after.
Exercise
A script downloads 50 small files one after another and takes 100 seconds, with the CPU nearly idle. Do you need concurrency, parallelism, or both, and why?
Show answer
Concurrency. The script is slow because it waits on the network while the CPU sits idle. Overlapping the waits fixes that, and extra cores would add little because there is almost no computation to spread across them.