Threads, Processes, or Async: Choosing Correctly

Threads, Processes, or Async: Choosing Correctly in Python: Python gives you three concurrency models, and picking the wrong one makes your program slower…

Concept Explanation

Python gives you three concurrency models, and picking the wrong one makes your program slower rather than faster. The choice is not a matter of taste — it is determined by one question:

Is your bottleneck the CPU, or is it waiting?

The GIL, Briefly

CPython's Global Interpreter Lock allows only one thread to execute Python bytecode at a time. This is why threads do not speed up computation: four threads doing arithmetic take turns on one core.

The crucial detail is that the GIL is released during I/O. While a thread waits on a network response or a disk read, other threads run. So threads help enormously with waiting and not at all with computing.

The Decision

WorkloadUseWhy
Network requests, database queries, file I/OThreads or asyncGIL is released while waiting
Maths, image processing, parsing, compressionProcessesEach process has its own GIL
Thousands of concurrent connectionsAsyncNo thread stack per connection
A mixAsync for I/O + a process pool for CPUCombine them

A one-line diagnostic: if your program pegs one CPU core at 100%, it is CPU-bound and needs processes. If CPU usage is low while the program is slow, it is I/O-bound and needs threads or async.

Threads

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=16) as pool:
    results = list(pool.map(fetch_url, urls))

Cheap to create, share memory directly, and limited by the GIL for computation. Sharing memory is also the danger: two threads incrementing the same counter can lose updates, because counter += 1 is three bytecodes, not one. Use threading.Lock around shared mutable state.

Processes

from concurrent.futures import ProcessPoolExecutor

with ProcessPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(heavy_computation, chunks))

True parallelism across cores. The costs are real: starting a process takes tens of milliseconds, and every argument and return value is pickled and copied between processes. So a process pool only wins when each task does enough work to dwarf that overhead — roughly, more than a few milliseconds each.

Three constraints catch people: the function must be defined at module level (lambdas cannot be pickled), the arguments must be picklable, and on Windows and macOS the entry point must be guarded with if __name__ == "__main__": or you get infinite process spawning.

Async

async def main():
    async with httpx.AsyncClient() as client:
        results = await asyncio.gather(*[client.get(u) for u in urls])

One thread, one event loop, cooperative multitasking. Each await is a point where the task voluntarily yields control while waiting. Because there are no thread stacks, ten thousand concurrent connections is routine — a thread pool would need ten thousand stacks at roughly 8 MB of virtual address space each.

The catch is that async is all or nothing. One blocking call — time.sleep, requests.get, a synchronous database driver — freezes the entire event loop, including every other task. You need async-native libraries throughout: httpx or aiohttp instead of requests, asyncpg instead of psycopg2, aiofiles instead of open.

If you must call blocking code, hand it to a thread:

result = await asyncio.to_thread(blocking_function, arg)

Choosing max_workers

TypeSensible default
Threads (I/O)10–50; scale with latency, not cores
Processes (CPU)os.cpu_count(), or minus one to stay responsive
AsyncNo worker count — use a Semaphore to bound concurrency

More threads than the downstream service can handle is a self-inflicted denial of service. Bound it.


Code Example #1 (Basic)

The same two workloads under all three models.

import math
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

TASKS = 8


def io_task(n: int) -> int:
    """I/O-bound: waiting, not computing. The GIL is released here."""
    time.sleep(0.25)
    return n


def cpu_task(n: int) -> float:
    """CPU-bound: pure computation. The GIL is held throughout."""
    return sum(math.sqrt(i) * math.sin(i) for i in range(1, 900_000))


def benchmark(label, fn, executor_cls=None, workers=None):
    start = time.perf_counter()
    if executor_cls is None:
        [fn(i) for i in range(TASKS)]
    else:
        with executor_cls(max_workers=workers) as pool:
            list(pool.map(fn, range(TASKS)))
    elapsed = time.perf_counter() - start
    print(f"  {label:<26} {elapsed:>6.2f} s")
    return elapsed


