GIL & Concurrency

Difficulty: Advanced

Question

What is the Global Interpreter Lock (GIL) in CPython, and how do you achieve real parallelism in Python?

Answer

The GIL is a mutex in CPython that lets only one thread execute Python bytecode at a time within a process. It makes reference counting and the interpreter's internals simple and safe, but it means CPU-bound pure-Python code does not speed up with more threads. To get true parallelism you use multiple processes (multiprocessing, ProcessPoolExecutor), native code that releases the GIL (NumPy, many C extensions), or the newer free-threaded CPython build.

Why CPython has a GIL

CPython manages memory with reference counts stored on every object. If two threads incremented and decremented the same count without coordination, objects could be freed while still in use. Putting one big lock around the interpreter avoided fine-grained locks on every object, kept single-threaded code fast and made writing C extensions easy. The GIL is a CPython implementation detail, not part of the language: Jython and IronPython never had one, and PyPy has its own.

When the GIL hurts and when it does not

A thread releases the GIL when it blocks on I/O (sockets, files, time.sleep) and periodically while running bytecode (the switch interval, 5 ms by default, see sys.getswitchinterval()).

WorkloadThreads help?Best tool
I/O-bound (HTTP calls, DB queries)Yes, threads wait in parallelThreadPoolExecutor or asyncio
CPU-bound pure Python (parsing, loops)No, often slowerProcessPoolExecutor, multiprocessing
CPU-bound in NumPy, hashlib, zlibOften yes, these release the GILThreads are fine

So a service that calls 50 bank APIs concurrently works well with threads or asyncio, but resizing 10,000 images in pure Python needs processes.

Concurrency options compared

The free-threaded build (no GIL)

PEP 703 introduced an optional build of CPython with the GIL disabled. It shipped as experimental in Python 3.13 (python3.13t) and became officially supported, though still not the default, in 3.14 (PEP 779). In that build, threads run Python bytecode truly in parallel. Trade-offs: single-threaded code runs somewhat slower, and C extensions must be rebuilt and marked as safe, otherwise the interpreter may re-enable the GIL when it imports them. You can check with sys._is_gil_enabled(). For most production code in 2026 the standard GIL build is still what you deploy, so knowing the process and asyncio patterns remains essential.

Common misconceptions

Picking a concurrency model in Python. Match the tool to whether your work waits on I/O or burns CPU.
threadingasynciomultiprocessing
Parallel CPU workNo (with GIL)NoYes
Best forBlocking I/OMany network connectionsCPU-heavy tasks
Memory modelShared memoryShared, single threadSeparate processes
OverheadLowVery low per taskHigh (spawn + pickling)

Code examples

Threads vs processes on CPU-bound work

import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def cpu_task(n):
    return sum(i * i for i in range(n))

def bench(executor_cls):
    start = time.perf_counter()
    with executor_cls(max_workers=4) as ex:
        list(ex.map(cpu_task, [5_000_000] * 4))
    return time.perf_counter() - start

if __name__ == "__main__":       # required for process pools on Windows/macOS
    print(f"threads:   {bench(ThreadPoolExecutor):.2f}s")
    print(f"processes: {bench(ProcessPoolExecutor):.2f}s")

On the standard GIL build, threads take roughly as long as doing the work serially, while processes use multiple cores. Exact timings depend on your machine.

I/O-bound work with asyncio

import asyncio

async def fetch_balance(bank):
    await asyncio.sleep(1)          # stands in for a network call
    return f"{bank}: ok"

async def main():
    banks = ["HDFC", "ICICI", "SBI", "Axis"]
    results = await asyncio.gather(*(fetch_balance(b) for b in banks))
    print(results)

asyncio.run(main())   # finishes in about 1s, not 4s

While one coroutine awaits I/O the event loop runs the others, so four 1-second waits overlap on a single thread.

The GIL does not make += atomic

import threading

count = 0
lock = threading.Lock()

def work():
    global count
    for _ in range(100_000):
        with lock:          # remove the lock and the total can come out short
            count += 1

threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(count)

count += 1 is a load, add and store; a thread switch between them loses updates. Your own shared state always needs a lock.

Key points

Common follow-up questions

Interview tips

Concepts covered

GIL, Threading, Multiprocessing, asyncio, Free-threaded Python, Concurrency vs Parallelism

More Python Interview questions