Skip to content
BIASED

Concurrency: threads, processes and asyncio

Block 1 of 8~2 min

Waiting and computing

The topic Writing fast Python made code faster on one processor core: measure first, choose the right data structure, cut interpreter overhead, let built-ins and NumPy run the loop in C. Every one of those speed-ups used a single core. The Apple M1 that the timings in this course come from has eight. And a program also spends time on things that are not computation at all: waiting for a file, a database, a web server.

This topic is about doing several things at once. Two words get mixed up here, so fix them first.

  • Concurrency is structuring a program as several tasks whose lifetimes overlap. On one core the tasks take turns.
  • Parallelism is executing several things at the same instant, on several cores.

A concurrent program on one core can still finish sooner, if its tasks wait: one task's waiting is another's working time. Only parallelism speeds up pure computation. That splits work into two kinds, and the kind decides the tool.

  • I/O-bound work spends its time waiting for something outside the processor: the network, a disk, a database, a timer. More cores do not help; overlapping the waits does.
  • CPU-bound work keeps a core busy: parsing, numerical loops in Python, compressing. Only more cores help, and only if the work can be split.

Here is the baseline for waiting. Three dataset shards take 0.3, 0.1 and 0.2 s to arrive, and the program fetches them one after another:

import time
 
def fetch(name, delay):
    time.sleep(delay)              # stands in for downloading a shard
    return name
 
t0 = time.perf_counter()
shards = [fetch(n, d) for n, d in [("a", 0.3), ("b", 0.1), ("c", 0.2)]]
print(shards, f"{time.perf_counter() - t0:.2f} s")
['a', 'b', 'c'] 0.62 s

The times in this topic come from CPython 3.14.7 on that M1 under macOS; on your machine they will differ. The processor was idle for almost all of these 0.62 s. Python has three tools for doing better: threads, processes and asyncio.

Answers are saved on the server and tied to this browser until you sign in.