Skip to content
BIASED

Concurrency: threads, processes and asyncio

How a program does several things at once. Waiting against computing, threads and the GIL, the free-threaded 3.14t build, processes with concurrent.futures, asyncio coroutines and TaskGroup, races and locks.

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.

Threads and the GIL

A thread is an independent sequence of execution inside a process. It has its own call stack and shares everything else, including all objects, with the other threads. concurrent.futures.ThreadPoolExecutor keeps a pool of threads and hands out work. Its map works like the built-in map, but runs the calls in the pool's threads:

import time
from concurrent.futures import ThreadPoolExecutor
 
def fetch(name, delay):
    time.sleep(delay)              # releases the GIL while waiting
    return name
 
t0 = time.perf_counter()
with ThreadPoolExecutor(max_workers=3) as pool:
    shards = list(pool.map(fetch, ["a", "b", "c"], [0.3, 0.1, 0.2]))
print(shards, f"{time.perf_counter() - t0:.2f} s")
['a', 'b', 'c'] 0.31 s

The three waits overlapped. Results come back in the order of the inputs, whatever order the threads finish in, and leaving the with block waits for all of them.

The default build of CPython has one lock, the global interpreter lock (GIL). A thread must hold it to execute bytecode or touch Python objects. It exists because every instruction updates reference counts (see the topic How CPython runs code) and shared interpreter structures without other synchronization. One lock around everything is the cheapest way to keep them consistent, and most programs run a single thread anyway. Three rules follow.

  1. Only the thread holding the GIL executes bytecode.
  2. A thread releases the GIL around any call that may block: time.sleep, reading a file or a socket, waiting on a lock. Many C libraries also release it during long computations: NumPy in most array operations, hashlib on large inputs.
  3. A thread that keeps computing is asked to drop the GIL after the switch interval, 5 ms by default (sys.getswitchinterval()), so that other threads get a turn.

Now CPU-bound work. A countdown while n: n -= 1 is pure bytecode:

import time
from concurrent.futures import ThreadPoolExecutor
 
def spin(n):
    while n:
        n -= 1
 
def timed(label, f):
    t0 = time.perf_counter()
    f()
    print(f"{label:9} {time.perf_counter() - t0:.2f} s")
 
timed("1 thread", lambda: [spin(10_000_000) for _ in range(4)])
with ThreadPoolExecutor(max_workers=4) as pool:
    timed("4 threads", lambda: list(pool.map(spin, [10_000_000] * 4)))
1 thread  0.61 s
4 threads 0.60 s

Four threads were no faster than one. They took turns holding the GIL, so at any instant one core did all the work. In the default build, threads overlap waiting, not computing.

The free-threaded build

PEP 703 made the GIL optional. CPython can be built without it, as a separate free-threaded build whose executable is python3.14t. In 3.13 it was experimental. Since 3.14 it is officially supported but still optional: the ordinary python3.14 keeps the GIL. uv installs it with uv python install 3.14t. A script can ask which build it runs on:

import sys
 
print(sys._is_gil_enabled())

This prints True on the default build and False on python3.14t.

Without the GIL, something else has to keep reference counts correct. The free-threaded build uses biased reference counting: cheap updates for the thread that owns an object, atomic ones for the others. Many objects also carry their own small lock. The countdown script from the previous block, unchanged, run with python3.14t:

1 thread  0.61 s
4 threads 0.17 s

Now four threads were about 3.6 times faster than one, close to the four-fold ideal. This parallel time is the most sensitive number in the topic: it depends on how busy the other cores are, and in other runs, while the machine was busy with other work, it came out between 0.16 and 0.43 s. Run with the GIL switched back on (python3.14t -X gil=1), four threads were again about as slow as one.

The build has a price. Single-threaded code is a little slower: the 3.14 release notes give roughly 5–10 %, depending on platform and compiler. C extension modules must be built for this build and declare that they are safe without the GIL; importing one that does not turns the GIL back on for the whole process, with a warning. The experimental JIT is not available in it. And code that was correct only because the GIL happened to serialize it becomes visibly wrong, as the block on races will show.

Processes

A process has its own interpreter, its own memory and, in the default build, its own GIL. Several processes compute in parallel on any build. concurrent.futures.ProcessPoolExecutor has the same interface as the thread pool:

import time
from concurrent.futures import ProcessPoolExecutor
 
