This paper presents a C + + lock-free queue implementation code, which is mainly used for one thread to read data and another thread to write data
Copy Code code as follows:
#ifndef Lock_free_queue_h_
#define Lock_free_queue_h_
No lock queue, suitable for one thread read, one thread write
#include <list>
Template <typename t>
Class Lockfreequeue
{
Public
Lockfreequeue ()
{
List.push_back (T ());//Split node
Ihead = List.begin ();
Itail = List.end ();
};
void Produce (const t& T)//Save message
{
List.push_back (t);
Itail = List.end ();
List.erase (List.begin (), ihead);
};
BOOL Consume (t& T)//Fetch message
{
TypeName Tlist::iterator inext = Ihead;
++inext;
if (Inext!= itail)
{
Ihead = Inext;
t = *ihead;
return true;
}
return false;
};
BOOL Peek (t& T)//view message not deleted
{
TypeName Tlist::iterator inext = Ihead;
++inext;
if (Inext!= itail)
{
t = *inext;
return true;
}
return false;
}
BOOL IsEmpty ()
{
TypeName Tlist::iterator inext = Ihead;
++inext;
if (Inext!= itail)
{
return false;
}
Else
{
return true;
}
}
int Getmaxsize ()
{
return List.max_size ();
};
Private
typedef std::list<t> TLIST;
Tlist list;
TypeName Tlist::iterator Ihead, Itail;
};
#endif