Back to Explore
GuideVibeFix editorialUpdated Nov 23, 2026

Picking the Right Python Concurrency Model: threading vs multiprocessing vs asyncio

Python offers three concurrency models — threading, multiprocessing, and asyncio — and the wrong pick adds bugs without adding speed. Measured on a fictional bookshop order program: threads and asyncio both cut five I/O waits from 1.00 s to 0.20 s, threads match sequential code on CPU work while processes speed up, plus a shared-counter race, timeouts, and a decision table. Standard library only, Python 3.12.3.

Real photo: a laptop screen showing lines of code

A vibe project gets slow: five orders arrive at once, each one takes 0.2 seconds to fetch, and fetching them one by one takes a full second; fetch them concurrently and all five come back in 0.2 seconds. But switch to a pure computation task and threads stop helping at all — only processes speed it up. Python offers three concurrency models — threading, multiprocessing, and asyncio — and picking the wrong one not only fails to speed things up, it adds bugs that are hard to track down. This guide uses a fictional small bookshop order-processing program (titles, prices, and orders are all demo data) to explain the three models: first decide whether the task waits on I/O or burns CPU, then pick the tool. All code uses only the Python standard library, was actually run on Python 3.12.3, and every output quoted is a real measured result; timing numbers vary by machine, so this guide quotes them as "in this run" and draws conclusions from relative speed, not absolute milliseconds.

One sentence first, from the official Python threading documentation: "In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once." If you want a program to make better use of a multi-core machine, the same page advises "you are advised to use multiprocessing". Once that sentence clicks, everything else follows: threads are good at waiting, processes are good at computing, and asyncio is a different way of being good at waiting.

Two words to keep apart: concurrency and parallelism

Concurrency means handling several tasks within the same period of time — not necessarily doing them at the same instant. Parallelism means literally doing them at the same instant, which needs several CPU cores. Five orders at 0.2 seconds each take 1 second sequentially and 0.2 seconds concurrently: the waits overlap, but no five CPUs are working at once. That is concurrency, not parallelism. Four chunks of pure computation handed to four processes, each occupying its own core, is parallelism. Many selection mistakes come from mixing the two words up: using a concurrency tool for a parallelism problem, or the other way round.

To tell which kind of task you have, ask one question: when the program is slow, is the CPU working or waiting? Waiting on a network response, a disk read, or user input means I/O-bound. Doing arithmetic, parsing, compression, or running a model means CPU-bound. The next two sections look at I/O tasks first, then CPU tasks — the difference is obvious.

Sequential execution: five orders take 1 second

First the plainest version: fetch one order at a time, waiting 0.2 seconds per fetch (time.sleep stands in for a network or database wait):

import time

def fetch_order(i):
    """Simulate one I/O wait: wait 0.2 s, then return an order."""
    time.sleep(0.2)
    return f"order{i}"

orders = [fetch_order(i) for i in range(5)]

Output:

Fetched sequentially:  ['order0', 'order1', 'order2', 'order3', 'order4']
Sequential time: 1.00 seconds

Five waits in a row add up to 5 × 0.2 = 1.00 seconds. While waiting, the CPU does nothing at all — it just idles. That is the signature of an I/O-bound task: the bottleneck is waiting, not computing power. If the waits can overlap, total time drops from "count × single wait" to "about one wait".

threading: while one thread waits, another runs

Threads solve it by waiting in parallel: five threads each wait their own 0.2 seconds, the waits overlap, and the total lands near 0.2 seconds. concurrent.futures.ThreadPoolExecutor is the least-effort way to write it — no manual thread start-up or clean-up:

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=5) as pool:
    orders = list(pool.map(fetch_order, range(5)))

Output:

Fetched with thread pool:  ['order0', 'order1', 'order2', 'order3', 'order4']
Thread pool time: 0.20 seconds

The same five orders now take 0.20 seconds instead of 1.00 — five times faster. Two details matter: first, pool.map returns results in input order, so you never have to track which one came back first; second, the thread switch happens while waiting — when one thread calls time.sleep and blocks, the GIL is released and another thread runs. That is exactly why threads work for I/O: while waiting, no CPU is needed at all. Threads share one memory space, so passing data between them is the easiest of the three models; the price is that shared state needs locks of your own, as the counter example below shows.

