No video

The Python Global Interpreter Lock - Explained

  Рет қаралды 63,748

Tech With Tim

Tech With Tim

Күн бұрын

Today, I'm revealing the worst feature Python has... The GIL (Global Interpreter Lock)! We'll be going over what the GIL is, how it compares to traditional programs, and why it's one of the worst features.
💻 Master Blockchain and Web 3.0 development today by using BlockchainExpert: 🔗 algoexpert.io/... (Use code "tim" for a discount!)
💻 Accelerate your software engineering career with ProgrammingExpert: 🔗 programmingexp... (Use code "tim" for a discount!)
🎬 Timestamps⏱️
00:00 | What is The GIL
00:18 | How Traditional Programs Work
01:44 | The Problem With Python
02:37 | Why Use Multiple Threads in Python
04:10 | Multi-Processing
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
👕 Merchandise: 🔗 teespring.com/...
📸 Instagram: 🔗 / tech_with_tim
📱 Twitter: 🔗 / techwithtimm
🔊 Discord: 🔗 / discord
📝 LinkedIn: 🔗 / tim-ruscica-82631b179
🌎 Website: 🔗 techwithtim.net
📂 GitHub: 🔗 github.com/tec...
One-Time Donations: 💲 www.paypal.com...
Patreon: 💲 / techwithtim
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
⭐️ Tags ⭐️
- Tech With Tim
- The GIL
- Python
⭐️ Hashtags ⭐️
#programming #python #coding