if __name__ == "__main__":          # required on Windows and macOS
    print("=== I/O-BOUND (8 tasks, 0.25s wait each) ===")
    seq = benchmark("sequential", io_task)
    thr = benchmark("ThreadPoolExecutor(8)", io_task, ThreadPoolExecutor, 8)
    proc = benchmark("ProcessPoolExecutor(8)", io_task, ProcessPoolExecutor, 8)
    print(f"  -> threads {seq / thr:.1f}x faster; processes {seq / proc:.1f}x "
          f"but with far more overhead\n")

    print("=== CPU-BOUND (8 tasks of heavy maths) ===")
    seq = benchmark("sequential", cpu_task)
    thr = benchmark("ThreadPoolExecutor(8)", cpu_task, ThreadPoolExecutor, 8)
    proc = benchmark("ProcessPoolExecutor(4)", cpu_task, ProcessPoolExecutor, 4)
    print(f"  -> threads {seq / thr:.2f}x (NO gain -- the GIL serialises them)")
    print(f"  -> processes {seq / proc:.1f}x (real parallelism across cores)\n")

    print("The whole lesson: threads for waiting, processes for computing.")

The thread row under the CPU-bound heading is the important one. It comes out at roughly 1.0× — sometimes slightly worse than sequential, because of the cost of switching between threads that cannot actually run in parallel.

Code Example #2 (Intermediate)

Async with bounded concurrency, the blocking-call trap, and a race condition.

import asyncio
import math
import threading
import time
from concurrent.futures import ProcessPoolExecutor


# ==================== Async with a concurrency bound ====================
async def fetch(session_id: int, semaphore: asyncio.Semaphore) -> dict:
    """Simulates an HTTP call. The Semaphore caps how many run at once."""
    async with semaphore:                       # never more than N in flight
        await asyncio.sleep(0.2)                # async sleep -- yields the loop
        return {"id": session_id, "status": 200}


async def fetch_all(count: int, max_concurrent: int) -> list:
    semaphore = asyncio.Semaphore(max_concurrent)
    tasks = [fetch(i, semaphore) for i in range(count)]
    return await asyncio.gather(*tasks, return_exceptions=True)


# ==================== The blocking-call trap ====================
async def good_task(name: str) -> str:
    await asyncio.sleep(0.3)                    # cooperative: yields
    return name


async def bad_task(name: str) -> str:
    time.sleep(0.3)                             # BLOCKING: freezes the whole loop
    return name


async def offloaded_task(name: str) -> str:
    # The correct escape hatch for unavoidable blocking code
    await asyncio.to_thread(time.sleep, 0.3)
    return name


# ==================== Async + a process pool for CPU work ====================
def crunch(n: int) -> float:
    return sum(math.sqrt(i) for i in range(1, 600_000))


async def mixed_workload() -> tuple:
    loop = asyncio.get_running_loop()
    with ProcessPoolExecutor(max_workers=3) as pool:
        # I/O in the event loop, CPU in separate processes, both at once
        io_part = fetch_all(20, max_concurrent=10)
        cpu_part = asyncio.gather(*[
            loop.run_in_executor(pool, crunch, i) for i in range(3)
        ])
        return await asyncio.gather(io_part, cpu_part)


# ==================== The race condition threads create ====================
class Counter:
    def __init__(self):
        self.value = 0
        self.lock = threading.Lock()

    def unsafe_increment(self):
        self.value += 1                         # read, add, write: 3 bytecodes

    def safe_increment(self):
        with self.lock:
            self.value += 1


def hammer(counter, method_name, iterations):
    method = getattr(counter, method_name)
    for _ in range(iterations):
        method()


async def main():
    print("=== Async: 60 requests, concurrency capped at 10 ===")
    start = time.perf_counter()
    results = await fetch_all(60, max_concurrent=10)
    elapsed = time.perf_counter() - start
    print(f"  {len(results)} responses in {elapsed:.2f}s")
    print(f"  sequential would be 12.0s; unbounded would hammer the server")
    print(f"  6 batches x 0.2s = ~1.2s, as measured\n")

    print("=== The blocking-call trap ===")
    start = time.perf_counter()
    await asyncio.gather(*[good_task(f"t{i}") for i in range(5)])
    print(f"  5 x await asyncio.sleep(0.3):  {time.perf_counter() - start:.2f}s  (concurrent)")

    start = time.perf_counter()
    await asyncio.gather(*[bad_task(f"t{i}") for i in range(5)])
    print(f"  5 x time.sleep(0.3):           {time.perf_counter() - start:.2f}s  "
          f"(SERIAL -- the loop was frozen)")

    start = time.perf_counter()
    await asyncio.gather(*[offloaded_task(f"t{i}") for i in range(5)])
    print(f"  5 x asyncio.to_thread(sleep):  {time.perf_counter() - start:.2f}s  "
          f"(concurrent again)\n")

    print("=== Async I/O and process-pool CPU work, simultaneously ===")
    start = time.perf_counter()
    io_results, cpu_results = await mixed_workload()
    print(f"  {len(io_results)} requests + {len(cpu_results)} CPU tasks "
          f"in {time.perf_counter() - start:.2f}s\n")


