title: How to avoid race condition when refcounting without a mutex?
body: <p>I'm trying to figure out how to avoid the race condition in the following code, with thread A acquiring the datablock, then thread B Releasing/deleting it, and then thread A AddRefing it.  Is it possible to fix this without a mutex? I think that it's possible to fix this with atomic_thread_fence, but I really have no idea how it would apply to this situation. </p>
  
  <pre><code>#include &lt;atomic&gt;
  
  class Foo
  {
      std::atomic&lt;Datablock*&gt; datablock
  
  public:
      Datablock * get_datablock()
      {
          Datablock * datablock = m_datablock.load();
          if(datablock) datablock-&gt;AddRef();
          return datablock;
      }
  
      void set_datablock(Datablock* datablock)
      {
          datablock = m_datablock.exchange(datablock);
          if(datablock) datablock-&gt;Release();
      }
  };
  </code></pre>