Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python: Global Interpeter Lock

$
0
0
What is GIL?

GIL (Global interpreter Lock) is a mutex. Mutex is an mutual exclusion object used toprevent 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.

Whenthe 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 ordoing 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:


Python: Global Interpeter Lock
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 tofully 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, illustratesthe difference in a great way:


Python: Global Interpeter Lock

You can see that parallelism is when the tasks literally run at the same time. Whilein concurrency the taskscan 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).

Externalresources

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 :wink:

David Beazley presention

Vishal Kanaujia & Chetan Giridhar


Viewing all articles
Browse latest Browse all 9596

Trending Articles