def spin(n):
    while n:
        n -= 1
    return n
 
if __name__ == "__main__":
    t0 = time.perf_counter()
    with ProcessPoolExecutor(max_workers=4) as pool:
        print(list(pool.map(spin, [10_000_000] * 4)))
    print(f"{time.perf_counter() - t0:.2f} s")
[0, 0, 0, 0]
0.24 s

That is on the default build, with the GIL, and the 0.24 s include starting four new interpreters. With the workers already running, the countdowns alone took about 0.18 s. Three rules come with processes.

  • Arguments and results are copied. They are serialized with pickle, sent through a pipe and rebuilt in the other process. A large list costs time proportional to its size. A function is sent by name, so it must be defined with def at the top level of a module; a lambda or a nested function cannot be pickled at all. Processes pay off when each task computes far longer than it spends moving data.
  • Starting a process costs time. A new interpreter starts and imports modules: tens of milliseconds. Reuse a pool for many tasks rather than one process per task.
  • The __main__ guard. On macOS and Windows a worker starts with spawn: a fresh interpreter that imports your main module to find the function. Since 3.14 Linux defaults to forkserver, which behaves the same way here. Without if __name__ == "__main__": each worker would start a pool of its own on import. Python stops that with a RuntimeError in each worker ("An attempt has been made to start a new process before the current process has finished its bootstrapping phase").

The lower-level module multiprocessing offers Process, Pool, queues and shared memory; concurrent.futures covers most needs with less code. Python 3.14 also adds InterpreterPoolExecutor, which runs tasks in several interpreters inside one process, each with its own GIL.

The machine-learning courses meet processes in data loading. PyTorch's DataLoader with num_workers > 0 starts worker processes that prepare batches while the model trains. That is why such scripts need the __main__ guard on macOS and Windows.

asyncio: one thread, many waits

Threads overlap waits, but each costs a stack and operating-system scheduling. A server with 10,000 open connections does not want 10,000 threads. asyncio overlaps waits inside one thread. Its pieces:

  • async def defines a coroutine function. Calling it does not run the body; it returns a coroutine object, a paused computation, as calling a generator function returns a generator (see the topic Iteration, comprehensions and generators).
  • await x inside a coroutine runs x until it completes and takes its result. If x has to wait for a timer or a socket, the coroutine is suspended right there and control goes back to the event loop.
  • The event loop keeps a queue of ready tasks. It runs each one until it reaches an await that must wait, then asks the operating system to wake it when the earliest timer expires or a watched socket is ready.
  • A task wraps a coroutine so that the loop runs it concurrently with others. asyncio.TaskGroup (3.11+) creates tasks with tg.create_task(...); leaving its async with block waits for all of them.
  • asyncio.run(main()) creates a loop, runs main() to completion and closes the loop.

The three shards again, now as tasks:

import asyncio
 
async def fetch(name, delay):
    print(f"{name} starts")
    await asyncio.sleep(delay)      # stands in for waiting on the network
    print(f"{name} done")
    return name
 
async def main():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(n, d)) for n, d in [("a", 0.3), ("b", 0.1), ("c", 0.2)]]
    print([t.result() for t in tasks])
 
asyncio.run(main())
a starts
b starts
c starts
b done
c done
a done
['a', 'b', 'c']

main creates three tasks, and nothing has run in them yet. When main waits at the end of the async with block, the loop runs the ready tasks in order. Each prints "starts", reaches await asyncio.sleep(...), sets a timer and gives control back. The loop then sleeps until 0.1 s and resumes b, at 0.2 s resumes c, at 0.3 s resumes a. With all three finished, the group lets main continue. The whole program took 0.30 s, the longest wait rather than the sum.

Switching happens only at await. Between two awaits a coroutine runs uninterrupted, which makes shared state much easier to reason about than with threads.

How to break asyncio

asyncio gives concurrency only if every task keeps returning to the loop. Three coroutines that wait for d seconds in different ways:

async def good(d):
    await asyncio.sleep(d)                   # gives control back to the loop
 
async def blocking(d):
    time.sleep(d)                            # holds the whole loop
 
async def offloaded(d):
    await asyncio.to_thread(time.sleep, d)   # the blocking call runs in a thread

The same three delays, 0.3, 0.1 and 0.2 s, measured four ways (asyncio.gather runs its arguments as concurrent tasks, like a small TaskGroup):

