Code for parsing the C ++ lock-free queue

Source: Internet
Author: User
Tags lock queue

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.