🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Threads, Processes, or asyncio: Choosing in Python

Python ConcurrencyđŸŸĸ Free Lesson

Threads, Processes, or asyncio: Choosing in Python

Concurrency in Python fails in predictable ways: a process pool that raises PicklingError on a closure, a thread pool with two hundred workers hammering one database, an async function that blocks the event loop and makes everything slower than sequential code. All three come from the same mistake — choosing an executor before classifying the work. The rule of thumb is short: waiting on the network belongs in threads or asyncio, pure computation belongs in processes, and anything that shares mutable state needs an explicit plan regardless of executor.

What You'll Learn

  • 1Classify a workload as I/O-bound or CPU-bound and pick the matching executor
  • 2Explain what the GIL does and does not prevent
  • 3Write worker functions that survive pickling in a process pool
  • 4Bound concurrency with worker counts, timeouts, and semaphores

The GIL, in the only terms that matter for this choice

The global interpreter lock lets exactly one thread execute Python bytecode at a time. It is released during most blocking operations — socket reads, file writes, time.sleep, many C extensions — which is why threads speed up I/O-bound work even though they never run Python code in parallel. It is held during pure Python arithmetic, which is why a tight loop over a list gets no faster with threads and does get faster with separate processes.

Processes sidestep the lock by running independent interpreters with their own memory, and pay for it with startup cost, a higher memory footprint, and a hard requirement that every argument and return value cross a pipe in pickled form. asyncio is different in kind: it is cooperative single-threaded scheduling, so it scales to tens of thousands of idle connections while one thread does the work, but a single blocking call stalls every task in the loop.

WorkloadExecutorWhyWatch out for
HTTP calls, database queries, file readsThreadPoolExecutorBlocking calls release the GILWorker count, connection pool size
Parsing, compression, numeric loopsProcessPoolExecutorReal parallelism across coresPicklability of arguments and results
Thousands of mostly idle socketsasyncioCheap tasks, one threadAny blocking call inside a coroutine
Mixed I/O and CPU in one pipelineasyncio plus a process poolEach stage gets the right toolOrdering and error propagation

Fan-out with ThreadPoolExecutor

Threads shine when you have many independent blocking calls. Submit jobs, keep a mapping from future to input so the result can be labelled, and iterate with as_completed so you process answers as they arrive instead of waiting for the slowest one first.

python
from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED
import urllib.request


def fetch(url: str, timeout: float = 5.0) -> tuple[str, int]:
    with urllib.request.urlopen(url, timeout=timeout) as response:
        return url, response.status_code


urls = [
    "https://example.com",
    "https://example.org",
    "https://example.net",
]

with ThreadPoolExecutor(max_workers=8) as pool:
    futures = {pool.submit(fetch, url): url for url in urls}
    done, pending = wait(futures, timeout=10, return_when=FIRST_COMPLETED)
    for future in done:
        try:
            url, status = future.result()
            print(f"{url} -> {status}")
        except Exception as exc:
            print(f"{futures[future]} failed: {type(exc).__name__}: {exc}")
    for future in pending:
        future.cancel()

Two habits worth forming. Always call future.result() inside a try, because exceptions surface there rather than at submission. And size max_workers from the downstream limit — a pool of 64 threads against a database configured for 10 connections converts a latency problem into a queueing problem.

Real parallelism with ProcessPoolExecutor

CPU-bound work needs separate interpreters. The catch is that the callable and its arguments must be picklable, which rules out lambdas, locally defined functions, and bound methods of unpicklable objects. Define the worker at module level and pass plain data.

python
from concurrent.futures import ProcessPoolExecutor
import os
import zlib


def compress_chunk(chunk: bytes) -> int:
    return len(zlib.compress(chunk, 6))


if __name__ == "__main__":
    chunks = [bytes(250_000) for _ in range(40)]
    with ProcessPoolExecutor(max_workers=os.cpu_count()) as pool:
        sizes = list(pool.map(compress_chunk, chunks, chunksize=4))
    print(sum(sizes))

chunksize matters more than it looks: each task crosses a process boundary, so handing work over in batches amortises the pickling cost. On Windows the guard if __name__ == "__main__" is mandatory, because child processes re-import the main module and would otherwise start the pool recursively. Two further arguments earn their place in real services: initializer plus initargs run once per worker to load configuration or open a connection, and max_tasks_per_child recycles a worker after a fixed number of jobs to contain memory leaks in long-running pools.

Fan-out with asyncio when connections outnumber threads

When the count of concurrent waits is in the thousands, threads become expensive because each carries a stack. asyncio.gather runs the coroutines cooperatively in one thread, and asyncio.Semaphore is the tool that turns "launch everything at once" into controlled fan-out.

python
import asyncio
import aiohttp

LIMIT = asyncio.Semaphore(20)


async def fetch(session: aiohttp.ClientSession, url: str) -> tuple[str, int]:
    async with LIMIT:
        async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as resp:
            return url, resp.status


async def main(urls: list[str]) -> None:
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(fetch(session, u)) for u in urls]
        results = await asyncio.gather(*tasks, return_exceptions=True)
    for item in results:
        print(item if isinstance(item, Exception) else item)