Code Time
for d in DELAYS: await good(d) 0.61 s
gather of three blocking 0.63 s
gather of three offloaded 0.31 s
gather of three good 0.30 s

The first row is the commonest mistake. await waits for its argument to finish, so awaiting coroutines one by one runs them in sequence. Concurrency comes from creating tasks first. The second row blocks the loop: time.sleep, requests.get or a long computation never returns control, and every other task stands still. Use asynchronous libraries for I/O, and asyncio.to_thread for a blocking call you cannot avoid.

A third surprise is failure. If one task in a TaskGroup raises, the group cancels the others and raises an ExceptionGroup when the block exits; except* (see the topic Files and exceptions) handles it:

import asyncio
 
async def fail():
    await asyncio.sleep(0.05)
    raise ValueError("bad batch")
 
async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            slow = tg.create_task(asyncio.sleep(1))
            tg.create_task(fail())
    except* ValueError as eg:
        print("caught:", eg.exceptions, "slow cancelled:", slow.cancelled())
 
asyncio.run(main())
caught: (ValueError('bad batch'),) slow cancelled: True

The whole run took about 0.05 s, not 1 s. asyncio is for I/O-bound work: a CPU-bound coroutine never reaches an await and starves every other task.

Races and locks

When threads share data, the result can depend on their timing: a race condition. The classic case is a shared counter. Four threads each add 1 to it 250,000 times, so it should end at 1,000,000:

import threading
 
counter = 0
 
def bump(n):
    global counter
    for _ in range(n):
        counter += 1               # read, add, write
 
threads = [threading.Thread(target=bump, args=(250_000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(counter)

dis (see the topic How CPython runs code) shows that counter += 1 is several instructions: LOAD_GLOBAL, LOAD_SMALL_INT, BINARY_OP (+=), STORE_GLOBAL. If another thread stores between this thread's load and store, its update is overwritten. Three runs of each variant:

Build and code Result
default build, counter += 1 1,000,000 in three runs of three
default build, counter = counter + one(), switch interval 1 µs 472,645, 570,149, 491,519
free-threaded build, counter += 1 291,937, 252,121, 294,240
either build, the update inside with lock: 1,000,000 every time

The first row is the trap. The default build switches threads only at certain points, such as function calls and the backward jumps of loops. counter += 1 has none between its load and its store, so on 3.14 it happens not to lose updates. Nothing in the language promises that. Put a call between the read and the write and switch often, and half the updates vanish. Remove the GIL, and even += 1 loses about three quarters of them.

The fix is a lock around the critical section, the read-modify-write:

counter = 0
lock = threading.Lock()
 
def bump(n):
    global counter
    for _ in range(n):
        with lock:                 # one thread at a time inside this block
            counter += 1

with lock: acquires the lock, waiting if another thread holds it, and releases it on exit, even on an exception. Better still, share less: give each thread its own data and combine results at the end, as pool.map does, or pass work through a queue.Queue, which does its own locking. A single built-in operation on one object, such as list.append or d[key] = value, is safe on both builds. A sequence of them, such as "check that a key is missing, then insert", is not.

asyncio has fewer races, but not none. A check and an update with no await between them are safe. A check, an await, then an update can interleave with another task; asyncio.Lock serves that case.

Choosing a tool

The kind of work and the build decide the tool:

Work Default build Free-threaded 3.14t
Waits (network, disk, timers), up to hundreds threads threads
Very many waits (thousands of connections) asyncio asyncio
CPU-bound Python code processes threads or processes
CPU-bound work inside C code that releases the GIL (NumPy, hashlib) threads threads
Tasks that must not share memory or crash each other processes processes

Whatever the tool, use a pool and reuse it, keep shared state small, and put a lock around every read-modify-write of what remains.

Look at what concurrency bought for computing: four cores gave a speed-up of about 3.6, and eight cores could give at most 8. The topic Writing fast Python showed a bigger lever, of the order of a hundred times, with no extra cores at all: run the loop in compiled code instead of in the interpreter. For numerical work that comes first, and parallelism comes on top; NumPy even releases the GIL inside most operations, so threads and arrays combine.

This closes the Under the hood module. The next topic, NumPy arrays, opens the scientific stack: what an array is in memory, a block of raw numbers with a dtype, a shape and strides, and why that one picture makes vectorized code fast.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

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