if __name__ == "__main__":
    asyncio.run(main())

    print("=== Threads and shared mutable state ===")
    for method, label in [("unsafe_increment", "no lock"),
                          ("safe_increment", "with lock")]:
        counter = Counter()
        threads = [threading.Thread(target=hammer, args=(counter, method, 200_000))
                   for _ in range(4)]
        start = time.perf_counter()
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        expected = 4 * 200_000
        status = "correct" if counter.value == expected else f"LOST {expected - counter.value:,} updates"
        print(f"  {label:<11} {counter.value:>9,} / {expected:,}  "
              f"({time.perf_counter() - start:.2f}s)  {status}")

    print("\n  '+= 1' is read, add, write -- a thread switch between them loses the update.")

Two results here are worth staring at. The time.sleep row takes five times as long as the asyncio.sleep row despite looking almost identical in the source — one blocking call inside an async function serialises everything. And the unlocked counter loses updates non-deterministically, which is exactly what makes race conditions so unpleasant: the bug appears under load, in production, and not in your tests.


Common Mistakes

  1. Threads for CPU-bound work: the GIL means zero speedup, and often a small slowdown.
  2. Processes for tiny tasks: pickling and process startup cost more than the work. Batch into chunks.
  3. A blocking call inside async code: time.sleep, requests.get, or a sync database driver freezes the entire event loop.
  4. Unbounded asyncio.gather: ten thousand simultaneous requests will exhaust file descriptors and overwhelm the server. Use a Semaphore.
  5. No lock around shared mutable state: counter += 1 is not atomic, and lost updates appear only under load.
  6. Missing if __name__ == "__main__": with a process pool on Windows or macOS: infinite process spawning.
  7. Passing an unpicklable argument to a process pool: lambdas, open file handles, and database connections all fail.
  8. Forgetting await: the coroutine is created and never runs. Python warns, but only if you notice.
  9. Expecting processes to share memory: each has its own copy. Use a queue, a pipe, or multiprocessing.Manager.
  10. Too many threads: hundreds of threads means context-switching overhead and a downstream service you have just attacked.
  11. Not handling exceptions in gather: without return_exceptions=True, the first failure cancels every sibling task.
  12. Mixing asyncio.run inside an already-running loop: raises RuntimeError. Use await instead.

Best Practices

  • Diagnose first: pinned CPU means processes; low CPU and slow means threads or async.
  • Use concurrent.futures rather than raw Thread and Process objects — the executor API is the same for both, so switching is one word.
  • Bound concurrency always: max_workers for pools, asyncio.Semaphore for async.
  • Size pools by workload: os.cpu_count() for processes, 10–50 for I/O threads.
  • Keep async pure: async-native libraries throughout, and asyncio.to_thread for anything blocking you cannot replace.
  • Prefer immutable data and queues over shared state; when you must share, use a Lock and hold it briefly.
  • Guard the entry point with if __name__ == "__main__": whenever a process pool is involved.
  • Chunk small tasks before sending them to a process pool so each unit is worth the pickling cost.
  • Use return_exceptions=True in gather so one failure does not cancel everything.
  • Combine models when the workload is mixed: async for the I/O, run_in_executor with a process pool for the CPU.
  • Measure the sequential version first. If it is fast enough, concurrency is pure added complexity.
  • Consider Python 3.13's free-threaded build if you are on it — but write for the GIL until it is the default.

Practice Exercises

  1. The Diagnosis: Write one function that sleeps 0.2 s and one that computes a large sum. Run each under sequential, thread pool, and process pool, and produce a table of the six timings. Write a comment stating the rule your numbers demonstrate.
  2. The Frozen Loop: Write two async functions, one using await asyncio.sleep(0.5) and one using time.sleep(0.5). Run five of each with asyncio.gather, time both, and explain why one takes 0.5 s and the other 2.5 s.
  3. The Race: Launch four threads that each increment a shared counter 100,000 times without a lock, and print how many updates were lost. Add a threading.Lock, confirm the count is exact, and note the cost in runtime.