Skip to main content

python's global interpreter lock

·1 min
Disclaimer: This is an unrefined post, see Consistency over Perfectionism.

Python’s Global Interpreter Lock (GIL) is a solution to memory management without introducing garbage collection.

Python uses a technique called reference counting to figure out which objects can be dispose of, which needs to be protected from race conditions in order to prevent memory leaks or, even worse, incorrectly releasing memory while references to an object still exist.

The GIL effectively enforces all Python programs to run in a single thread.

Historically, Python was designed to be simple to adopt, so its community created lots of extensions to existing C libraries: since many of them were not thread-safe, the GIL was introduced in the language to ensure proper memory management. Python code can still make use of threads via the threading package, but, because of the GIL, CPU-bound multi-threaded Python programs take slightly longer than their single-threaded counterparts, since they have to acquire and release the lock when context-switching: I/O-bound threads, on the other hand, are not affected as much, since they share the lock while waiting for I/O.