# GIL & Concurrency

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

Canonical: https://www.internhack.in/learn/interview/python-interview/python-gil
Last updated: 2026-11-28

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()`).

| Workload | Threads help? | Best tool |
| --- | --- | --- |
| I/O-bound (HTTP calls, DB queries) | Yes, threads wait in parallel | `ThreadPoolExecutor` or `asyncio` |
| CPU-bound pure Python (parsing, loops) | No, often slower | `ProcessPoolExecutor`, `multiprocessing` |
| CPU-bound in NumPy, hashlib, zlib | Often yes, these release the GIL | Threads 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

- **threading**: shared memory, cheap to start, good for blocking I/O. Still needs locks for shared state, because the GIL does not make your own read-modify-write sequences like `count += 1` atomic.
- **asyncio**: one thread, cooperative multitasking with `async`/`await`. Scales to thousands of open connections (FastAPI, aiohttp) but any blocking or CPU-heavy call freezes the event loop.
- **multiprocessing / ProcessPoolExecutor**: separate interpreters, each with its own GIL, so they run on separate cores. Costs: process start-up, higher memory and pickling of arguments and results.
- **Subinterpreters**: Python 3.14 added the `concurrent.interpreters` module and `InterpreterPoolExecutor` (PEP 734). Each interpreter has its own GIL, giving parallelism inside one process with stronger isolation than threads.

### 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

- "The GIL makes my code thread-safe." It only protects the interpreter's internals. Compound operations on your data still race.
- "Python cannot use multiple cores." It can, via processes, native extensions or free-threading.
- "asyncio is parallel." It is concurrent, not parallel: one thread interleaving tasks.

**Picking a concurrency model in Python. Match the tool to whether your work waits on I/O or burns CPU.**

|  | threading | asyncio | multiprocessing |
| --- | --- | --- | --- |
| Parallel CPU work | No (with GIL) | No | Yes |
| Best for | Blocking I/O | Many network connections | CPU-heavy tasks |
| Memory model | Shared memory | Shared, single thread | Separate processes |
| Overhead | Low | Very low per task | High (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

- The GIL lets one thread run Python bytecode at a time per process in CPython
- Threads still help I/O-bound work because blocking calls release the GIL
- CPU-bound pure Python needs processes, native code or the free-threaded build
- Free-threaded CPython: experimental in 3.13, officially supported but optional in 3.14
- The GIL does not make your own compound operations thread-safe

## Common follow-up questions

- Why does CPython use reference counting, and how does that relate to the GIL?
- When would you choose asyncio over a thread pool?
- What overheads does multiprocessing add, and how do you share data between processes?
- What changes for C extension authors in free-threaded Python?
- How do Gunicorn or Uvicorn workers get around the GIL for web apps?

## Interview tips

- Separate I/O-bound and CPU-bound clearly; most of the marks are in that distinction
- Mention free-threaded Python (PEP 703, 3.13/3.14) to show you are current, but say it is opt-in
- Correct the 'GIL means thread-safe' myth before the interviewer asks

## Concepts covered

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

Previous: [Generators & Iterators](https://www.internhack.in/learn/interview/python-interview/python-generators) · Next: [Variables & Data Types](https://www.internhack.in/learn/interview/python-interview/python-variables-types) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [Strings & String Methods](https://www.internhack.in/learn/interview/python-interview/python-strings)
- [Lists, Tuples & Sets](https://www.internhack.in/learn/interview/python-interview/python-lists-tuples-sets)
- [Dictionaries & Operations](https://www.internhack.in/learn/interview/python-interview/python-dictionaries)
- [Control Flow & Loops](https://www.internhack.in/learn/interview/python-interview/python-control-flow)
- [Functions & Arguments](https://www.internhack.in/learn/interview/python-interview/python-functions)
- [\*args & kwargs](https://www.internhack.in/learn/interview/python-interview/python-args-kwargs)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
