c++mutexrace-condition

c++ mutex and memory barrier


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?


Solution

  • 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?

    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.