title: Lockfree Stack with atomic
body: <p>I need to build a lock-free stack implementation. I read <a href="http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange" rel="nofollow noreferrer">this page</a> and I understand the functionality of the listed lock-free push operation.</p>
  
  <p>Now, I have to build a similar version of the pop operation. This is what I've done until now but I think, there are some concurrency problems:</p>
  
  <pre><code>template &lt;class T&gt;
  bool CASStack&lt;T&gt;::pop(T&amp; ret) {
  node&lt;T&gt;* old_head = head.load(std::memory_order_relaxed);
  
  if(old_head == nullptr) {
      return false;
  }
  
  // from here on we can assume that there is an element to pop
  node&lt;T&gt;* new_head;
  
  do {
      new_head = old_head-&gt;next;
  } while(!head.compare_exchange_weak(old_head, new_head, std::memory_order_acquire, std::memory_order_relaxed));
  
  ret = old_head-&gt;data;
  
  return true;
  }
  </code></pre>
  
  <p>I think I also will get trouble if I delete old_head after the swap, right?</p>
  
  <p>EDIT: Updated question!</p>