Python - Can’t we get rid of the Global Interpreter Lock?


The Global Interpretor Lock is a mutex in Python. Let’s first understand what is a Global Interpreter Lock (GIL) −

What is a GIL?

The global interpreter lock, or GIL, is a mutex that −

  • Protects access to Python objects,
  • Prevents multiple threads from executing Python bytecodes at once.
  • Prevents race conditions.
  • Ensures thread safety.

The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL.

Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice.

Issues with GIL

  • The GIL is not ideal, since it prevents multithreaded programs from taking full advantage of multiprocessor systems in certain situations.

  • The GIL can worsen performance.

Why we can’t remove GIL?

We can’t remove the GIL, since,

  • That would make Python slower than Python 2 in single-threaded performance.

  • Since the GIL exists even before the thread concepts introduced, other features have grown to depend on the issues it solved. This makes it even harded to remove the GIL without breaking some of the Python libraries.

Can GIL be removed?

The following properties are desirable for any probable GIL replacment −

  • First, the probable GIL replacement should be possible to implement.

  • Possible to maintain and survive long term.

  • It should fasten the single-threaded programs.

  • The proposal should be source-compatible with the macros used by all existing CPython extensions.

Updated on: 20-Sep-2022

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements