This article provides an implementation code for the C ++ lock-free queue, which is mainly used for one thread to read data and write data in another thread.
Copy codeThe Code is as follows: # ifndef LOCK_FREE_QUEUE_H _
# Define LOCK_FREE_QUEUE_H _
// No lock queue, suitable for reading by one thread and writing by one thread
# Include <list>
Template <typename T>
Class LockFreeQueue
{
Public:
LockFreeQueue ()
{
List. push_back (T (); // split the node
IHead = list. begin ();
ITail = list. end ();
};
Void Produce (const T & t) // store messages
{
List. push_back (t );
ITail = list. end ();
List. erase (list. begin (), iHead );
};
Bool Consume (T & t) // retrieves the message
{
Typename TList: iterator iNext = iHead;
++ INext;
If (iNext! = ITail)
{
IHead = iNext;
T = * iHead;
Return true;
}
Return false;
};
Bool Peek (T & t) // check that the message is 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