Skip to content

Python multiprocessing vs threading: choosing for the GIL

Pick between threading, multiprocessing, asyncio, and ProcessPoolExecutor for a Python workload — the GIL, fork vs spawn, shared state, and operational cost.

The Python concurrency menu reads like a trick question. There’s threading, multiprocessing, concurrent.futures.ThreadPoolExecutor, concurrent.futures.ProcessPoolExecutor, and asyncio. They all “do work in parallel” but solve different problems and break in different ways. The decision is mostly about the GIL (Global Interpreter Lock): CPU-bound work needs separate processes to use multiple cores; I/O-bound work can use threads or asyncio because the GIL releases during I/O syscalls. This article makes the choice explicit.

How to verify

Check what the workload actually is and which Python you’re running:

python -c "import sys; print(sys.version, sys.platform)"
python -c "import sys; print('GIL' if sys._is_gil_enabled() else 'no-GIL')" 2>/dev/null
py-spy record -d 30 -o /tmp/p.svg --pid <pid>   # check if CPU-bound
top -p <pid>                                       # %CPU >90 means CPU-bound
strace -p <pid> -c -e trace=network,read,write    # check I/O ratio

If py-spy shows the worker is 60%+ in socket.recv or select.select, it’s I/O-bound — threads or asyncio. If it’s 60%+ in numerical or parsing code, it’s CPU-bound — processes.

What’s happening

CPython has the GIL: a mutex that lets only one thread execute Python bytecode at a time per interpreter. Threads still help for I/O because the interpreter releases the GIL during a blocking syscall, but they don’t help for CPU-bound Python work — N threads give you 1x the throughput, not N.

multiprocessing and ProcessPoolExecutor sidestep this by spawning separate processes, each with its own GIL. For 4 CPU-bound workers, you get roughly 4x throughput at the cost of inter-process communication (pickle on every queue op) and process startup time. The cost of a Process.start() is around 50ms on Linux, much higher on Windows or macOS where the default is spawn instead of fork.

asyncio is the third path. A single thread runs a cooperative event loop where coroutines yield with await. For I/O-bound workloads (HTTP fan-out, database queries on a non-blocking driver), asyncio scales to tens of thousands of concurrent operations on one core because there’s no thread context switch, no GIL contention, just function calls. But: blocking the loop with a synchronous library or a CPU spike stalls every other coroutine.

Python 3.13’s free-threading build is the wild card. It disables the GIL, so threads finally use multiple cores for CPU work. Adoption is still early; pure-Python code mostly works, C extensions vary. For 2026 production, assume the GIL.

Decision

  1. Workload is I/O-bound (HTTP, DB queries, file reads):

    • Use asyncio if every library you call is non-blocking (httpx, asyncpg, redis-py async, motor for Mongo). One worker per CPU core; saturate I/O on each.
    • Use threading / ThreadPoolExecutor if any library is sync-only (requests, psycopg2 without [binary], paramiko). Threads work fine for blocking I/O because the GIL releases.
    # threading for sync I/O fan-out
    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(max_workers=32) as pool:
        results = list(pool.map(fetch_url, urls))
  2. Workload is CPU-bound (NumPy/Pandas if not vectorised, image processing, parsing large JSON):

    • Use multiprocessing / ProcessPoolExecutor. N workers, where N is the CPU count.
    • Avoid sending large objects through the queue — pickling 100 MB per task kills throughput. Pass file paths or DB IDs; let the worker load.
    from concurrent.futures import ProcessPoolExecutor
    with ProcessPoolExecutor(max_workers=os.cpu_count()) as pool:
        results = list(pool.map(parse_file, paths, chunksize=10))
  3. Workload mixes CPU and I/O:

    • Combine. asyncio for the I/O fan-out, loop.run_in_executor(ProcessPoolExecutor(), cpu_work, arg) for the CPU spikes. The event loop stays responsive; CPU work goes to its own process.
    import asyncio
    from concurrent.futures import ProcessPoolExecutor
    
    pool = ProcessPoolExecutor(max_workers=4)
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(pool, heavy_compute, data)
  4. Pick fork vs spawn deliberately:

    • fork (default on Linux) duplicates the parent at fork time — fast (~ms) and inherits all state. Issues: open DB connections are duplicated and break; threads in the parent become “orphaned” in the child.

    • spawn (default on macOS / Windows, opt-in on Linux) starts a fresh interpreter and re-imports the module. Slower (50-500ms) but produces a clean child.

    • For production servers that hold connections at startup, prefer spawn and reopen connections in each worker:

      import multiprocessing as mp
      mp.set_start_method("spawn", force=True)
  5. Don’t use bare threading.Thread for production work — no error reporting, no result, no timeout. Use ThreadPoolExecutor.submit() and Future.result(timeout=...).

  6. For Celery and RQ: Celery has its own pool model. --pool=prefork is processes (the default; matches the multiprocessing reasoning). --pool=gevent is greenlets (asyncio-like, monkey-patches stdlib). --pool=threads is threads. Pick the same way you would for an inline workload — Celery just wraps it.

Common pitfalls

  • multiprocessing on Windows or macOS with global state — the child re-imports the module, so module-level “do this once” code runs N times. Guard with if __name__ == "__main__":.
  • Mixing multiprocessing with a Django app — Django connections must be closed in the parent before fork. Use django.db.connections.close_all() then fork.
  • Hitting the OS file-descriptor limit with too many threads or processes — ulimit -n defaults to 1024 on some hosts. Set LimitNOFILE=65535 in the systemd unit.
  • Sharing mutable state via multiprocessing.Manager — slow (everything is RPC) and easy to deadlock. Use queues for messages and shared-memory Array or Value for raw bytes.
  • asyncio + a blocking library — time.sleep(1) in an async function stalls the whole loop. Use await asyncio.sleep(1). Same for any sync HTTP/DB client.

For the asyncio production deployment side, see Python asyncio in production. Stack Harbor’s managed operations practice picks processes for CPU work, asyncio for I/O fan-out on greenfield codebases, and threads for inherited sync code paths — the wrong choice surfaces as either dead CPU cores (threads for CPU work) or a stalled event loop (sync call in async).