More threads is not always better. I/O tasks can use far more threads than CPU cores (dozens is common), because threads spend most of their time waiting; but every thread takes stack memory, and a few thousand threads will eat memory first. If concurrency has to reach thousands or tens of thousands, threads are the wrong tool — that is where the next section's asyncio comes in.

asyncio: concurrent waiting without threads

asyncio takes a different approach: one thread, one event loop, taking turns advancing several tasks. When a task waits on I/O it yields control (await), the loop moves on to the next task, and when the I/O returns, the loop comes back. Functions become async def and waits become await asyncio.sleep:

import asyncio

async def afetch_order(i):
    await asyncio.sleep(0.2)
    return f"order{i}"

async def main_io():
    orders = await asyncio.gather(*(afetch_order(i) for i in range(5)))
    print("Fetched with asyncio: ", list(orders))

asyncio.run(main_io())

Output:

Fetched with asyncio:  ['order0', 'order1', 'order2', 'order3', 'order4']
asyncio time: 0.20 seconds

Again 0.20 seconds — a tie with the thread pool. But the cost behind it is completely different: asyncio runs on a single thread, so there is no thread-switching overhead and no shared-memory locking problem; the price is that code must be written in async style — every wait needs await, plain functions cannot await, and ordinary synchronous libraries (such as requests or time.sleep) block the whole event loop the moment they are used inside an async function. The docs describe asyncio as task-level concurrency "without requiring the use of multiple operating system threads" — it saves threads, not the waiting itself.

A common misunderstanding is that "asyncio is faster than threads". For I/O tasks the two take about the same time (both measured 0.20 seconds here); asyncio wins on scale and resource use, threads win on ordinary-looking code and direct use of synchronous libraries. In a new project with heavy I/O concurrency and async versions of the libraries you need, pick asyncio; if you just want to parallelise existing synchronous code with the smallest possible change, pick threading.

CPU work: threads do not help, processes do

Switch to pure computation and the picture flips. Below are four identical computations (each sums the squares of 8 million numbers), run sequentially, with a thread pool, and with a process pool:

def cpu_work(n):
    """Pure CPU work: sum of squares."""
    return sum(i * i for i in range(n))

Output (in this run, on a VM with about 1.5 shared CPU cores):

Sequential CPU time: 2.60 seconds, results: 4 sets
Thread CPU time: 2.43 seconds, results: 4 sets
Process CPU time: 1.58 seconds, results: 4 sets
All three results identical:  True
Single sum of squares = 170666634666668000000

The thread pool's 2.43 seconds is basically the same as sequential's 2.60 — four threads queue up for the GIL and only one computes at a time, pure wasted effort. The process pool's 1.58 seconds is genuinely faster, but only by about forty percent, because this machine has only about 1.5 shared CPU cores to compute on; on a machine with four or more cores the process pool's advantage grows. Judge by the relative pattern, not the absolute numbers: for CPU work, threads are about equal to sequential, and processes speed up with core count. The chart below plots the three I/O timings; the CPU conclusion is written under it.

Bar chart: fetching 5 orders takes 1.00 seconds sequentially and 0.20 seconds with either a thread pool or asyncio; for CPU work threads are about equal to sequential while a process pool speeds up with core count

The process pool code is almost identical to the thread pool — just swap ThreadPoolExecutor for ProcessPoolExecutor:

from concurrent.futures import ProcessPoolExecutor

with ProcessPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(cpu_work, [8_000_000] * 4))

But the costs of processes are worth knowing: first, starting a process is much slower than starting a thread, so if each task is tiny, start-up costs more than the computation saved; second, processes do not share memory, so arguments and results travel through serialisation (pickle) — passing big objects is expensive, and things that cannot be pickled (open files, database connections) cannot be passed at all; third, debugging is harder, because a child process crash does not surface directly in the main process. The rule of thumb: a single task should take at least a few hundred milliseconds to be worth putting in a process pool; for tasks of a few milliseconds, a process pool is slower than sequential code.

