title: Read-write thread-safe smart pointer in C++, x86-64
body: <p>I develop some lock free data structure and following problem arises.</p>
  
  <p>I have writer thread that creates objects on heap and wraps them in smart pointer with reference counter. I also have a lot of reader threads, that work with these objects. Code can look like this:</p>
  
  <pre><code>SmartPtr ptr;
  
  class Reader : public Thread {
      virtual void Run {
         for (;;) {
             SmartPtr local(ptr);
             // do smth   
         }
      }   
  };
  
  class Writer : public Thread {
      virtual void Run {
         for (;;) {
             SmartPtr newPtr(new Object);    
             ptr = newPtr;  
         }
      }
  };
  
  int main() {
      Pool* pool = SystemThreadPool();
      pool-&gt;Run(new Reader());
      pool-&gt;Run(new Writer());
      for (;;) // wait for crash :(
  }
  </code></pre>
  
  <p>When I create thread-local copy of <code>ptr</code> it means at least</p>
  
  <ol>
  <li>Read an address.</li>
  <li>Increment reference counter.</li>
  </ol>
  
  <p>I can't do these two operations atomically and thus sometimes my readers work with deleted object.</p>
  
  <p>The question is - what kind of smart pointer should I use to make read-write access from several threads with correct memory management possible? Solution should exist, since Java programmers don't even care about such a problem, simply relying on that all objects are references and are deleted only when nobody uses them.</p>
  
  <p>For PowerPC I found <a href="http://drdobbs.com/184401888">http://drdobbs.com/184401888</a>, looks nice, but uses Load-Linked and Store-Conditional instructions, that we don't have in x86. </p>
  
  <p>As far I as I understand, boost pointers provide such functionality only using locks. I need lock free solution.</p>