Why Python (CPython and others) uses the GIL?

Technology CommunityCategory: PythonWhy Python (CPython and others) uses the GIL?
VietMX Staff asked 3 years ago

In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe.

Python has a GIL as opposed to fine-grained locking for several reasons:

  • It is faster in the single-threaded case.
  • It is faster in the multi-threaded case for i/o bound programs.
  • It is faster in the multi-threaded case for cpu-bound programs that do their compute-intensive work in C libraries.
  • It makes C extensions easier to write: there will be no switch of Python threads except where you allow it to happen (i.e. between the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros).
  • It makes wrapping C libraries easier. You don’t have to worry about thread-safety. If the library is not thread-safe, you simply keep the GIL locked while you call it.