class MyTest {
void getter() {
std::unique_lock lock(mutex);
if (!set_) {
cout << "set already" << endl;
}
}
void setter() {
set_ = true;
}
private:
bool set_ = false;
std::mutex mutex_;
};
There are two threads: thread A calls setter(), and thread B calls getter(). In thread A, set_ = true is executed. but no mutex, so no memory barrier. thread B gets lock. At this moment, is there a chance thread B still sees set_ = false as stale data? Asking this since no memory barrier in thread A. But thread B has mutex, thus memory barrier. Can thread B still gets the latest change from thread A without using mutex/memory barrier?
At this moment, is there a chance thread
Bstill seesset_ = falseas stale data? Asking this since no memory barrier in thread A.
But thread
Bhas mutex, thus memory barrier. Can threadBstill gets the latest change from threadAwithout using mutex/memory barrier?
Yes to both. There is a data race (and therefore undefined behavior) since the write in thread A can happen while thread B is reading. The mutex lock in thread B does nothing to prevent the race since A does nothing to synchronize with it.
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