Category: python
What Is the GIL?
Published on 27 Oct 2026
Explanation
Traditional GIL-enabled CPython builds allow one thread at a time to execute Python bytecode within an interpreter, limiting some CPU-bound threading.
Code:
import threading
def task():
for _ in range(100_000): pass
threads = [threading.Thread(target=task) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
Explanation
Multiprocessing or native libraries that release the GIL may help CPU-heavy work more than ordinary threads on traditional CPython.
Code:
from multiprocessing import Process
def calculate(): print(sum(range(1_000_000)))
if __name__ == '__main__':
processes = [Process(target=calculate) for _ in range(2)]
for p in processes: p.start()
for p in processes: p.join()
Explanation
Threads can be useful for I/O-bound operations because another thread can make progress while one waits for I/O.
Code:
import threading, time
def task(name):
print('Start', name)
time.sleep(1)
print('End', name)
threads = [threading.Thread(target=task, args=(n,)) for n in 'ABC']
for t in threads: t.start()
for t in threads: t.join()
Explanation
asyncio supports cooperative concurrency for asynchronous I/O but does not automatically parallelize CPU-heavy Python code.
Code:
import asyncio
async def task(name):
print('Start', name)
await asyncio.sleep(1)
print('End', name)
async def main(): await asyncio.gather(task('A'), task('B'))
asyncio.run(main())
Explanation
GIL behavior depends on interpreter and build. Modern CPython offers optional free-threaded builds, so inspect and benchmark the actual runtime.
Code:
import sys, sysconfig
print(sys.implementation.name)
print(sys.version)
print(sysconfig.get_config_var('Py_GIL_DISABLED'))