循环队列 作为消息队列

为了避免消息队列频繁的申请和释放内存,采用循环队列作为消息队列。

queue.h:

#ifndef INC_QUEUE_H_
#define INC_QUEUE_H_

#include <pthread.h>
#include <iostream>
using namespace std;

#define MAX_QUEUE_SIZE  500000
#define SINGLE_DATA_SIZE 1024

class Queue
{
public:
    Queue(int maxSize = MAX_QUEUE_SIZE, int singleDataSize = SINGLE_DATA_SIZE);
    ~Queue();

public:
    static Queue* getInstance();
    string pop();
    bool enqueue(const string& str);
    bool dequeue(string& str);
    bool isEmpty()const;
    bool isFull()const;

private:
    int m_maxSize;
    string* m_pBase;//内存的使用地址
    int m_front; //第一个元素的. 出队列时要取的元素
    int m_rear;//最后一个元素的下一个元素

    static Queue* m_queue;
};


#endif /* INC_QUEUE_H_ */

queue.cpp

#include "queue.h"

Queue* Queue::m_queue = NULL;

Queue::Queue(int maxSize, int bufSize)
{
    m_maxSize = maxSize;
    m_pBase = new string[maxSize * bufSize];
    //to do 申请失败
    m_front = 0;
    m_rear = 0;
}

Queue::~Queue()
{
    if(m_pBase)
        delete []m_pBase;
}

Queue* Queue::getInstance()
{
    if(!Queue::m_queue)
    {
        m_queue = new Queue();
        return m_queue;
    }

    return m_queue;
}

//循环队列保留一个不可用的节点
bool Queue::isFull()const
{
    return m_front == (m_rear + 1)%m_maxSize;
}

bool Queue::isEmpty()const
{
    return m_front == m_rear;
}

string Queue::pop()
{
    return m_pBase[m_front];
}

bool Queue::enqueue(const string& str)
{
    if(isFull())
        return false;

    m_pBase[m_rear] = const_cast<char*>(str.c_str());
    m_rear = (m_rear + 1)%m_maxSize;

    return true;
}

bool Queue::dequeue(string& str)
{
    if(isEmpty())
        return false;

    str = m_pBase[m_front];
    m_front = (m_front + 1)%m_maxSize;
    return true;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值