Mutex In C++
Вставка
- Опубліковано 11 вер 2024
- JOIN ME
-----
UA-cam 🎬 / @cppnuts
Patreon 🚀 / cppnuts
COMPLETE PLAYLIST
------------
C++ Tutorial For Beginners: • Introduction To C++
STL (Standard Template Library): • STL In C++
ThreadIng In C++: • Multithreading In C++
Data Structures: • Data Structure
Algorithms: • Binary Search
Design Patterns: • Factory Design Pattern...
Smart Pointers: • Smart Pointer In C++
C++14: • Digit Separator In C++
C++17: • std string_view in C++...
C++ All Type Casts: • static_cast In C++
INTERVIEW PLAYLIST
------------
C++ Interview Q&A: • Structural Padding & P...
C++ Interview Q&A For Experienced: • How delete[] Knows How...
Linked List Interview Questions: • Find Kth Node From Bac...
BST Interview Questions: • Search Element In Bina...
Array Interview Questions: • Reverse An Array
String Interview Questions: • Check String Is Palind...
Bit Manipulation Questions: • Find Set Bit In Intege...
Binary Tree Interview Question: • Invert Binary Tree
Sorting Algorithms: • Bubble Sort
C++ MCQ: • Video
C MCQ: • What printf returns af...
C Interview Questions: • Designated Initializat...
QUICK SHORT VIDEOS
-------------
C++ Short : • C++ Short Videos
C Short : • Shorts C Programming MCQ
In this video we will learn about Mutex In C++ Threading | Why Use Mutex | What Is Race Condition And How To Solve It? | What Is Critical Section
Mutex: Mutual Exclusion
RACE CONDITION:
0. Race condition is a situation where two or more threads/process happens to change a common data at the same time.
1. If there is a race condition then we have to protect it and the protected section is called critical section/region.
MUTEX:
0. Mutex is used to avoid race condition.
1. We use lock() , unlock() on mutex to avoid race condition.
#threading #cpp #programming #tutorial #computerscience #softwareengineering
Hi everyone, Don't forget to hit LIKE and SUBSCRIBE button for more videos like this!!
And this will help me a-lot.
Thank you man!
British guy here; you're an amazing teacher and I can understand you very well. Brilliant content as always.
Thanks dude, and glad that i can help people..
Thanks for giving this feeling..
So Mutex is like Toilet, only one person can enter and when he finished another person can enter.
Exactly.. 😃
😂😂😂
The toilet is the critical region rather. The key to the toilet is mutex.
Depends...couple may enter together, for some common interest.😂😂😂
@@saurabhverma3453 @CPPNuts needs to explain that situation now.
Best Video on Mutex concept Ever..Thanks a lot for making understading vast conepts so easy to understand..Thanks
Thanks for your appreciation dude.
I really appreciate you giving us this content for free. Great playlist on threading. Keep going!
Welcome dude..
It's always fun to watch your videos, not boring at all. Keep creating such amazing informative videos
Thank you so much 😀
awesome man.... Really awesome . i just want to say need more videos on multi-threading. You started from basic but we need till depth :):) . No need to watch other videos .Really each and every topic explanation is awesome. keep it up man .
Thanks man, sure new videos will come.
Yourself are using mutex while drawing and coding ...
I like your english too.. so...
++subscribed..
Thanks man!!
I never thought I would find a channel like this 😳😳😳 great work
Thanks for such a nice comment, means a lot.
Can you start making c++ mini projects
No man sorry, i hardly get time for youtube regular videos, i am not a professor, work in some company as SE.
@@CppNuts oh never mind your tuts are great
After watching ur videos....no need to watch other videos.... awesome man.
Its my pleasure, thanks for the comment man.
PLEASE ADD ALL THE COMPUTER SCIENCE COURSES NEEDED, YOU'RE THE ONE THAT TEACHES BEST. I have an electrical and electronics engineering background but I am willing to learn computer science, and if you have any suggestion from your videos to start from the beginning please let me know, if you don't I am waiting to you create those videos.
Thanks..
Actually there is no start and end.
You can choose a playlists for the start, like you can go for C Tutorial PlayList and then C++ Tutorial Playlist, once you are done with these you can choose to prepare for interview of still go for data structure playlist and design pattern playlist.
Nice explanation. Please make a video on the semaphore as well.
Great explanation,
you make every topic easy for every one.
thanks bhiya
it help me a lot.
Thanks man!!
Instead of int myAmount = 0 ., we can go for std::atomic myAmount(0) will solve the race condition making myAmount atomic
For this case this would be easier, but the task was to show how to use a mutex.
Thanks Lot Dear, I was waiting for c++11 for long time. Your attitude is so impressive . Can you plz make a video How mutex is failed to handle more than two thread .
Hi Raman, thanks for the comment but i am not able to understand why mutex will fail to handle more than two threads??
It is actually meant for more than 1 thread.
i duno why ppl are disliking... explained very well thank u
Thanks..
thank you sir.....your videos are really very helpful in getting the concept.. keep doing the same
Thanks man!!
Your explanation makes it very clear, thank you!
Glad it was helpful!
the best ever explaination , there is always something new to learn here. thank you so much SIR.
Thanks dude..
Very well explained all the concepts. I have been following you from quite sometime and really grateful for the contents that you make. I have one request please could you explain about semaphores with an example in c++. I have gone through many other contents available on internet, although I have a rough idea about semaphores and its mechanism but need a good example in c++ to understand the implementation of semaphores more clearly. If you could explain this it would be a great help for me. Thanks again :)
Sure..
Great tutorial!
Love from America
Great thorough explanation of what is a very simple concept. Well done. Thank you.
Great example and very easy to understand also for beginners on multithreading
simple , short and easy to understand... will be grt if u have added deadlock condition. mutex vs semaphore as well.. may be in next video..
Yaa man, if i will include everything in one video then it becomes very big.
Thanks!
1. Race condition vs. Mutex
Agree I m a c# developer bt watch your videos for concepts. 👍
I can understand the concepts explained by you,
I want to know , in c++ , when we can pass arguments to a "child thread function" ,after execution of the "child thread function" , how to collect the return value (which is a vector) in the parent thread i.e., main()
std::promise And std::future In C++ Threading
ua-cam.com/video/XDZkyQVsbDY/v-deo.html
sir, you're really a great teacher. thanks a lot.
Thanks man..
Actually I think that not only race condition is present when you modify the data but also when you access it and other thread/process modify it. For example, in a condition where something cannot happen when a count is zero. Suppose count is one, you pass the condition but in that moment, other process/thread start to execute and decrements count to zero, and then you return and make wrong this with that count.
Correct, that is called read write problem or write read problem, if you have studied DBMS there also we call it an issue. So it's not race condition when it is write write.
So you are correct, race condition is there if wr or rw conditions are there, not only ww.
@@CppNuts Thanks for answer. Happy day
Thank you so much. You explained well the Mutex. Keep going on.
simple and easy to understand explanation.
Thanks for such an explanation ❤
These videos are amazing omg I actually got it
Join is linking one task after another!!!!
Thank you, quality content!
Thank you so much for the comment!!
When multiple threads trying to access a resources,a threads get resources and lock it and once threads work is done it unblocks resources and make available for other threads.
Prevents the race condition
Great and well optimized. Thanks for this video.
Glad you liked it!
I have subscribed. Yo dude, it is absolutely amazing!
Thanks for the sub!
One thing which I don't understand here, why people are disliking this video?🤦♂️🤦♂️
All the concepts have been explained clearly. Thanks a lot. If possible could you explain about threads creation using posix as well in a short video? @CppNuts
The vedio are very nice to understand the thread concepts.
Thanks man!!
Awesome explanation sir....😊👍
Thanks man..
Awesome explanation like always, I love this channel.
Thanks dude..
Thank you, very helpful!
Hi. This is a nice explaination of Mutex. Can you please upload a file for notes for all sections, that would be really helpful
Go to channels about page, u ill get the link.
Really great tutorial but I have a doubt, what will happen if same thread tries to lock() 2 times without using unlock() first after the first lock()??? I mean what will happen if same thread uses lock() 2 times and then uses unlock()?
Great explanation!
Glad it was helpful!
This explanation was amazing with simple code .i would request you pls. post Semaphore & Spin lock. awaiting..!
mast samjhaya dhanyavad
Great video ! Can you please tell me what tool you used for writing on the screen ? This looks very professional.
very nicely explain mutux
Thanks for your comment dude!!
Very good one !!
Very nice explanation.
Thanks
please make a video on v table..and v pointer
Sure once this threading playlist will be over i will make video on virtual.
Even i been waiting for virtual videos.
Great video! I do have one doubt though, using mutex we can restrict access to the critical section to a single thread at a time, but there is not guarantee as to which thread reaches the critical section first. In the example discussed in the video the order in which the threads access the critical section has no impact on the final result. But if we have situation where the order of execution of threads impacts the final result, (suppose say we are performing two different mathematical operations on the global variable on the separate threads) then how do we deal with such a situation?
Hi, did you get answer for thus even i am having same doubt
@shubhamtiwari7704 We can use either condition variable or semaphore, i have both the videos.
Binary Semaphore In C++ With Programming Example
ua-cam.com/video/fEC9Q-vShq8/v-deo.html
Condition Variable In C++
ua-cam.com/video/eh_9zUNmTig/v-deo.html
Very good and understandable video thank you
10:50 If there always will be a time difference between thread T1 and T2 when they are approaching a critical section, then how will there be a race condition? Then why would we even need a mutex?
Sorry if this question is so simple. Noticed no one asked this in comments so I thought of asking.
Great tutorial ! A bit slow but thats perfect to ensure understanding. Whats the name of the song used as intro ?
It's a general purpose doubt : can we extend all this concepts of threading functionality in c Lang by using the stdio header file instead of iostream
Yes there are so many things available in c programming language, look for pthread you will get everything.
(unlike c++ , c programming doesn't have its own threading header you will have to use pthread)
as u have said, there is tiny difference of time in reaching to CPU by thread.
so if there is tiny difference, already then, whats the use of mutex.?
any thread reaching 1st will increase the value and the subsequent thread will change the updated value.
please clear my doubt.
this is applicable when one core processor, but when there is multiple core, two threads can run actually parallel.
@@CppNuts oh...yes. thanks man.
even with single core, you may want to use a mutex, cause most of the code you'll write will have more than one instruction, so you probably want another thread to execute a part a function another thread is using
Hi ,Thanks for the video..Could you please explain how can we detect the race condition in our code ...I can't simply refer the logs as logs can be in GB ,please explain how can i debug the race condition..
Waiting for your reply..Thanks in advance
I heared that there are few tools or library which can find race conditions but never used it.
@@CppNuts thanks, i was thinking ,can we debug and figure out the race condition without using new tool?if yes,then how?
thank u so much for your videos
Glad you like them!
Sir, how it will work when T1 goes to CPU1 and T2 goes to CPU2, in case of multiple CPUs to change some variable or file
?
Thank You, your videos are very very helpful 🙏
Hi, can you lower ur intro music? its very high compared to ur voice in vidoes. Good videos btw!
Hello Sir,
Thanks for this video .I have one doubt if we are not using mutex lock and unlock in the given example then also it is giving the output 2 always and also we are not getting any run-time issues could you please clarify.
Thanks in advance.
try to create more than 2 threads.. may be 5 or 10 then you will see the difference.
As @Parvez said if you will create more threads the chances of being caught will increase.
What happened if forget to add instruction m.unlock() ? in the critical section
@CppNuts : We might need some better example of race condition, as without mutex also the above program will might always(for me it always gave 2) give result as 2.
Computers are fast it is hrad to reproduce.
I don't understand... I have the same code than you but if i comment/uncomment the lock and unlock lines, the result remain the same... so I don't understand how is it usefull... Help?
So many people complain about this, i have tested in 2 different computers, actually 3 computer and i see everything is good.
Really don't know how to debug this problem you are mentioning.
Good explanation
Thanks and welcome
When i run the code without mutex, still i got output:2 can someone tell me why the output isn't 1 as taught
Questions:-
1. Mutex and thread sychroniztion , are they same ?
2. can T2 skip the critical section if it is locked by T1 ?
1. Mutex is a locking mechanism and using mutex multiple threads synchronise to access critical section.
2. T2 can skip if we are using try_lock function.
I think you should watch threading playlist.
and watch it from the beginning. And until unless you are sure about the topic don't move forward.
output of the 1st code (Race Condition code ) is 2
Its Vary Compile to Compiler or something else happen?
best explanation :)
Glad you liked it
even without mutex answer is coming right in my case
If you will run multiple time, changes are are it won't
how can accumulator load two things at the same time
@8.12 -> what if ++myAmount throws exception ? then it will be locked forever. Instead we can use lock_guard ?
Hi I have some question
What is the maximum critical section in one thread?
and If I want two critical section in one thread how can I do it
Thank you
i compiled same program without using mutex it is working correcr then what is the use of mutex if i am getting same out put without mutex
Love this video~! Thanks:)
Glad you enjoyed it!
What will happen if an error occurs while executing ++myAmount ? Will the mutex still be locked ?
std::mutex is similar to CRITICAL_SECTION in Windows and is used for synchronizing threads in the same process, right ?
Hi I have a question, let's say we have a single serial communication port and we want to read two different things periodically in same period. In this case, there will be two request which want to use serialport.read function at the same time, so can we say our read function is a shared object ? Can we use mutex for these two periodic serial port readings ?
Can you please provide me the video on how to implement our own malloc function like mymalloc
And
What is smart pointer and it's types in CPP plz sir I humble request
Sorry i don't have such video for now.
Can you please tell me which IDE/compiler you are using ??
Sublime text editor 3.
Super. Thanks
Thanks..
Hi Rupesh, Can you please tell me how to run(not sleep) a thread for 10 minutes?
sleep for 10 minutes or run 10 minutes a thread is equal?
I am looking for the reply
Thanks
Hi Irshad, i couldn't get the question. Please explain in details.
Samjhauta ;) nicely summed up :)
Glad you liked it
Question:
Is data race condition always not recommended?
If so, why didn't cpp std library just embed mutex inside the thread? if it was embedded, the threads can always guarantee it is race condition-free.
is there any specific case we "want to" use race condition? or is it just lazy implementation?
By the way, I love your videos!
sometimes we want to intentionally generate a race condition.
consider global data
int flag = 0
consder thread 1
while (flag == 0) {
}
consider thread 2
if (flag == 0) {
flag = 1
}
thread 1 is waiting for thread 2 to modify the value of flag so that it can break out of its loop.
Whether the other thread is in waiting state or blocked state? Once you said it is in blocking state and again you said it is in waiting state.
It is waiting for mutex.
Thanks ! What happens if we don't use t1.join(), t2.join() here ?
Please watch my join and detach video for full details.
ua-cam.com/video/q3-5sDe6lzg/v-deo.html
Does this also work if I have only 1 thread but many users who start my program and try to run this same thread? For example: The thread should write into a file. Now many users can start the program at the same time and run the thread which wants to write into the same file. Are the threads also blocked from being able to access the file at the same time in this case?
brilliant
perfect again
Thanks man!!
brother thanks a lot , i have one doubt when mutex is not used . Then either t1 or t2 will start . If t1 has started and makes x =1 and t2 also runs with some delay and makes x=2 , please clear me
thanks
helpful!
I'm bigger fan of your viedoes
Can you please provide me the videos on semaphore
Sure wait for it.
please make video of recursive mutex
Sure man!
Hi Rupesh,
What is the difference between critical section and mutex ?
It is always recommended to use criticalsection to sync within same process and mutex to sync different processes...how criticalsection perform better over mutex?
I think their is confusion; Mutex is used to Synchronies Critical Section. If you dont have CriticalSection then we dont need Mutex.
@Rupesh, Thanks for the video. I believe adding one of realtime example on CriticalSection and mutex help a lot to audience.
Sure man!
Noo Rupesh,
As per my understanding, there are 4 types of synchronisation methods.
1. Critical section
2. Mutex
3. Event
4. Semaphore
I want to know why we prefer critical section over mutex to sync threads within same process...?
is there any method to find the minimum time taken by a processor or ram or a particular motherboard component to function?
There must be..
Thank you!
You're welcome!