Shared state: without a lock, counts get lost

Threads sharing memory is an advantage and the biggest trap at the same time. Eight threads incrementing the same counter, 50,000 times each, should end at 400,000. The demo deliberately splits "read–modify–write" into three steps with a yield in the middle, to widen the race window:

import threading

counter = [0]
def bump_no_lock(n):
    for _ in range(n):
        old = counter[0]
        time.sleep(0)
        counter[0] = old + 1

Output:

8 threads x 50000, no lock:  50000 (expected 400000)
8 threads x 50000, with lock:  400000 (expected 400000)

Without a lock only 50,000 survives — the eight threads read the same old value almost every round and overwrite each other, leaving roughly one thread's worth. Wrap the read–modify–write in a threading.Lock so the threads queue up, and the result is correct:

lock = threading.Lock()
def bump_with_lock(n):
    for _ in range(n):
        with lock:
            counter2[0] += 1

Two things to note: first, how many counts get lost changes every run — in this run it was 50,000, on another machine or another run it will differ — which is exactly how race bugs behave: "it passed in testing" does not mean the bug is absent; second, locks are not free — the longer the locked section, the more concurrency degrades. Avoid shared mutable state when you can: let each thread compute its own part and combine the results afterwards (as pool.map does by returning each result), which is cleaner than locking. asyncio has no race of this kind because it runs on one thread; multiprocessing has none either because processes do not share memory — the shared-state headache belongs to threading alone.

asyncio timeouts: give up when it takes too long

One of the most useful small tools in concurrent code is the timeout: if one I/O wait drags on, stop waiting. In asyncio, wrap the call in asyncio.wait_for and a timeout raises TimeoutError:

async def slow_fetch():
    await asyncio.sleep(2)
    return "slow order"

try:
    await asyncio.wait_for(slow_fetch(), timeout=0.5)
except TimeoutError:
    print("Timed out after 0.5 s: gave up waiting, returned a default")

Output:

Timed out after 0.5 s: gave up waiting, returned a default
Got it:  order99

A request that would have taken 2 seconds was abandoned at 0.5 seconds, and the program was not held up by it; a normal request (0.2 seconds) then returned fine. This matters most when calling third-party APIs: concurrency without timeouts turns "one slow request holds up everything" from a sequential risk into a parallel one. threading has no equally handy timeout idiom — usually you reach for future.result(timeout=...) from concurrent.futures, which works the same way but reads more verbosely.

Four everyday vibe-project scenarios, matched to a model

Theory done — here are the four most common vibe-project scenarios, matched directly to a model. First, aggregating several third-party APIs: a "today's AI news digest" page that fetches 10 RSS feeds at once and renders the combined result. This is textbook I/O-bound, with no dependencies between requests — pick threading, the lowest-effort option. The usual synchronous libraries (requests, feedparser) go straight into a thread pool with no async rewrite; give each source a timeout so one dead source cannot hold up the whole page.

Second, a web service holding thousands of long-lived connections: the backend of an AI chat room keeping several thousand WebSocket connections open, waiting for users to type. Threads would run out of memory first — thousands of threads cost stack memory even while idle, and most of them are just waiting for a message. Pick asyncio: a single-threaded event loop holds thousands of connections comfortably. The price is that database drivers and HTTP clients must all switch to async versions, because one synchronous call blocks the whole loop — weigh the rewrite cost against the gain.

Third, batch-processing user uploads: a "watermark 100 images" feature where each image takes a few hundred milliseconds of computation. Image processing is pure CPU work, so threads do not help — pick multiprocessing with a pool sized to the core count. And have results flow back to the main process before writing to the database; do not let each child process write to the database itself, or several processes writing to the same SQLite file will lock each other out, slow everything down, or error out.

Fourth, a scheduled job that mixes computing and waiting: a daily "yesterday's data report" that pulls data from the database (I/O wait), computes aggregate metrics (CPU burn), then sends an email (I/O wait). Do not combine two models up front for a mixed job like this: first measure which phase dominates. If fetching the data takes eighty percent of the time, a thread pool alone is enough; if computing the metrics takes eighty percent, a process pool alone is enough. Only when the two phases cost about the same, and the workload is large, is a combination such as a process pool running asyncio worth it. For most vibe-project scheduled jobs, one model does the job.

