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.
Jim mischel
source share