Пікірлер: 95
@bereck7735
@bereck7735 Жыл бұрын
For the people who are asking the question, why was GIL introduced in the first place or what advantage does it have is that the primary purpose of the GIL is to simplify the memory management and ensure thread safety in python ( cpython ). It is a lock that allows only one thread to execute Python bytecode at a time, even on multi-core systems. This means that even if you have multiple threads in a Python program, they can't truly execute in parallel and take full advantage of multiple CPU cores. The GIL was introduced in python to simplify the memory management of Python objects. The memory management in python is implemented using reference counting, where each object keeps a count of how many references are pointing to it. When the reference count of an object reaches zero, it is deallocated. The GIL ensures that reference counting is thread-safe by allowing only one thread to modify the reference count at a time. While the GIL simplifies memory management and provides thread safety, it also has some drawbacks. Because only one thread can execute Python bytecode at a time, it can limit the performance of multi-threaded Python programs, especially those that involve CPU-bound tasks. However, the GIL is not always a limiting factor for performance, as it can still be beneficial in scenarios where the program is I/O bound or when using extension modules written in languages like C/C++ that release the GIL during their operations. Although you cannot enable / disable or remove GIL, it is a part of python itself, although there is a project that exist where a fork of cpython is being developed without GIL.
@grawss
@grawss Жыл бұрын
I just said something similar (but less verbose) in another comment, but you clearly know more about it than me. If you don't mind another question, why would it be difficult at all to release the GIL if the purpose was merely simplification of locks and memory? I assume it has to do with the way they count refs, but that would imply flawed design more-so than removing complexity.
@TechWithTim
@TechWithTim Жыл бұрын
Great comment and explanation! Thanks for the explaining that so elegantly :)
@bereck7735
@bereck7735 Жыл бұрын
@@grawss Well one of the main reasons for the GIL existence is thread safety and memory management and yes this has been discussed for a long time, GIL is technically a tradeoff between peformance and safety. Second, removing GIL is a HUGE task, because first, GIL is part of cpython's interpreter and remving that is a huge amount of work, as it is probably one of the biggest breaking changes that may happen to python, Second, writing an alternative the GIL is also a lot of work and research and adds more complexity. Then you have legacy code support Due to python's design, a lot of python libraries, expect and depend on GIL and how it works and if the GIL is removed, a lot of those libraries with break ( think of this the absolute mayhem that happened with python 2 to python 3 release ) and then you have also perfomance implications, now it will increase performance in multi threaded tasks, but it will degrade performance in single threaded tasks, not to mention, sacrificing safety and adding more complexity, now ofcourse the implementation or the concept of GIL is not the perfect or the only way, other programming languages can do all this and do not have something like GIL, but because this was decided as python's internal component a long time ago, changing / removing it is too much of a hassle now.
@bereck7735
@bereck7735 Жыл бұрын
@@grawss also GIL isnt defensible, if the developers of cpython really wanted, they can create an alternative of GIL, with none of its drawbacks, but because python has had it for so long, that it has been accepted and also worked around with, yes GIL tends to hinder with AI/ML development but developers have started to make workarounds around it, a lot of developers may not agree witb GIL and its existence, but they still accept it and well just deal with it.
@bereck7735
@bereck7735 Жыл бұрын
@@grawss If you are interested in a non GIL version of python or a version where you selectively enable / disable GIL in python, read PEP 703
@MrDowntemp0
@MrDowntemp0 Жыл бұрын
Eehh... this video isn't very informative. (WHY is there a GIL? Why don't other languages use it? What are the benefits of having a GIL? etc.) In addition some of the simplifying goes so far as to spread misinformation. Why would you use non interpreted languages when explaining how other languages can use the same interpreter at the same time? I know there are special cases for C++, but the vast majority of the time it's compiled, not interpreted.
@raymondforbes4295
@raymondforbes4295 Жыл бұрын
I really think if you are going to make a video on the GIL it is worth exploring why it exists and how important it was for the adoption of Python. I would also point out that using IO bound applications as an example isn't a great one. It is very rare for IO issues to be CPU bound. Async and event loops work perfectly well for IO bound applications.
@JoseJimeniz
@JoseJimeniz Жыл бұрын
Waiting on I/O is also not a good example because you can do what Windows does: Overlapped (i.e. asynchronous) IO. You don't need threads. You give Windows a callback when the I/O is complete, and your entire can be single-threaded event-driven. And others talking about the the reference counting not being thread-safe; just change it to InterlockedIncrement/InterlockedDecrement like all reference-counting has done since the mid-1990s.
@SivaranjanGoswami
@SivaranjanGoswami Жыл бұрын
I have extensively used both multi-threading and multi-processing on my codes. The thumb rule is to go for multi-processing if a process needs to perform some processor-intensive task. If it just needs to wait for a response from an API, database, or some I/O device, use multi-threading. GIL doesn't cause problems if you know how to structure your code efficiently. Python is one of the easiest languages to learn, but these are some advanced concepts of Python that needs a thorough understanding of the concepts.
@vaibhav_uk
@vaibhav_uk 8 ай бұрын
where to learn all of this?
@SivaranjanGoswami
@SivaranjanGoswami 8 ай бұрын
@@vaibhav_uk you learn these things by facing problems. If a code is taking too long to execute, you explore how to make it run faster. You find a solution on the internet. You try something. If it works, explore - why it works. If it doesn't work, explore - what else you can do to make it work. Learning is a lifelong journey. I have been coding for more than a decade. Today I learned something new from a junior employee in my team.
@wealox
@wealox Жыл бұрын
2:05 C++, Go and Rust are not interpreted languages.
@TechWithTim
@TechWithTim Жыл бұрын
Ah good call, meant to say that they can run true parallel programs! I.e no lock
@loadeddice1304
@loadeddice1304 Жыл бұрын
Hi Tim, could you make more videos on this topic? Maybe going further into detail with multi-processing and how to handle the separation of tasks and how to recombine the output?
@Djellowman
@Djellowman Жыл бұрын
I knew all of this, but wish you went into WHY python implements a GIL.
@broteinstain8256
@broteinstain8256 Жыл бұрын
He explains more I think in a few of his other videos he has done recently, but this video could have had more details about why it exists or the efforts that have been made to remove it so far.
@nitkarshchourasia2406
@nitkarshchourasia2406 4 ай бұрын
🎯 Key Takeaways for quick navigation: 00:00 *🎬 Introduction to the Global Interpreter Lock (GIL)* - Explanation of the Global Interpreter Lock (GIL) in Python. - Overview of how traditional CPU processing works with threads. - Understanding software threads and their execution on CPU cores. 02:05 *🔒 Limitations of GIL in Python* - Discussion on the limitations imposed by the Global Interpreter Lock (GIL). - Explanation of how the GIL restricts parallel processing in Python. - Impact of GIL on multithreading and parallel execution in Python programs. 03:07 *🔄 Handling IO Operations with Threading* - Use cases for multithreading in Python, particularly in IO-bound operations. - Explanation of how multithreading enables concurrent execution in IO-bound tasks. - Example scenarios demonstrating the benefits of multithreading for IO operations. 04:10 *⚙️ Introduction to Multiprocessing* - Introduction to Python's multiprocessing module as an alternative to multithreading. - Explanation of how multiprocessing allows parallel execution by spawning separate processes. - Comparison between multithreading and multiprocessing in Python. Made with HARPA AI
@MakeDataUseful
@MakeDataUseful Жыл бұрын
I’m kind of a fan of the GIL, it’s a level of complexity removed for new Python people
@jaimeduncan6167
@jaimeduncan6167 5 ай бұрын
Very good explanation, some details: 1. All modern CPUs are superscalar, which means that you can, and should perform multiple operations per thread. Modern compilers will attempt to help you out, for example by unrolling a loop for an arithmetic loop. 2. The summation is not sped up by a factor of 4, it was a perfect example to explain why. The speed-up is not that big because you have to add the segments, two times.
@aflous
@aflous Жыл бұрын
Great job on explaining the Global Interpreter Lock (GIL) in Python, but I don't agree with the final conclusion regarding multiprocessing being not as easy to handle as multithreading. Writing safe concurrent code is currently a really hard task. David Baron once said, "You Must be This Tall to Write Multi-Threaded Code," pointing at a post-it note placed at an 8-foot height in Mozilla’s San Francisco office.
@Saadullahkhan3
@Saadullahkhan3 4 ай бұрын
SImple in GIL: Multi-Threading(Concurrent): Not really parallel because here is multiple threads with one interpreter Multi-Processing(Parallel): Spawn multiple interpreter for each thread Parallel: Parallelism refers to the simultaneous execution of multiple tasks or processes, where each task is broken down into smaller sub-tasks that can be executed independently and simultaneously on multiple processors or CPU cores. In parallel execution, tasks run at the same time, truly concurrently, and can potentially speed up the overall execution time. Parallelism requires hardware support for multiple processing units. Concurrent: Concurrency, on the other hand, refers to the ability of a system to handle multiple tasks or processes at the same time, even if they are not executing simultaneously. In a concurrent system, tasks may be started, run for a while, paused, and then resumed later, interleaving their execution. Concurrency doesn't necessarily require multiple processing units; it can be achieved through techniques like time-sharing or interleaved execution on a single processor. Because python is simplest language GIL ensure that a beginner mistake not become a problem by limiting threads while multi-processing is more complicated to multi-threading so python give to advanced user and create a awesome balance. If you want to enjoy power of multiple works at a time but not to make it complicated use multi-threading and when actually want parallel execution use multi-procession
@MedartN7
@MedartN7 Жыл бұрын
"The Guy" form Disturbed(David Draiman best vocalist our generation period!) covers make me smile, interesting way that You use him like that :) Nice explanation Tim, thank You for Your work!
@eltreum1
@eltreum1 Ай бұрын
Ah my old arch nemesis and frenemy the GIL. When I was new to it, I hated it and didn't understand why make an OOP language with all this flexibility then constrain it so heavy handed. The GIL is that best friend that will always call you out on your BS and stop you from doing dumb things. If you are running afoul of the GIL, you are either going about solving your problem in the worst way possible, or using Python for the wrong job and something else should be used instead. Working with/around the GIL can be an interesting exercise to deconstruct your problem into proper units of atomic work. You have to go out of your way and know a lot to write thread/memory unsafe code in Py typically.
@b001
@b001 Жыл бұрын
Nice video, very informative! The style was perfect for this video, great demonstrations.
@gJonii
@gJonii Жыл бұрын
I've never understood hate for GIL. Python has plenty of problems, GIL wouldn't make my top-100 list. For threads, you can do multiple OS threads, if you need this. Or you can do co-operative multitasking with async, generators, etc. There are ways to do whatever you need threads for, but better. And GIL means the programs now lack one extremely common failure mode entirely, while making Python programs run faster. Seems like almost universally a good idea.
@WaldoTheWombat
@WaldoTheWombat 2 ай бұрын
Great video Tim, thank you! Perhaps you could make another video explaining why the GIL even exists in the first place.
@thomasluk4319
@thomasluk4319 2 ай бұрын
I would like to ask is it better to use threading or multiprocessing for writing and saving files. Reecently I have a program to read scan data from sensor, the sensor has a very high sensing rate and produce a lot of data point. I have first tried to use threading to create a one producer-multiple consumer pattern, but I find out that once a consumer start writing to csv (large amount of data), the producer callback cannot be triggered.... so I switched to use multiprocessing and it works out fine. But most people in the Internet saying that writing file is a IO task, and IO task should use threading. Can some one explain the reason? or there is some misunderstanding for me about how to correctly use threading?
@becauseiwanttoanime9541
@becauseiwanttoanime9541 Жыл бұрын
I absolutely love the new video style! its focused to the point short and give all the information we need! Great video! Thanks tim!
@TechWithTim
@TechWithTim Жыл бұрын
Glad you liked it!
@reasonforge9997
@reasonforge9997 10 ай бұрын
You seem to be leaving out a huge piece here: async and its predecessors green threads. They have been the typical way get around waiting for non-CPU intensive processes.
@lowkeygaming4716
@lowkeygaming4716 Жыл бұрын
When I was a newbie I use gunicorn to support multiprocessing, now I'm also using celery to support async process and multiprocessing in my project. It's additional complexity to setup but still worth the effort.
@Kyfow
@Kyfow Жыл бұрын
Here's the trap - even if you're using multiple threads and async processing you're not actually running multithreading. It's still limited by the GIL. Essentially async in python is a clever trick that puts the request in a pseudo thread management system run by python, but multiple async requests to your server are still gonna share the same GIL.
@malakarakesh3139
@malakarakesh3139 7 ай бұрын
at 4:05, if one thread execution is I/O blocked, how does the interpreter switch to process another thread execution? how does the interpreter know to release the lock for another thread?
@kitetm7596
@kitetm7596 Жыл бұрын
2:56 This is basically Async in python right
@aflous
@aflous Жыл бұрын
No, you can achieve this using multiple threads. However, you can achieve the same, if not easier, using async and coroutines.
@mo7sin711
@mo7sin711 3 ай бұрын
I need help I'm studying the freecodecamp course, and when i type the following code for the conditional exercise x = 0 y = 10 if 0 == x: if y == 10: print('YES') the output in the VS code terminal is Syntax Error however when I run it in python itself or an online compiler, it runs successfully and prints YES I need help :(
@leamon9024
@leamon9024 Жыл бұрын
Thanks Tim. Could you also make a video about the difference between coroutine and thread? Thank you
@clearthinking5441
@clearthinking5441 Ай бұрын
what is the benefit of multiple-threads vs async?
@passportbro904
@passportbro904 7 ай бұрын
I started learning python 12 months ago, watching videos like this now no more for loops lol, gonna start applying for jobs in about 3 months, i wanna be an sql developer, wish me luck
@user-gs8te4dr3l
@user-gs8te4dr3l Жыл бұрын
Autocomplete not working for OpenCV (cv2) in jupyter lab , please help
@TheManOfTheHourEveryHour
@TheManOfTheHourEveryHour Жыл бұрын
Are there any major singular culprits outside of GIL that contribute to Python's slowness?
@kilianklaiber6367
@kilianklaiber6367 Ай бұрын
Your explanations are fantastic!
@topeque6993
@topeque6993 Жыл бұрын
Hey Tim i abosultely love your videos! Can you make a tutorial on building a captive portal with Django?I really like to make one but im having a hard time. Thank you
@609neo
@609neo Жыл бұрын
This is wrong. C++, Rust and Go programs are compiled and runs on bare metal. They have no interpreter, for comparison. There are mentions about a Go runtime but that is simply additional code added by the Go compiler to take care of garbage collection and other things rather than a virtual machine level abstraction as in JVM.
@arpitagarwal8330
@arpitagarwal8330 Жыл бұрын
Hey tim I am really motivated by ur programming journey and skills. I want to ask as a amateur programmer what steps do I need to become professional software programmer.I don't have cs degree.
@vaishantsah
@vaishantsah 8 ай бұрын
find ur area of interest in CS and take a course related to it. But before it watch the apps required for it and learn it's basics on YT. Python3, SQL are the most common and the most in demand. DATA SCIENCE and DATA ANALYST are one of the most popular area of interest. DevOps and Web Development is also iin demand. For Web Dev I'd recommend you get a Full Stack Course of it and grab a job using referrals.
@santaclause0015
@santaclause0015 Жыл бұрын
so what does Polars and Dask do? please explain?
@mquanit
@mquanit 11 ай бұрын
I have a Go background and this GIL in python looks like mutexes in Go. Helps acheiving thread safe programs.
@TheDavidlloydjones
@TheDavidlloydjones Жыл бұрын
To add twenty numbers on four cores, you have to count up the numbers, 20, count up the cores, 4, divide the 20 by the four, 5 -- and by this time your "limited" opponent is finished adding the twenty. There may be programs where Python is slower -- but this example clearly isn't one of them.
@garrettsmith315
@garrettsmith315 Жыл бұрын
I love the informative videos but i miss your hardcore coding tutorials. I understand you probably don't have the same time that you used to but just know I watch your tutorials all the time!
@ButchCassidyAndSundanceKid
@ButchCassidyAndSundanceKid Жыл бұрын
Hopefully the new kid on the block, Mojo will solve this problem.
@gokulsrinivasan8563
@gokulsrinivasan8563 6 ай бұрын
Just a Awesome explanation
@JEffinger
@JEffinger Жыл бұрын
Yes but why is there a GIL? the video doesn't explain why Python does this when other languages don't.
@jal051
@jal051 Жыл бұрын
Python is not compiled.
@aflous
@aflous Жыл бұрын
In a few words, the GIL in Python ensures thread safety. In more words, the GIL ensures that memory management operations are thread-safe. Without the GIL, if multiple threads accessed and modified the same objects simultaneously, it could result in race conditions and memory corruption. The GIL guarantees that only one thread can execute Python bytecode at a time, preventing such issues.
@Dmittry
@Dmittry 2 ай бұрын
If there are 4 cores then a CPU can have 4 OR 8 threads. Not between.
@whu.9163
@whu.9163 Жыл бұрын
That I/O blocking example is not that great. Python still has async which is nice for such operations
@rikthecuber
@rikthecuber Жыл бұрын
I have a qn, are there any advantages of having GIL over not having it?
@mihirshah1717
@mihirshah1717 Жыл бұрын
why don't you try asking chatgpt the same question
@skyr-inf
@skyr-inf Жыл бұрын
Absolutely amazing explanation. Still would like to know why the lock is there though.
@moon911x
@moon911x Жыл бұрын
most controversial feature 💩
@gvozdyara9563
@gvozdyara9563 Жыл бұрын
I like GIL, can't imagine my l life without it
@KayderimGameplays
@KayderimGameplays Жыл бұрын
Hey man, will you be using the Mojo language when it comes out? I want to make a game in the future and many people told me to not use python and that i should go for C# or C++, do you think this Mojo will be a better option for it?
@kitetm7596
@kitetm7596 Жыл бұрын
Which engine are you going for?
@markp1634
@markp1634 Жыл бұрын
As unreal uses c++, and unity uses c#, mojo will not help a game made In either of those.
@KayderimGameplays
@KayderimGameplays Жыл бұрын
@@markp1634 Oh, so i can't use the unreal or unity with python or mojo? I'm not into those things yet
@shokhdev
@shokhdev Жыл бұрын
Hey love your content❤ next time could you please make video about JavaScript 😅 thank you 🙏
@Millenial_Live
@Millenial_Live Жыл бұрын
Video right not Oreo 😂😢
@BAMBOOM2021
@BAMBOOM2021 Жыл бұрын
Why did they decide to call them threads? Why didnt they call them tables? Now threads might sound cooler. But its really not related to sewing as much as it related to sorting. So when these threads come together after processing, are they called strings or ropes or something?Or are they more like a way to pipe programs through rather than sorting? Because you said that python still is able to multiprocess. If thats the case, then why didnt they just call them pipes or ziplines or something? Lol. Jesus Loves You Man.God Bless You.
@kvelez
@kvelez Жыл бұрын
Excellent.
@olu_the_ai_guy
@olu_the_ai_guy Жыл бұрын
Awesome
@user-dl1su3li5s
@user-dl1su3li5s 11 ай бұрын
I wanted to say that if you see my msg, I have bought Programming expert course and it is utter waste. You are teaching as if its 10 year old learning programming. I took that course thinking it has shown around 251 problems to solve and I get frustrated seeing True or False question, this or that. Have some standard question You have add practice questions. Not 2nd grade questions. Very disappointed and not getting refund too.
@programmingjobesch7291
@programmingjobesch7291 Жыл бұрын
Was just looking this up yesterday.
@ninjanape
@ninjanape Жыл бұрын
I clicked because of The Guy Those who know, know🤘
@mentefria98
@mentefria98 Жыл бұрын
And still, what are the advantages of having a GIL?
@grawss
@grawss Жыл бұрын
Couple reasons I can think up: It's better on resources due to the singular lock on its singular thread, and in doing that, the entire language becomes enormously easier* since you don't have to manage locks or worry about state management. *personal note: Enormously easier for a few hours, since you can just learn those things, and then the GIL isn't as defensible. :(
@jal051
@jal051 Жыл бұрын
Look. If you want speed use a compiled language. Python will never be fast. It's just not designed for it.
@LambdaCreates
@LambdaCreates Жыл бұрын
second comment. 134th viewer. 16th liker. all just 4 minutes after the video was published
@EbenHodzi
@EbenHodzi Жыл бұрын
Very educational
@user-ip3ve3dt9c
@user-ip3ve3dt9c Жыл бұрын
Love form India ❤
@nobdysus8326
@nobdysus8326 Жыл бұрын
first
@jokurandompappa
@jokurandompappa Жыл бұрын
U are handsome, but I liked the facecamless teaching way more
@ElTitoAndrezz
@ElTitoAndrezz Жыл бұрын
second
What is the Python Interpreter? (How does Python Work?)
14:08
Afternerd
Рет қаралды 79 М.
Unlocking your CPU cores in Python (multiprocessing)
12:16
mCoding
Рет қаралды 300 М.
UNO!
00:18
БРУНО
Рет қаралды 4,6 МЛН
Pool Bed Prank By My Grandpa 😂 #funny
00:47
SKITS
Рет қаралды 18 МЛН
WHO CAN RUN FASTER?
00:23
Zhong
Рет қаралды 39 МЛН
15 Python Libraries You Should Know About
14:54
ArjanCodes
Рет қаралды 382 М.
Python is NOT Single Threaded (and how to bypass the GIL)
10:23
Jack of Some
Рет қаралды 108 М.
threading vs multiprocessing in python
22:31
Dave's Space
Рет қаралды 573 М.
How To Practice Programming So You Actually Get Good
15:46
Tech With Tim
Рет қаралды 123 М.
Pydantic Tutorial • Solving Python's Biggest Problem
11:07
pixegami
Рет қаралды 262 М.
Python multithreading 🧵
13:34
Bro Code
Рет қаралды 64 М.
Asyncio in Python - Full Tutorial
24:59
Tech With Tim
Рет қаралды 65 М.
python is removing the GIL! (PEP 703) (advanced) anthony explains #550
24:04
Modern Python logging
21:32
mCoding
Рет қаралды 176 М.
FANG Interview Question | Process vs Thread
3:51
ByteByteGo
Рет қаралды 303 М.