title: Synchronisation in C++ 11 with std::atomic
body: <p>I have the following code that runs fine on Intel processors but produces weird data on ARM processors.<br />
  I suspect that this is a synchronisation problem.</p>
  <p>Basically I have a producer thread calling <code>setLiveData(...)</code> periodically and a consumer thread calling <code>getLiveData(...)</code> periodically as well.</p>
  <p>.h file</p>
  <pre><code>class DataHandler{
  public:
  ...
  private:
  
      LiveDataValue lastValues_;
      bool lastValuesValid;
  };
  </code></pre>
  <p>.cpp file</p>
  <pre><code>bool DataHandler::getLiveData(LiveDataValue *val)
  {
      if(this-&gt;lastValuesValid){
          *val = this-&gt;lastValues_;
          return true;
      }else
          return false;
  }
  
  void DataHandler::setLiveData(LiveDataValue val)
  {
      this-&gt;lastValuesValid = false;
      this-&gt;lastValues = val;
      this-&gt;lastValuesValid = true;
  }
  </code></pre>
  <p>Just by reading the code, I think that I need to make sure that <code>setLiveData</code> is atomic in the sense that a consumer thread can't call <code>getLiveData(...)</code> while a producer thread is in the middle of <code>setLiveData(...)</code></p>
  <p>I've found <a href="https://stackoverflow.com/a/31978762/15186">this answer</a> and tried to used it fixing the code:</p>
  <p>.h file</p>
  <pre><code>class DataHandler{
  public:
  ...
  private:
  
      LiveDataValue lastValues_;
      std::atomic&lt;bool&gt; lastValuesValid;
  };
  </code></pre>
  <p>.cpp file</p>
  <pre><code>bool DataHandler::getLiveData(LiveDataValue *val)
  {
     while (!this-&gt;lastValuesValid.load(std::memory_order_acquire))
     {
         std::this_thread::yield();
     }
  
      if(this-&gt;lastValuesValid){
          *val = this-&gt;lastValues_;
          return true;
      }else
          return false;
  }
  
  void DataHandler::setLiveData(LiveDataValue val)
  {
      this-&gt;lastValuesValid_.store(false, std::memory_order_release);
      this-&gt;lastValues = val;
      this-&gt;lastValuesValid_.store(true, std::memory_order_release);
  }
  </code></pre>
  <p>My problem is that I never exit the while loop in getLiveData called by the reader thread. Why is that?</p>
  <p>EDIT : LiveDataValue is a complex union typedef, not detailed here.</p>