Python: Global Interpeter Lock

What is GIL?

GIL (Global interpreter Lock) is a mutex. Mutex is an mutual exclusion object used to prevent from two threads or more, to access the same piece of code.  This piece of code  also called ‘critical section’.

So GIL is Python’s way to ensure only one thread is running the code at any given time. It serializes the access to the interpreter and ensures that each thread gets exclusive access to the interpreter internals when running.

Remember that Python’s threads are real operating system threads (POSIX threads or pthreads) and they are fully managed by the host operating system.

When the other threads are running?

Any thread that wants to run, needs to acquire the GIL first. It’s possible to acquire GIL whenever the running thread is waiting or doing I/O operation.

There are also some C extensions which release GIL so that other threads can run.

This is described well with the following drawing which is commonly used in GIL presentions:


Does it apply for all Python implementations?

The answer is no. You have GIL in CPython, but not in Jython and IronPython for example, which allows you to fully exploit multiprocessor systems.

So there is no concurrency with GIL?

Not exactly. There are some aspects of concurrency in CPython, but you may say that there is no parallelism.

What is the difference between concurrency and parallelism?

There are two drawings which, in my opinion, illustrates the difference in a great way:


You can see that parallelism is when the tasks literally run at the same time. While in concurrency  the tasks can start, run and complete in overlapping time periods, so they can run on the same time, but it’s not necessarily the case (e.g two tasks on single core hardware).

External resources

There are some excellent resources on GIL (on which I based this short summary post), written by people who actually know what they are talking about 😉

David Beazley presention

Vishal Kanaujia & Chetan Giridhar 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s