add optimistic lock list

master
caiyuzheng 2021-03-19 01:37:46 +08:00
parent ae1e5d0104
commit b06fa65636
1 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,83 @@
#pragma once
#include <list>
/*
*
*/
template <typename T>
class LockfreeList
{
private:
std::list<T> list;
private:
int mutex;
int lock;
int unlock;
public:
LockfreeList():mutex(0),lock(0),unlock(1){};
~LockfreeList(){};
void Lock()
{
while( !__sync_bool_compare_and_swap (&mutex,lock, 1) )
{
usleep(100);
}
}
void Unlock()
{
__sync_bool_compare_and_swap (&mutex,unlock, 0) ;
}
void Push(T data)
{
Lock();
list.push_back(data);
Unlock();
}
T Front()
{
Lock();
T data = list.front();
Unlock();
return data;
}
void PopFront()
{
Lock();
list.pop_front();
Unlock();
}
bool IsEmpty()
{
Lock();
if( list.empty() )
{
Unlock();
return true;
}
else
{
Unlock();
return false;
}
}
bool Find(T data)
{
typename std::list<T>::iterator it;
Lock();
for ( it = list.begin(); it != list.end(); ++it)
{
if( *it == data )
{
Unlock();
return true;
}
}
Unlock();
return false;
}
};