怎样写ring buffer
时间: 2024-02-03 21:03:09 浏览: 66
xm-ring-buffer.tar.gz_RINGBUFFER_XMRING_buffer_circlebuffer_wayr
Ring buffer,也叫循环缓冲区,是一种常用的数据结构,用于在固定大小的缓冲区中存储数据。它可以避免在缓存区末尾时出现溢出的情况,而且可以很快地读取和写入数据。
下面是一个简单的ring buffer的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 10
typedef struct {
int *buffer;
int head;
int tail;
int size;
} RingBuffer;
RingBuffer *createRingBuffer(int size) {
RingBuffer *rb = malloc(sizeof(RingBuffer));
rb->buffer = malloc(sizeof(int) * size);
rb->head = 0;
rb->tail = 0;
rb->size = size;
return rb;
}
void destroyRingBuffer(RingBuffer *rb) {
free(rb->buffer);
free(rb);
}
int isRingBufferFull(RingBuffer *rb) {
return ((rb->tail + 1) % rb->size) == rb->head;
}
int isRingBufferEmpty(RingBuffer *rb) {
return rb->head == rb->tail;
}
void writeRingBuffer(RingBuffer *rb, int data) {
if (isRingBufferFull(rb)) {
printf("Ring buffer is full, can't write data!\n");
return;
}
rb->buffer[rb->tail] = data;
rb->tail = (rb->tail + 1) % rb->size;
}
int readRingBuffer(RingBuffer *rb) {
if (isRingBufferEmpty(rb)) {
printf("Ring buffer is empty, can't read data!\n");
return -1;
}
int data = rb->buffer[rb->head];
rb->head = (rb->head + 1) % rb->size;
return data;
}
int main() {
RingBuffer *rb = createRingBuffer(BUFFER_SIZE);
writeRingBuffer(rb, 1);
writeRingBuffer(rb, 2);
writeRingBuffer(rb, 3);
int data = readRingBuffer(rb);
printf("Read data: %d\n", data);
writeRingBuffer(rb, 4);
writeRingBuffer(rb, 5);
data = readRingBuffer(rb);
printf("Read data: %d\n", data);
data = readRingBuffer(rb);
printf("Read data: %d\n", data);
data = readRingBuffer(rb);
printf("Read data: %d\n", data);
data = readRingBuffer(rb);
printf("Read data: %d\n", data);
data = readRingBuffer(rb);
printf("Read data: %d\n", data);
destroyRingBuffer(rb);
return 0;
}
```
以上是使用C语言实现的ring buffer,其中包含了创建、销毁、写入数据和读取数据等操作的函数。在使用时,先创建一个指定大小的ring buffer,然后可以利用writeRingBuffer函数写入数据,利用readRingBuffer函数读取数据。在写入数据时,如果ring buffer已满,则会提示无法写入数据;在读取数据时,如果ring buffer为空,则会提示无法读取数据。在使用完毕后,需要调用destroyRingBuffer函数销毁ring buffer,释放内存空间。
阅读全文