Skip to content
Search

Global interpreter lock

lastmod 2025-09-18created 2017-01-247 edits

Global interpreter lock (GIL) is a mechanism used in computer language interpreters to synchronize the execution of threads so that only one native thread can execute at a time. An interpreter that uses GIL always allows exactly one thread to execute at a time, even if run on a multi-core processor. Some popular interpreters that have GIL are CPython and Ruby MRI.

GIL stands for Global Interpreter Lock, one of the techniques used to synchronize threads when there are multiple threads. The GIL places a lock at the global level and restricts code execution so that it can only run while holding this lock. As a result, no more than one thread runs at the same time. For example, even when three threads split up the work as in the figure below, only one thread can actually occupy the CPU. In other words, only one core is actually used.

GIL efficiency

Intuitively, if only one core can be used even on a multi-core machine, supporting multi threads with a GIL seems like it would cause serious performance problems. In most cases, however, it isn't a big problem. To be precise, it isn't a problem because most programs are I/O bound. An I/O-bound program spends most of its time waiting for I/O events, so other threads can use the CPU while it waits for an event.

Conversely, if a program is CPU bound, writing a multi-threaded program doesn't improve performance. In fact, performance can even drop because of the time spent acquiring and releasing the lock.

Pros of the GIL

Although performance may suffer in multi-threaded programs, many interpreter implementations use a GIL, including CPython, PyPy, Ruby MRI, Rubinius, and the Lua interpreter. The first reason is that implementing multi-threads with a GIL is much easier than implementing parallel multi-threads.

Moreover, the problem with such parallel multi-thread implementations is that they actually become slower in single-threaded use. So although there were many attempts to remove the GIL in CPython and Ruby MRI, they ultimately couldn't overcome the single-thread performance loss and went back to the GIL. Eventually, Guido van Rossum, the creator of Python, even declared that he would not accept any implementation that removes the GIL from CPython at the cost of single-thread performance.

Multiprocessing vs Multithreading

Py_BEGIN_ALLOW_THREADS
res = waitpid(pid, &status, options);
Py_END_ALLOW_THREADS

The Py_BEGIN_ALLOW_THREADS macro in C code is a macro that releases the GIL in Python.

That is, it releases the GIL lock, waits for waitpid to finish (which may take an unknown amount of time), and then restores it with the Py_END_ALLOW_THREADS macro.

See also

Favorite site

author Zer0 sitemap