I’ve made a hand-made mutex for my project, but I doubt if it is thread safe…
bool blocked;
while ( blocked )
{
}
blocked = true;
...
blocked = false;
Lets say, thread A passes the while loop and doesn’t block the flag in time (doesn’t have time to set the flag to false) and thread B passes the while loop too!
-
Is it possible? Why?
-
As I get it mutex has the very same principle of work. Why can not this occur in mutex? I’ve read about atomic operations which can not be interrupted… So the
check-if-mutex-availableandmutex-blockcan not be interrupted, right?
Your code is completely defunct!
The reason is that access to the variable
blockedis not atomic. Two threads can read it simultaneously and decide that the mutex is unlocked, if the two reads happen before the first thread writes out thetrueupdate and the update propagates to all CPUs.You need atomic variables and atomic exchange to solve this. The
atomic_flagtype is exactly what you want:(Alternatively, you could use a
std::atomic<bool>andexchange(true), but theatomic_flagis made especially for this purpose.)Atomic variables do not only prevent the compiler from reordering code that appears to be unrelated if this were a single-threaded context, but they also make the compiler generate the necessary code to prevent the CPU itself from reordering instructions in a way that would allow inconsistent execution flow.
In fact, if you want to be slightly more efficient, you can demand a less expensive memory ordering on the set and clear operations, like so:
The reason is that you only care about the correct ordering in one direction: a delayed update in the other direction is not very expensive, but requiring sequential consistency (as is the default) may well be expensive.
Important: The above code is a so-called spin lock, because while the state is locked, we do a busy spin (the
whileloop). This is very bad in almost all situations. A kernel-provided mutex system call is a whole different kettle of fish, since it allows the thread to signal the kernel that it can go to sleep and let the kernel deschedule the entire thread. That is almost always the better behaviour.