一个简单的无锁栈实现
/*************************************************************************
> File Name: lockfreestack.cpp
> Author:
> Mail:
> Created Time: Tue 31 Jul 2018 05:01:35 PM CST
************************************************************************/
#include<iostream>
#include <memory>
#include <atomic>
#include <thread>
template<class T>
class LockFreeStack
{
struct Node{
Node(T dta)
{
node = std::make_shared<T>(dta);
}
std::shared_ptr<T> node;
Node* next;
};
public:
LockFreeStack(){ head = NULL; }
virtual ~LockFreeStack(){}
void Push( T dta )
{
Node* node_dta = new Node(dta);
node_dta->next = head;
while( node_dta && !head.compare_exchange_weak(node_dta->next, node_dta) );
}
std::shared_ptr<T> Pop()
{
++threads_in_pop;
Node* old_node = head.load();
while( old_node && !head.compare_exchange_weak(old_node, old_node->next) );
std::shared_ptr<T> res;
if( old_node )
{
res.swap(old_node->node);
}
TryReclaim(old_node);
return res;
}
private:
//回收内存
void TryReclaim( Node* node )
{
if( threads_in_pop == 1 )
{
Node* to_be_delete = node_to_be_delete.exchange(NULL);
if( --threads_in_pop == 0 )
{
DeleteNode(to_be_delete );
}
else{
AddNodesToDelete( to_be_delete, true );
}
delete node;
node = NULL;
}
else{
AddNodesToDelete( node, false );
--threads_in_pop;
}
}
void AddNodesToDelete( Node* node, bool find_tail )
{
Node* buf = node;
while( find_tail && buf->next )
{
buf = buf->next;
}
buf->next = node_to_be_delete;
while( node_to_be_delete.compare_exchange_weak(buf->next, node) );
}
void DeleteNode( Node* node )
{
while( node )
{
Node* buf = node->next;
delete node;
node = NULL;
node = buf;
}
}
private:
std::atomic<Node*> head;
std::atomic<Node*> node_to_be_delete;
std::atomic<int> threads_in_pop;
};
LockFreeStack<int> stack;
void PushStackI()
{
for( int i = 0; i < 10; ++i )
{
stack.Push( i );
}
}
void PushStackJ()
{
for( int i = 20; i < 30; ++i )
{
stack.Push( i );
}
}
void PopStack()
{
while( 1 )
{
std::shared_ptr<int> ptr = stack.Pop();
if( ptr )
std::cout << *ptr << std::endl;
}
}
int main()
{
std::thread t1( PushStackI);
std::thread t2( PushStackJ);
std::thread t3( PopStack);
t1.join();
t2.join();
t3.join();
return 0;
}