I'm trying to understand the multithreading programming in C.
I have doubt that as we uses MUTEXES for thread synchronization, why we can't use Boolean variable to block the critical area of code to be executed.
What is specialty of mutes over Boolean variable?
PS: Actually this question was asked in an interview. So please share your knowledge about this.
The problem is that two threads could both see the Boolean value as available at the same time, and both would then assume that it's safe to continue.
For example, say you have this code:
bool myLock = false; // visible to all threads
void someFunction()
{
if (!myLock)
{
myLock = true;
// do whatever
// and then release the lock
mylock = false;
}
}
Now, imagine that two threads are executing. Thread A reads myLock
and sees that it's false
, so it goes on to the next instruction. At the same time, Thread B reads myLock
and sees that it's false
, because Thread A hasn't yet set it to true
. So Thread B goes right ahead and takes the lock, too. At this point, both threads are executing the code that's supposed to be protected by a mutual exclusion lock.
It gets worse because Thread A finishes what it's doing and sets mylock
back to false
while Thread B is still executing. So another thread can come along and take the lock even though Thread B is still in there.
A mutex guarantees atomicity. That is, it guarantees that the check-and-update can only be done by a single thread at a time. So if you replace the boolean with a mutex, you have:
if (mutex.Acquire())
{
// do stuff
// then release the lock
mutex.Release();
}
There's no chance that two threads can acquire the mutex simultaneously.
If you tried to use a boolean as a "fake mutex", I could easily keep pointing out flaws in your implementation until you basically wound up re-inventing the mutex. A mutex is basically a boolean with all the extra stuff you need to use it for thread synchronization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With