Mutex In C++
HTML-код
- Опубликовано: 15 июн 2019
- JOIN ME
-----
RUclips 🎬 / @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 😀
Great thorough explanation of what is a very simple concept. Well done. Thank you.
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.
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..
Great tutorial!
Love from America
Great explanation,
you make every topic easy for every one.
thanks bhiya
it help me a lot.
Thanks man!!
Great example and very easy to understand also for beginners on multithreading
These videos are amazing omg I actually got it
thank you sir.....your videos are really very helpful in getting the concept.. keep doing the same
Thanks man!!
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!
Thank you so much. You explained well the Mutex. Keep going on.
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
Thank you, quality content!
Thank you so much for the comment!!
After watching ur videos....no need to watch other videos.... awesome man.
Its my pleasure, thanks for the comment man.
Awesome explanation like always, I love this channel.
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..
Yourself are using mutex while drawing and coding ...
I like your english too.. so...
++subscribed..
Thanks man!!
Thanks for such an explanation ❤
Nice explanation. Please make a video on the semaphore as well.
Thank you, very helpful!
Agree I m a c# developer bt watch your videos for concepts. 👍
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?
simple and easy to understand explanation.
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.
Thanks!
1. Race condition vs. Mutex
Great video ! Can you please tell me what tool you used for writing on the screen ? This looks very professional.
Very good one !!
This explanation was amazing with simple code .i would request you pls. post Semaphore & Spin lock. awaiting..!
Thanks a lot 💙
sir, you're really a great teacher. thanks a lot.
Thanks man..
Love this video~! Thanks:)
Glad you enjoyed it!
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.
One thing which I don't understand here, why people are disliking this video?🤦♂️🤦♂️
i duno why ppl are disliking... explained very well thank u
Thanks..
Great explanation!
Glad it was helpful!
Join is linking one task after another!!!!
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.
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 ?
@8.12 -> what if ++myAmount throws exception ? then it will be locked forever. Instead we can use lock_guard ?
Awesome explanation sir....😊👍
Thanks man..
thank u so much for your videos
Glad you like them!
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
The vedio are very nice to understand the thread concepts.
Thanks man!!
Very nice explanation.
Thanks
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?
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
ruclips.net/video/XDZkyQVsbDY/видео.html
cool tut!!!
Thanks man!!
mast samjhaya dhanyavad
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()?
Thank you!
You're welcome!
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
Super. Thanks
Thanks..
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
std::mutex is similar to CRITICAL_SECTION in Windows and is used for synchronizing threads in the same process, right ?
output of the 1st code (Race Condition code ) is 2
Its Vary Compile to Compiler or something else happen?
Pls help as u said 3:34 that there can be race and issue with final value of i but in my case i am facing problem am getting it same without mutex if i change i++ to ++i in thread func it does just u told else it dont.
#include
#include
#include
void ThreadWork(int& i);
int main (){
int i = 0;
std::vector threadList;
for (int j = 0; j < 10000; j++)
{
threadList.push_back(std::thread(ThreadWork, std::ref(i)));
}
std::cout
Thanks
Great tutorial ! A bit slow but thats perfect to ensure understanding. Whats the name of the song used as intro ?
What happened if forget to add instruction m.unlock() ? in the critical section
very nicely explain mutux
Thanks for your comment dude!!
helpful!
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
best explanation :)
Glad you liked it
Good explanation
Thanks and welcome
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 🙏
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.
Thank you
You're welcome
brilliant
how can accumulator load two things at the same time
What will happen if an error occurs while executing ++myAmount ? Will the mutex still be locked ?
perfect again
Thanks man!!
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..
Samjhauta ;) nicely summed up :)
Glad you liked it
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.
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.
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.
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.
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)
Thanks ! What happens if we don't use t1.join(), t2.join() here ?
Please watch my join and detach video for full details.
ruclips.net/video/q3-5sDe6lzg/видео.html
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
Can you please tell me which IDE/compiler you are using ??
Sublime text editor 3.
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.
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.
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?
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...?
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.
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.
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.
10:10
In a multi-core processor, is there always a tiny time difference b/w two threads?
If that's the case, how can we call multi-threading TRUE parallel processing?
What did i exactly mentioned in the video, if you can mention that may be i can answer to this question.
@@CppNuts The timestamp I provided in the above comment is supposed to serve this purpose.
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.
WOW
please make video of recursive mutex
Sure man!
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
@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.