asyncio.run(main(["https://example.com", "https://example.org"]))

Note the semaphore is acquired inside the task. Gathering unbounded tasks that each immediately block on a lock still allocates every task object up front; for very large job lists, feed the queue with a bounded worker pool instead of creating one task per item.

Mixing the two: the pattern that keeps bite

A realistic service blocks on a database, waits on an HTTP API, and then crunches numbers. Running the CPU step directly inside the event loop stalls every other request, so hand it to a process pool through loop.run_in_executor, which is the standard bridge between the two worlds.

python
import asyncio
from concurrent.futures import ProcessPoolExecutor


def rank(features: list[float]) -> list[float]:
    return sorted(features, key=lambda f: -f)


async def score(payload: list[list[float]]) -> list[list[float]]:
    loop = asyncio.get_running_loop()
    with ProcessPoolExecutor(max_workers=2) as pool:
        futures = [loop.run_in_executor(pool, rank, row) for row in payload]
        return await asyncio.gather(*futures)


print(asyncio.run(score([[3.0, 1.0], [9.0, 4.0]])))

Creating the pool inside the request is shown for clarity; in a real service build one pool at startup and share it, because process creation dwarfs the cost of the work.

Backpressure, before the traffic arrives

Every concurrency bug that reaches production is a queue that grew without a limit. If the producer is faster than the consumer — a crawler feeding a parser, a web hook receiver feeding a database writer — then unbounded submission converts a slow dependency into an out-of-memory crash. Bounded concurrency is the fix, and there are three places to put the bound, each with a different failure mode.

Put it in the executor: max_workers caps how many jobs run, but submitted tasks still queue internally, so the list of futures can grow arbitrarily. Put it in a semaphore acquired before submitting, and excess work waits at the source where you can still time it out. Put it in a bounded queue with a fixed number of consumer threads, and a full queue pushes back on the producer, which is usually the behaviour a service actually wants.

Whichever you choose, decide what happens when the limit is reached: block, reject with an error, or drop with a metric. Silently buffering is the only wrong answer, because it moves the failure from a visible rejection to an invisible latency spike that surfaces minutes later as a timeout somewhere else.

Timeouts, cancellation, and the errors that get lost

A future that never finishes holds a worker forever, so every blocking call needs a deadline: future.result(timeout=...) for threads, asyncio.wait_for for coroutines, and urllib's own timeout for the socket layer. Cancelling a submitted future only works if it has not started; once a worker is running you can only abandon it, which is why timeouts must be enforced at the source rather than by cancelling the handle.

Exceptions deserve the same discipline. gather without return_exceptions=True raises the first failure and leaves the rest running as orphans, while as_completed never surfaces a failure you did not ask for. Decide explicitly whether one bad URL should abort the batch, and write that choice into the call.

Common Mistakes

Using processes for I/O-bound work because they feel more parallel

Fix: Threads release the GIL while waiting, so they are faster and far cheaper for network and disk work

Passing a lambda or a nested function to ProcessPoolExecutor

Fix: Move the worker to module level and pass only picklable data as arguments

Setting max_workers to os.cpu_count() for a thread pool that talks to a database

Fix: Size the pool from the downstream connection limit, not from the CPU count

Calling a blocking library inside an async request handler

Fix: Wrap it with loop.run_in_executor, or use the async client the library provides

Creating a fresh executor for every request

Fix: Build one executor at startup and reuse it; process and thread creation costs dominate short tasks

Best Practices

  • Classify the workload out loud before choosing an executor: waiting, computing, or idling
  • Give every blocking call a timeout and every gather an explicit error policy
  • Keep worker functions module-level, small, and free of shared mutable state
  • Match concurrency to the slowest downstream dependency rather than to the CPU count
  • Benchmark the sequential version first, then measure the parallel version; a speedup you have not measured is a hypothesis

Interview Questions

Q1: Why do threads help with I/O if the GIL only lets one thread run Python at a time?

Blocking operations such as socket reads release the GIL, so while one thread waits on the network another thread runs Python code. Throughput improves even though Python bytecode never executes in parallel.

Q2: What breaks when you submit a lambda to a process pool?

Pickling. Lambdas and locally defined functions have no importable qualified name, so the child process cannot reconstruct them. The fix is a module-level function with plain data arguments.

Q3: ThreadPoolExecutor or asyncio for 10,000 mostly idle connections?

asyncio, because a task costs far less memory and scheduling overhead than an OS thread. Threads become attractive when the waits involve blocking third-party libraries with no async variant.

Q4: How do you stop one slow task from stalling a batch?

Enforce a deadline at the source with future.result(timeout), asyncio.wait_for, or the client library's own timeout, and decide whether the batch fails or degrades when a deadline expires.

Key Takeaways

  • Classify first: I/O waits in threads or asyncio, pure computation in processes, idle connections in asyncio
  • The GIL blocks parallel Python bytecode but not blocking calls, which is why threads remain the right tool for network work
  • Process pools require picklable module-level workers and a __main__ guard on Windows
  • Bound concurrency with worker counts, semaphores, and timeouts so a burst cannot exhaust the dependency downstream
  • Bridges matter: run CPU work through loop.run_in_executor instead of blocking the event loop
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement