Python is an interpreter language.

It is in Python’s traits that the interpreter compiles the code to bytecode and then is executed via the Python virtual machine. This is the standard process with the reference implementation of Python, CPython. What if there were multiple threads that are to be executed by the interpreter simultaneously.

By default, Python has not made it possible by using a mechanism called Global Interpreter Lock. This Global Interpreter Lock can be identified as a mechanism like mutex that exerts constraints on the Python code limiting the number of threads in the state of execution to one. In Layman’s terms, this means only one thread can be executed at any given time in Python using the standard interpreter.

Table of Contents

You can skip to a specific section of this Python GIL tutorial using the table of contents below:

Prerequisite Concepts

Race Condition

From a thread synchronization standpoint, a critical section of a program can be identified as a space or a resource that is potentially being accessed by processes that run concurrently. The race condition phenomenon can occur when multiple threads are trying to access a shared resource which is also known as a critical section. Since it is not generally known how the scheduling algorithm has scheduled threads to be executed at a given time, the order or the priority of execution is unknown. This may result in a racing condition making multiple threads race for the same resource.

Mutex

In order to prevent any unpredictable consequences of race conditions, various thread synchronization mechanisms are used to control and limit access to this critical section forcing the threads or the processes to wait until the occupied thread is complete. There are many thread synchronization mechanisms such as mutex, conditions, semaphores to be employed in such scenarios.

A mutex, also known as mutual exclusion, can be defined as a mutually exclusive flag that keeps an eye out for the critical section in a code. The threads that are attempting to access this critical section are supposed to acquire a lock on this section preventing any race conditions.

#python

Understanding the Python Global Interpreter Lock (GIL)
1.55 GEEK