前言
循环数组主要是数据结构时一个定长数组+读和写的指针一般用于缓存,但是如果超过数组长度就会发生丢失。为了防止丢失,需要再加一层缓存。
一、说明
- 统一缓存的结构(Msg)使用一个长度加字节数组的指针
- RingBuffer主要结构为定长数组+读写指针,为了不发生丢失再使用C++STL中vector来再做一次缓存
- 当定长数组中的剩余空间小于总长度的1/3,才到vector中拉取内容。
- 主要优点:内存使用率高,不会发生丢失。
二、代码
1.实现
#pragma once
#include <vector>
#include <mutex>
#include <stdlib.h>
#include <string.h>
class Msg{
public:
unsigned int size;
const char* ptr;
unsigned long seq;
public:
Msg():size(0),ptr(NULL),seq(0){
}
Msg(unsigned int s, const char *p, unsigned long sq):size(s), ptr(p), seq(sq){
}
};
template <unsigned int QueueSize = 1024>
class RingBuffer{
private:
std::mutex mtx;
std::vector<Msg> msgBuffer;
Msg msgQueue[QueueSize];
unsigned int m_writeIdx;
unsigned int m_readIdx;
bool m_empty;
bool m_full;
public:
RingBuffer(){
m_readIdx =0;
m_writeIdx = 0;
m_empty = false;
m_full = false;
}