The Global Interpreter Lock (GIL)
00:00 CPython’s approach to thread safety is to use what is called the Global Interpreter Lock, or GIL. Rather than use a bunch of locks on individual shared resources, which would be very hard for compatibility and readability reasons, the GIL locks the entire Python interpreter.
00:20 Remember, that’s the part of CPython that reads in the bytecode and carries out the associated operation. Because the entire interpreter is locked, instead of a specific shared resource, each thread must obtain the interpreter lock to interpret some bytecode.
00:37 And because only one thread can have the lock at any given time, this essentially makes CPU-bound code—trying to perform a computation with multiple threads—singly-threaded. However, threading does have uses in other places of Python, like user interfaces and IO, but that’s not the focus here.
00:58 This performance limitation on CPU-bound code makes the GIL particularly infamous in the Python community. It’s a simple approach that allows Python to be both readable and compatible with old C extension modules, but at the cost of performance.
01:16 Lots of work has been done to come up with a better method of ensuring thread safety, but none have been able to outperform the GIL as of the time of this recording.
01:28 The bottom line is this: memory is a shared resource. We can only have one process or one thread accessing that block of memory at any given time or else unpredictable behavior might occur.
01:42 Protecting shared resources with mutexes is not easy, but it’s an essential part of memory management. Luckily for us, the GIL takes care of all of that.
01:52 If you’d like to learn more about the GIL, take a look at the article I’ve linked down in the video notes below.
Bartosz Zaczyński RP Team on March 12, 2021
@antchal It’s in the dropdown labeled “Supporting Material” just below the course title.
antchal on March 14, 2021
I was aware of the possibility of finding it in the corresponding article. But I thought, since I’m not reading an article here maybe RP attaches the URL at a more readily accesible place.
Thanks for clearing that doubt tough.
Become a Member to join the conversation.
antchal on March 12, 2021
Where is the article link for GIL that you mentioned in the video?