Mutex (Mutual Exclusion) is a synchronization mechanism in C++ that ensures only one thread can access a critical section of code at a time, preventing race conditions where multiple threads simultaneously access shared resources. The video demonstrates this using a car-sharing analogy where two friends cannot drive the same car simultaneously. Two implementation approaches are shown: lock_guard automatically locks and unlocks the mutex when the object goes out of scope, making it safer for simple cases, while unique_lock provides more flexibility by allowing manual unlock and deferred locking but requires careful management to avoid deadlocks.
Understanding Mutex in C++ (Multithreading for Beginners) | Mutual Exclusion Explained
Added:hi guys and welcome to my channel in this video I'm going to talk about one very interesting topic that confuses many beginners but it is very important to understand it and as you will see from this video it's not actually that hard uh so that is the topic of mutex and the first thing that I want to explain is what is mutex mutex is a term that is related to multi-threading in C plus plus and it stands for Mutual exclusion that means that mutex is a way to ensure that inside a multi-threaded application two threads cannot access the same code at the same time because that could cause many problems in your application in this video I will give you a short real life example of mutex so that you can understand the concept and if you want to learn more and if you want to understand more about multi-threading and how it's used in big projects and to build applications that we use every day then I would recommend you to watch my practical programming course the link will be in the description version and in that course multi-threading is just one of the many topics that you will learn because you will get all of the necessary skills so that you can start building applications yourself and get a job once you finish that course the course is going to be launched very soon and since you are my YouTube viewer I want to make sure that you get a special treatment when compared to other people so I'll put a link in the description that you can use to sign up and once the course is launched I am going to send you a special discount but as you will understand the number of people who can get this discount is limited so if you are interested it's completely free to sign up but do it right now so that you can secure your place so with that being said let's get back to the topic of new text as I said mutex is a way to prevent multiple threads from accessing the same part of the code at the same time and if you're not familiar with the concept of threads I already made another video where I explain multi-threading and the topic of threads and I will link that video here and also in the description so so make sure to watch it before you continue watching this video so what would be example of mutex in real life imagine the following situation let's say that you want to buy a Supercar and your friend also wants to buy a Supercar but you don't have enough money for example you have 1 million and he has 1 million but the car costs 2 million dollars so you decide to buy that car together and to share it but one thing that you need to keep in mind is that if you are sharing that car you cannot use it at the same time which means that if your friend is driving you will have to wait and if you are driving your friend will have to wait so those are the limitations now let's see how we can simulate that scenario in code so what I want to do is I want to create a function of return type void I will call it drive car okay and here I will receive one string parameter it will be string driver name okay and here I will simulate the driving of a car so I will say C out and then let's print driver's name and I will say here is driving okay and then I will say C out driver name and then let's say is done driving and let's put another end line and then here in between I will simulate the duration so the period while you are driving the car and I will do that by sleeping this thread so in order to do that you need to say include and then thread oh what is this include thread like this and now here I can say this thread okay and then let's say sleep four and here I will use Chrono okay and let's say seconds and I will say for example that you are driving for two seconds okay so this is our drive car function and now what I want to do is I want to simulate the situation where you and your friend are sharing the same car so how am I going to represent you and your friend well I am going to represent that with two threads so let's create thread if I say T1 and here I will pass two parameters the first one is going to be the method that this thread is executing and that is this drive car so what is going to be the task and the job of this thread and then the second thing is since this method receives one parameter I am going to pass it here and that is going to be the name of the driver so I will say saldina okay so this is the first friend the first thread and then let's create another one let's call it T2 its job is going to be the same function and the name of the driver will be let's say Elon okay so now these two threads are two friends that share the same card and now if I run this program we are going to see what will be the result of this application that we have written but one thing that we need to do first is the following I need to say T1 dot join and then also T2 dot join and this basically means before this program ends make sure that both of these threads have finished what they were doing so please don't end the program until both of these threads finish their job okay so you need to put this part here otherwise you are going to get an error so now let's see what's going to happen when we start the program okay Salina is driving Elon is driving and then Selena is done driving Elon is done driving I I a problem here and that is the following how can Elon drive the car before I finish driving the car so clearly we have a problem here where two threads or two friends are accessing the same resource at the same time which should not be possible what should happen instead is that I should drive the car and then once I finish driving the car then Elon can start driving and then when he finishes driving our application will end so now let's see how we can fix this problem so in order to solve this problem we use mutex and you can understand mutex as a lock that is used in order to lock certain part of the code while one thread is executing it and then once that thread finishes it will unlock that code so that other threads can access it and that part of the code that you want to lock is called critical section so in our case our critical section is this part of the code here so before one driver starts driving the car he will have to lock it here and then once he's done driving so that will be here he can unlock the car so that other drivers other threads can access that code so now let's see how we can write that code so the first thing that you need to do is you need to include mutex here okay and then you need to create a mutex that you will use in order to lock this critical section I will say new text and let's call it car mutex like this and then here I will lock my code so I will say unique lock of mutex I will call it car lock and do this variable I will give this mutex that we created okay so this is how we lock the critical section and then here once you are done driving what you need to do is you need to say car lock unlock okay so by simply doing and adding these two lines of code we have locked this critical section and now we shouldn't have the problem that we previously had so let's start the program and let's see the result okay saldina is driving and then saldina is not driving and only then Elon can start driving okay another thing that you should know is that there is a shorter way in order to lock this critical section so instead of using unique lock you can use lock guard how well it's actually very simple so you simply say lock guard like this the rest of the code stays the same and then here you can even delete this part where you are unlocking your critical section and we will come to that part and explain why in a moment but first I want to test the application let's see so saldina is driving and then seldina is not driving and only then Elon can start driving and then once he is done the application finishes okay so let's see what is the difference between lock guard and unique lock lock guard is easier and the more simple way to use mutex and its characteristics are following lock guard is going to lock your critical section at the same line where you create it also it is going to unlock the code automatically once this object goes out of scope and that is usually at the end of the block or at the end of the or at the end of the function so in our case that is here a disclosed curly bracket and because it is unlocking your code automatically that means that you cannot unlock it manually so lock guard cannot be unlocked manually that is the first thing and then the second thing which is benefit is that because it is unlocking the code and releasing mutex automatically it will make sure that your code is always unlocked and that the mutex is released properly even if your application has an exception or whatever happens your code is going to be properly unlocked and the mutex will be released so that is benefit so when you would use this lock guard you would use lock guard when you want to lock a short well-defined block of code like we have here on the other hand unique lock is harder to use but it has more options let's return this to Unique lock like this and here you will notice that I have unlocked my code manually and that is one thing that you have to do with unique lock so you need to unlock manually and if you forget to do that or if you don't know how to do it when to do it then you can cause huge problems in your application that is downside but it also has a benefit and that is that uni clock can be used in order to defer locking which means that you can delay locking because of different conditions and situations that happen in your application and also you can use the same object of unique lock in order to lock and unlock your code multiple times during the lifetime of this object which is something that you couldn't do with lock guard so as I promised at the beginning this video is going to be very easy to understand so I hope that now you do understand the idea and the concept of mutex in programming and if you want to learn more if you want to understand how this works in Big applications that you use every day and how you can build those applications as well then I invite you to sign up for my practical programming course the link will be in the description and it is completely free to sign up and in that course I'm going to teach you everything that you need to know in order to become a developer and start building the applications that you want to build and also since you are my YouTube viewer I will make sure to send you a special discount as soon as the course launches so that would be all for this video all of the code is going to be pinned in the comment and if you have any questions or any suggestions for my future videos leave those in the comment section as well and if you enjoyed this video and you have learned something new then definitely give it a thumbs up and say to the YouTube algorithm that you wanted to recommend you more videos like this where you can learn something new and where you can learn to code so thank you very much for watching and I will see you in some other video bye
Up Next

Thread Pool In C++: Efficient Multithreading Implementation Guide
@CppNuts
28.4K views•2024-02-27

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

Introduction to Multithreading in Modern C++: Build Your First App
@CodeBeauty
230.4K views•2021-10-27

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science















![Update [Moving] 2017/06/16](https://i.ytimg.com/vi/OOCBb724GJU/maxresdefault.jpg)










![[C++11] STL: Coundition Variable - Прерывание потоков](https://i.ytimg.com/vi/hc0lOBhsvdY/maxresdefault.jpg)
![Multithreading in Cpp [024] - std::condition_variable](https://i.ytimg.com/vi/uq5lc_y2op0/maxresdefault.jpg)



![Tajemnica Sandry została odkryta | Praktykanci #9 [4K]](https://i.ytimg.com/vi/E4cdJiMU-MY/maxresdefault.jpg)




