循环缓冲区的用途
循环缓冲区主要用在文件系统中,和FIFO队列进行互补,特点是读写指针互不干扰,适用于经典的生产者消费者问题,相关原理已有相关博主解释。
循环缓冲区的定义
struct TRingBuf {
char *buf;
char *end_pos_;
char *read_pos_;
char *write_pos_;
//int data_size_;
int data_write_size_;
int data_read_size_;
};
void TRingBufCreate(struct TRingBuf *self, void *buf, int buf_size);//construct
void TRingBufWrite(struct TRingBuf *self, void *data, int data_size);
void TRingBufRead(struct TRingBuf *self, void *buf, int buf_size);
void TRingBufClear(struct TRingBuf *self);//destruct
int TRingBufSize(struct TRingBuf *self);
int TRingBufFreeSize(struct TRingBuf *self);
int TRingBufDataSize(struct TRingBuf *self);
需要的头文件如下:
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
循环缓冲区的实现
#include "c_cache.h"
void TRingBufCreate(struct TRingBuf *self, void *buf, int buf_size) {
self->buf = (char*)buf;
self->write_pos_ = (char*)buf;
self->read_pos_ = (char*)buf;
self->end_pos_ = (char*)buf + buf_size;
//self->data_size_ = 0;
self->data_read_size_ = 0;
self->data_write_size_ = 0;
}
void TRingBufClear(struc