Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
SuperBald Avatar asked Oct 31 '25 02:10

SuperBald


1 Answers

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.

like image 95
Ted Lyngmo Avatar answered Nov 01 '25 18:11

Ted Lyngmo