Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use mutex instead of boolean variable for thread synchronization?

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.

like image 368
BSalunke Avatar asked Oct 23 '13 06:10

BSalunke


2 Answers

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.

like image 187
Jim Mischel Avatar answered Oct 12 '22 22:10

Jim Mischel


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.

like image 45
David Schwartz Avatar answered Oct 12 '22 22:10

David Schwartz