Sub topic 1
Concurrency and parallelism: what you are actually asking for
Programmers often say "make it concurrent" or "make it parallel" as if the two mean the same thing. They don't, and mixing them up leads to a common mistake in Python: adding threads to a program and getting no speedup. This chapter separates the two ideas, gives you a way to tell which one you need, and sets up the rest of the tutorial.
Prerequisites
This chapter assumes you can:
- Write and run Python functions and scripts.
- Use the standard library and
withstatements. - Picture a program doing several things at once, even if you haven't written one.
You don't need to know anything about threads, processes, or the Global Interpreter Lock (GIL) yet. Later chapters cover them.
Two different questions
Concurrency and parallelism answer different questions.
- Concurrency is about structure. Can several tasks be in progress at the same time, each started before the others finish? It describes how a program is organized.
- Parallelism is about execution. Are several pieces of work running at the exact same instant, on different CPU cores? It describes what the hardware is doing.
A concurrent program doesn't have to run anything in parallel. A parallel program is always concurrent, because its tasks overlap in time.
A common analogy is a cook in a kitchen. One cook can start the rice, chop vegetables while it simmers, and check the rice now and then. Several dishes are in progress, but only one pair of hands is working at any instant. That is concurrency. Two cooks working at two stoves at once is parallelism.
| Property | Concurrency | Parallelism |
|---|---|---|
| Main idea | Several tasks in progress, overlapping in time | Several tasks executing at the same instant |
| Needs multiple cores | No | Yes |
| What it mainly helps with | Waiting (network, disk, timers) | Computing (math, parsing, compression) |
| Describes | Program structure | Hardware activity |
| Possible on one core | Yes | No |
Concurrency without parallelism
You can see concurrency with nothing but a single thread. This small scheduler runs two tasks by taking turns. Each task is a generator, and yield hands control back to the scheduler.
from collections import deque
def task(name, steps):
for i in range(1, steps + 1):
print(f"{name}: step {i}")
yield # give control back to the scheduler
def run(tasks):
ready = deque(tasks)
while ready:
current = ready.popleft()
try:
next(current)
except StopIteration:
continue # this task has finished
ready.append(current)
run([task("A", 3), task("B", 2)])The output is:
A: step 1
B: step 1
A: step 2
B: step 2
A: step 3Both tasks are in progress at once. B starts before A finishes, and their steps interleave. But the program is one thread on one core, and no two lines ever execute at the same instant. This is concurrency with no parallelism.
Notice that the interleaving is deterministic here because you wrote the scheduler. With threads, the operating system decides when to switch, so the order can change from run to run. That difference is the source of the shared-state problems covered in a later chapter.
Why concurrency helps when tasks wait
Most programs spend a lot of time waiting: for a web server to answer, for a disk read, for a timer. While one task waits, the CPU has nothing to do for that task. Concurrency lets another task use that time.
The next example uses real threads. Each task "waits" for half a second with time.sleep, which stands in for a network call.
import threading
import time
def wait(seconds):
time.sleep(seconds)
def sequential():
for _ in range(3):
wait(0.5)
def threaded():
threads = [threading.Thread(target=wait, args=(0.5,)) for _ in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
for fn in (sequential, threaded):
start = time.perf_counter()
fn()
print(f"{fn.__name__}: {time.perf_counter() - start:.2f}s")Typical output is about sequential: 1.50s and threaded: 0.50s. The threaded version is three times faster, yet it did not compute anything faster. It overlapped three waits. Nothing was being calculated during those waits, so there was no computation to run in parallel.
This is the key point. Concurrency speeds up programs by overlapping idle time. It does not make the CPU do more work per second.
Parallelism: more hands doing real work
Parallelism helps when the CPU is the bottleneck. If a task spends its whole time calculating, there is no idle time to fill. Interleaving two such tasks on one core takes as long as running them one after the other, and a little longer once you count the switching. The only way to finish sooner is to give the work to more cores.
Your machine reports how many cores it has:
import os
print("Logical CPUs:", os.cpu_count())os.cpu_count() counts logical CPUs, so a machine with hyper-threading reports more than its physical core count. It also ignores limits set by containers or CPU affinity. On Linux, len(os.sched_getaffinity(0)) shows how many CPUs the current process may actually use. When you size a worker pool, the affinity number is often the safer one.
Parallel speedup has limits. Four cores rarely give a fourfold speedup, for three reasons:
- Some of the work can't be split up and stays sequential.
- Starting workers and moving data between them costs time.
- Cores share memory bandwidth and caches.
Later chapters measure these costs for processes.
Where Python complicates the picture
In many languages, "use threads" gives you both concurrency and parallelism. In the standard CPython interpreter, it usually gives you only concurrency. A mechanism called the Global Interpreter Lock (GIL) lets only one thread run Python bytecode at a time. Threads still overlap their waiting, because a thread blocked on I/O gives up the lock. But two threads doing pure Python arithmetic take turns instead of running side by side.
This chapter only previews that fact. The GIL gets its own chapters. For now, remember the practical result:
- Threads in CPython reliably give you concurrency, which helps with waiting.
- Processes give you parallelism, because each process has its own interpreter and its own GIL.
- The right choice depends on what your task spends its time on.
Some details differ across Python versions. Recent releases offer a free-threaded build with no GIL, which changes the second point. Treat the rules above as the behavior of the standard build.
A way to decide what you need
Before you pick a tool, ask what the task is waiting on. The answer decides between concurrency and parallelism.
The next chapter names these two kinds of work, I/O-bound and CPU-bound, and shows how to tell them apart. Real programs are often a mix, so the diagram is a starting point and not a rule. The last chapter in this tutorial returns to the decision with measurements.
Common mistakes
- Treating the words as synonyms. If a colleague asks for "parallel downloads", they usually mean overlapping waits. That is concurrency, and threads handle it well.
- Expecting speedup from concurrency alone on CPU-bound work. Interleaving calculations on one core never finishes sooner than running them in sequence.
- Expecting parallelism from more workers than cores. Eight CPU-bound processes on a four-core machine can't all run at once. The extra ones wait for a core.
- Judging by a single run. Timing depends on the machine, other running programs, and caching. Run each measurement several times and compare the typical value.
- Trusting
os.cpu_count()inside a container. The number can be larger than the CPU limit you were given.
Summary of the vocabulary
You'll use these terms through the rest of the tutorial:
- A task is a unit of work, such as one download or one calculation.
- In progress means a task has started and not yet finished.
- Concurrent means several tasks are in progress during the same period.
- Parallel means several tasks are executing at the same instant on separate cores.
- A bottleneck is the resource a task spends most of its time waiting on or using up. Finding it tells you which kind of help you need.
Exercise
Your script downloads 20 files from a web server, one after another, and takes 40 seconds. Profiling shows the CPU is idle almost all of that time. Do you need concurrency, parallelism, or both? Which would you reach for first on a standard CPython build, and why?
Show answer
You need concurrency. The time goes to waiting on the network, and nothing is being computed, so overlapping the waits cuts the total time. Threads (or asyncio) are the first choice on standard CPython, because a thread blocked on I/O releases the GIL and lets the others proceed. Parallelism across cores adds little here, since the CPU is idle and more cores don't make the server answer faster.
Exercise
The generator-based scheduler earlier in this chapter runs tasks A and B with interleaved output. Is it parallel? Would giving it a computation-heavy task make the whole run finish sooner than running the tasks one after the other?
Show answer
It is concurrent but not parallel. Everything runs on one thread and one core, and only one line of code executes at any instant. A computation-heavy task would not finish sooner. Interleaving CPU work on a single core takes at least as long as running it sequentially, plus the small overhead of switching between tasks.