Difficulty: Advanced
What is the Global Interpreter Lock (GIL) in CPython, and how do you achieve real parallelism in Python?
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.
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.
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.
count += 1 atomic.async/await. Scales to thousands of open connections (FastAPI, aiohttp) but any blocking or CPU-heavy call freezes the event loop.concurrent.interpreters module and InterpreterPoolExecutor (PEP 734). Each interpreter has its own GIL, giving parallelism inside one process with stronger isolation than threads.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.
| 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) |
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.
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.
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.
GIL, Threading, Multiprocessing, asyncio, Free-threaded Python, Concurrency vs Parallelism