title: Simple lock free stack c++11
body: <p>I've seen several overly complicated (in my opinion obviously) implementation of a lock free stack in c++ (using tags like <a href="https://stackoverflow.com/questions/24831200/lock-free-stack-is-this-a-correct-usage-of-c11-relaxed-atomics-can-it-be-pr">here</a>) and I came up with what I believe is a simple and still valid implementation. Since I couldn't find this implementation anywhere (I've seen the Push function implemented similarly to what I did but not the Pop), I'm guessing that it's incorrect in some way (most likely fails the ABA case):</p>
  
  <pre><code>template&lt;typename Data&gt;
  struct Element
  {
    Data mData;
    Element&lt;Data&gt;* mNext;
  };
  
  template&lt;typename Data&gt;
  class Stack
  {
   public:
    using Obj = Element&lt;Data&gt;;
    std::atomic&lt;Obj*&gt; mHead;
  
    void Push(Obj *newObj)
    {
      newObj-&gt;mNext = mHead.load();
      //Should I be using std::memory_order_acq_rel below??
      while(!mHead.compare_exchange_weak(newObj-&gt;mNext, newObj));
    }
  
    Obj* Pop()
    {
      Obj* old_head = mHead.load();
      while (1)
      {
        if (old_head == nullptr)
          return nullptr;
        //Should I be using std::memory_order_acq_rel below??
        if(mHead.compare_exchange_weak(old_head, old_head-&gt;mNext)) ///&lt;&lt;&lt; CL1
          return old_head;
      }
    }
  };
  </code></pre>
  
  <p>I'm assuming that the callers of Push and Pop will take care of memory allocation and deallocation. Another option is to make the above Push and Pop private methods and have new public functions that would take care of memory allocation and call these functions internally. I believe the most tricky part of this implementation is the line I marked with "CL1". The reason I think it's correct and still works in the ABA case is the following:</p>
  
  <p>Lets say the ABA case does happen. Meaning that mHead at "CL1" would be equal to old_head but the object they're both pointing to would actually be different than the one old_head was originally pointing to when I assigned mHead to it. But, I think that even if it's a different object we're still OK, since we know it's a valid "head". old_head is pointing to the same object as mHead is, so it IS the valid head of the stack and this means that old_head->mNext is the valid next head.
  So, updating mHead to old_head->mNext is still correct!</p>
  
  <p>To summarize:</p>
  
  <ol>
  <li>If mHead != old_head (another thread preempted us and changed mHead) -> old_head is updated to be the new mHead and we start the loop again.</li>
  <li>[NON-ABA] If mHead == old_head -> simple case, update mHead to be old_head->next (==mHead->mNext) and return old_head.</li>
  <li>[ABA] If mHead == old_head -> works as explained above.</li>
  </ol>
  
  <p>So, is my implementation valid? What am I missing?</p>