无锁多线程栈的实现主要是依赖了C的原子操作特性,例如:C++11里面的atomic的compare_exchange_xx,或者基本的InterlockedCompareExchange,都可以实现。下面我们将使用atomic实现。

#ifndef __SAFE_STACK_LL__
#define __SAFE_STACK_LL__
/*
use cas mode support thread safe
need c++x
*/
namespace ustd
{
template<class T>
class CSafeStack
{
struct _Node
{
_Node(const T &data) :_data(data){};
T _data;
_Node *_next;
};
public:
CSafeStack() :m_tail(nullptr){};

void push(const T &_d)
{
_Node *pnode = new _Node(_d);
pnode->_next = m_tail.load();
while (!m_tail.compare_exchange_weak(pnode->_next, pnode));
}

bool pop(T &_d)
{
_Node *pnode = m_tail.load();
/// note pnode is nullptr
while (pnode && !m_tail.compare_exchange_weak(pnode, pnode->_next));

if (pnode == nullptr)
return false;
_d = pnode->_data;
/// free node memory
delete pnode;
return true;
}
private:
std::atomic<_Node*> m_tail;
};
}
#endif