环形缓冲区,也称为循环缓冲区或环形队列,是一种数据结构,它在固定大小的数组中存储数据。当缓冲区满时,新的数据会覆盖旧的数据,从而形成一个“环形”的效果。这种数据结构在多线程编程、实时系统和嵌入式系统中非常有用,因为它可以高效地处理数据的读写操作。
以下是一个简单的单生产者单消费者环形缓冲区的实现示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define BUFFER_SIZE 10
typedef struct {
int buffer[BUFFER_SIZE];
int head;
int tail;
int count;
pthread_mutex_t lock;
pthread_cond_t not_empty;
pthread_cond_t not_full;
} CircularBuffer;
void cb_init(CircularBuffer *cb) {
cb->head = 0;
cb->tail = 0;
cb->count = 0;
pthread_mutex_init(&cb->lock, NULL);
pthread_cond_init(&cb->not_empty, NULL);
pthread_cond_init(&cb->not_full, NULL);
}
void cb_push(CircularBuffer *cb, int item) {
pthread_mutex_lock(&cb->lock);
while (cb->count == BUFFER_SIZE) {
pthread_cond_wait(&cb->not_full, &cb->lock);
}
cb->buffer[cb->head] = item;
cb->head = (cb->head + 1) % BUFFER_SIZE;
cb->count++;
pthread_cond_signal(&cb->not_empty);
pthread_mutex_unlock(&cb->lock);
}
int cb_pop(CircularBuffer *cb) {
pthread_mutex_lock(&cb->lock);
while (cb->count == 0) {
pthread_cond_wait(&cb->not_empty, &cb->lock);
}
int item = cb->buffer[cb->tail];
cb->tail = (cb->tail + 1) % BUFFER_SIZE;
cb->count--;
pthread_cond_signal(&cb->not_full);
pthread_mutex_unlock(&cb->lock);
return item;
}
void *producer(void *arg) {
CircularBuffer *cb = (CircularBuffer *)arg;
for (int i = 0; i < 20; i++) {
cb_push(cb, i);
printf("Produced: %d\n", i);
}
return NULL;
}
void *consumer(void *arg) {
CircularBuffer *cb = (CircularBuffer *)arg;
for (int i = 0; i < 20; i++) {
int item = cb_pop(cb);
printf("Consumed: %d\n", item);
}
return NULL;
}
int main() {
CircularBuffer cb;
cb_init(&cb);
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, &cb);
pthread_create(&consumer_thread, NULL, consumer, &cb);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
通过以上内容,你应该对Linux环形缓冲区有了一个全面的了解,包括其基础概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云