Why use a mutex instead of a boolean to synchronize threads?

I am trying to understand multithreaded programming in C.

I have doubts that since we use MUTEXES to synchronize threads, why can't we use a boolean to block a critical area of ​​code that needs to be executed.

What is the mute over boolean variable function?

PS: Actually, this question was asked in an interview. Therefore, please share your knowledge about this.

+8
multithreading synchronization mutex boolean
source share
4 answers

The problem is that two threads could simultaneously see the Boolean value as available, and both then assumed that it was safe to continue.

For example, let's 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 running. Thread A reads myLock and sees that it is false , so it moves on to the next statement. At the same time, Thread B reads myLock and sees that it is false , because Thread A has not set it to true yet. So Thread B goes straight ahead and takes the lock. At this point, both threads execute code that must be protected by a mutual exclusion lock.

This gets worse because Thread A finishes what it is doing and sets myLock back to false while Thread B is still running. Thus, another stream may come and occupy the castle, although stream B is still there.

Mutex guarantees atomicity. That is, this ensures that validation and updating can only be performed by one thread at a time. Therefore, if you replace boolean with mutex, you have:

 if (mutex.Acquire()) { // do stuff // then release the lock mutex.Release(); } 

There is no chance that two threads can simultaneously receive a mutex.

+6
source share
 int locked = 0; void lock( void ) { while ( locked ) sleep_api( little ); locked = 1; return; } 

This code is incorrect because two threads can simultaneously see 0 in a locked variable and think that they have a lock.

+2
source share

First of all, your proposal is not entirely clear. Say you have five threads competing for the same resource. It’s clear how to use mutexes to provide exclusive access. It is far from clear how you use a Boolean variable for this.

Moreover, logical variables can sometimes be used for synchronization. However, the circumstances under which this is applicable are limited and there are caveats (for example, such variables should usually be declared volatile ).

Mutexes are much more applicable. It may be worth mentioning that, in addition to (correctly) ensuring that only one thread can enter a protected partition, they also act as memory barriers .

+1
source share

If you tried to use a boolean expression as a β€œfake mutex,” I could easily point out flaws in your implementation until you basically finished re-creating the mutex. A mutex is mostly logical with additional materials needed to synchronize it.

+1
source share

All Articles