Part 13 / Topic 1 of 11
Concurrency vs parallelism
Most programs do one thing at a time. That is slow when the program spends its time waiting.
- Concurrency = dealing with many tasks in overlapping time. One worker switches between tasks while each one waits.
- Parallelism = doing many tasks at the very same moment, on several CPU cores (the separate "brains" inside your processor).
Think of a restaurant kitchen. Concurrency is one cook who puts rice on the stove, then chops onions while the rice boils, then stirs the dal. Parallelism is four cooks, each making a different dish at the same time.
I/O-bound vs CPU-bound
I/O means input/output: reading files, talking to a database, calling a web API. Ask "what is my program doing most of the time?"
| Kind | Most time spent | Examples | What helps |
|---|---|---|---|
| I/O-bound | Waiting for something outside | Downloading 100 pages, reading many files, calling APIs | Threads or asyncio (concurrency) |
| CPU-bound | Calculating | Resizing photos, heavy maths, compressing files | Processes (parallelism) |
import time
start = time.perf_counter() # a precise stopwatch, in seconds
time.sleep(0.2) # I/O-bound: the CPU is idle while we wait
total = sum(range(5_000_000)) # CPU-bound: the CPU is busy the whole time
print(total) # 12499997500000
๐ Going deeper: a process is a running program with its own memory. A thread is a line of work inside a process; all threads of a process share its memory. That sharing makes threads cheap, and also risky (section 3).
Done here? The practice set for Part 13 โ 8 exercises with solutions โ is on the part page.