In the project, threads need to share a buffer FIFO queue, one thread adds data to the queue, and the other thread obtains data (typical producer-consumer problem ). We started to consider using STL vector containers without random access. Frequent deletion of the first element causes memory movement, reducing efficiency. If you use linklist as a queue, you also need to allocate and release node memory frequently. Therefore, you can implement a limited-size FIFO queue and directly use Arrays for Ring reading.
Read/write of the queue needs to be synchronized in the external process thread (another rwguard class is written, see another article)
To the targeted simplicity of the project, a simple circular Buffer Queue is implemented, which is simpler than the STL vector.
PS: when using the template for the first time, the definition of the original class template should be placed in the. h file. Otherwise, a connection error will occur.
Template <class _ type>
Class c0000queue
{
Public:
Csharequeue ();
Csharequeue (unsigned int bufsize );
Virtual ~ Csharequeue ();
_ Type pop_front ();
Bool push_back (_ type item );
// Return capacity
Unsigned int capacity () {// warning: external data consistency is required.
Return m_capacity;
}
// Returns the current number.
Unsigned int size () {// warning: external data consistency is required
Return m_size;
}
// Whether it is full // warning: external control data consistency is required
Bool IsFull (){
Return (m_size> = m_capacity );
}
Bool IsEmpty (){
Return (m_size = 0 );
}
Protected:
UINT m_head;
UINT m_tail;
UINT m_size;
UINT m_capacity;
_ Type * pBuf;
};
Template <class _ Type>
C0000queue <_ Type >:: c0000queue (): m_head (0), m_tail (0), m_size (0)
{
PBuf = new _ Type [512]; // default value: 512
M_capacity = 512;
}
Template <class _ Type>
CShareQueue <_ Type >:: CShareQueue (unsigned int bufsize): m_head (0), m_tail (0)
{
If (bufsize> 512 | bufsize <1)
{
PBuf = new _ Type [512];
M_capacity = 512;
}
Else
{
PBuf = new _ Type [bufsize];
M_capacity = bufsize;
}
}
Template <class _ Type>
CShareQueue <_ Type> ::~ CShareQueue ()
{
Delete [] pBuf;
PBuf = NULL;
M_head = m_tail = m_size = m_capacity = 0;
}
// An element pops up.
Template <class _ Type>
_ Type c0000queue <_ Type>: pop_front ()
{
If (IsEmpty ())
{
Return NULL;
}
_ Type itemtmp;
Itemtmp = pBuf [m_head];
M_head = (m_head + 1) % m_capacity;
-- M_size;
Return itemtmp;
}
// Add a queue from the end
Template <class _ Type>
Bool c0000queue <_ Type>: push_back (_ Type item)
{
If (IsFull ())
{
Return FALSE;
}
PBuf [m_tail] = item;
M_tail = (m_tail + 1) % m_capacity;
+ M_size;
Return TRUE;
}
# Endif //! Defined (_ daly_c1_queue_h _)