Choosing: ask about the task first, then pick the tool

Here is the decision table in short form. Ask whether the task waits or computes, then look at scale and existing code:

I/O-bound work (waiting on the network, a database, or files) with concurrency in the tens to hundreds: use threading — the smallest change, and existing synchronous libraries work as-is. I/O-bound work with concurrency in the thousands, or a service written from scratch: use asyncio — the cheapest on resources, but the whole codebase must be async, with no synchronous library mixed in. CPU-bound work (arithmetic, parsing, compression, running a model): use multiprocessing — faster with more cores, but each task must be big enough and its arguments must be serialisable. Tasks that are tiny and numerous, where no model pays off: do not parallelise at all — sequential code is often fastest, because concurrency itself has overhead. Five 1-millisecond tasks run through a process pool take longer than running them in order.

Three more rules of thumb for the final check: first, mixed jobs (compute a while, wait a while) can combine models — a process pool with asyncio inside each process, for example — but confirm which side the bottleneck is on before combining; most of the time one model is enough. Second, Python 3.13 introduced free-threaded builds that can switch the GIL off, but the default build still ships with the GIL, and the conclusions in this guide were measured on Python 3.12.3, where they still hold; do not choose based on free threading until it becomes the default. Third, write the choice down in the project docs: code that mixes two concurrency models without saying why is some of the hardest code for the next person to take over.

The five traps beginners hit most

Trap one: calling a synchronous blocking function inside asyncio. Writing time.sleep(2) or requests.get(...) inside an async function blocks the entire event loop — no other task moves at all. Use await asyncio.sleep and an async HTTP library, or hand the synchronous call to asyncio.to_thread and let a thread run it.

Trap two: passing something unpicklable to a process pool. A process pool moves arguments through pickle, and database connections, open files, and objects holding locks cannot cross that boundary — it errors out directly. The fix is to create the connection again inside the child process instead of passing it in from the parent.

Trap three: sharing mutable state between threads without a lock. Counters, lists, and dictionaries can all lose data, and the loss comes and goes; combine partial results where possible, and where sharing is unavoidable, lock it, keeping the locked section as small as you can.

Trap four: forgetting to join, or forgetting to shut the pool down. If the main thread ends without waiting for its children, the program may exit and silently drop unfinished work; the with ThreadPoolExecutor(...) as pool form waits for every task when the with block exits, which is safer than manual join.

Trap five: exceptions swallowed by concurrency. An exception raised in a thread does not bubble up to the main thread on its own — pool.map only raises it when results are collected; in asyncio, gather raises the first exception by default, and you need return_exceptions=True to inspect each one. Error handling on concurrent paths needs its own tests, not just the happy path.

Wrap-up and checklist

In one sentence: wait on I/O with threads or asyncio, burn CPU with processes, and do not parallelise small tasks at all. Before shipping, run through this checklist: is the task type clear (waiting or computing)? For an I/O task, did you pick threads or asyncio, and write down why? For a CPU task going into a process pool, did you confirm each task is big enough and its arguments serialisable? Is every piece of shared mutable state locked, or replaced by combining partial results? Are timeouts in place? Was error handling tested on the concurrent path itself, not just the happy path? Once the choice is made, write it into the project docs so nobody has to guess it again later. The full demo code lives in the draft folder as demo242_zh.py, and the English rerun script is rerun_en_demo242_g1.py; the two runs agree on the numbers (timings aside, which vary by machine).

Boundaries with already-published guides: this guide compares threading, multiprocessing, and asyncio and how to choose between them; it does not teach asyncio syntax from scratch (a separate asyncio basics guide covers that), it does not cover database concurrency and transactions (a separate guide on concurrency and transactions covers the ordering scenario with Prisma and Drizzle), and it does not cover profiling tools (cProfile, timeit, and friends are outside this guide's scope). Each of the three covers its own stretch, with no overlap.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles