← All lessons
Python advanced · Lesson 10 of 11

Concurrency and asyncio

Most programs spend their time waiting: for a web page, a database, a file, a user. Concurrency means making progress on several tasks at once, so the waiting overlaps instead of adding up. Python has three main tools, and which to use depends on what the program waits for.

  • Threads (threading, concurrent.futures.ThreadPoolExecutor) run several functions in one program, sharing its memory. Good for work that waits on the network or disk (called I/O-bound).
  • Processes (multiprocessing, ProcessPoolExecutor) run separate copies of Python, each with its own memory, on different processor cores. Good for heavy calculation (CPU-bound).
  • asyncio runs many tasks in one thread, each handing control back whenever it waits. Good for thousands of network connections at once.

Why not threads for everything? CPython, the standard Python, has a GIL (global interpreter lock): only one thread runs Python code at a time. Threads still help with waiting, because a thread waiting on the network releases the lock, but they don't speed up pure maths. (Python 3.13 added an optional build without the GIL; it's still experimental.)

ThreadPoolExecutor.map is the simplest way to run a function on many inputs with a few threads. Here each task "waits" with time.sleep to stand in for a slow download: five tasks of 0.2 seconds finish in about 0.2 seconds, not 1.

import time
from concurrent.futures import ThreadPoolExecutor

def fetch(n):
    time.sleep(0.2)
    return n * n

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(fetch, range(5)))
print(results, time.perf_counter() - start < 0.6)
Prints
[0, 1, 4, 9, 16] True

When threads change shared data, two can interleave in the middle of an update and lose one of them. That's a race condition. Protect shared changes with a threading.Lock (with lock:), or better, avoid sharing: give each task its own data and combine the results at the end, as pool.map does.

asyncio uses two keywords. async def defines a coroutine, a function that can pause; await pauses it until something it's waiting for is ready, letting other coroutines run meanwhile. asyncio.run() starts the whole thing, and asyncio.gather() runs several coroutines concurrently.

import asyncio

async def brew(drink, seconds):
    await asyncio.sleep(seconds)
    return f"{drink} ready"

async def main():
    results = await asyncio.gather(brew("tea", 0.2), brew("coffee", 0.1))
    print(results)

asyncio.run(main())
Prints
['tea ready', 'coffee ready']

Both drinks brew at the same time, and gather returns the results in the order the tasks were given, not the order they finished. The catch with asyncio: everything in the chain must cooperate. A normal blocking call like time.sleep() or a plain requests.get() inside a coroutine freezes every task. Use the async versions (asyncio.sleep, an async HTTP library) or hand blocking work to a thread with asyncio.to_thread().

Measure before reaching for concurrency. It adds complexity, and plenty of "slow" programs are slow because of one bad loop, which the next lesson covers.

Practice

A script downloads 200 web pages one after another and spends nearly all its time waiting. What's the simplest speed-up?

More info

Quick reference

I/O-bound / CPU-boundWaiting on network or disk / busy calculating.
ThreadPoolExecutor / ProcessPoolExecutorRun tasks in threads (for waiting) / processes (for maths).
GILIn standard CPython, one thread runs Python code at a time.
race condition / LockThreads interleaving and losing updates / the guard against it.
async def / awaitA coroutine / pause until ready, letting others run.
asyncio.run / gather / to_threadStart / run concurrently / push blocking work to a thread.

Related courses