我正在尝试用C实现一个通用循环缓冲区(队列)。这是我目前的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
CIRCLEQ_HEAD(circleq, entry) head;
struct circleq *headp; /* Circular queue head. */
struct entry {
CIRCLEQ_ENTRY(entry) entries; /* Circular queue. */
int number;
};
int main()
{
CIRCLEQ_INIT(&head);
// Add some numbers to the queue
int i;
for (i = 0; i < 10; i++) {
struct entry* n = malloc(sizeof(struct entry));
n->number = i;
CIRCLEQ_INSERT_HEAD(&head, n, entries);
printf("Added %d to the queue\n", n->number);
}
// Remove a number from the queue
struct entry *n;
n = CIRCLEQ_FIRST(&head);
CIRCLEQ_REMOVE(&head, head.cqh_first, entries);
printf("Removed %d from the queue\n", n->number);
return 0;
}
产生以下输出:
Added 0 to the queue
Added 1 to the queue
Added 2 to the queue
Added 3 to the queue
Added 4 to the queue
Added 5 to the queue
Added 6 to the queue
Added 7 to the queue
Added 8 to the queue
Added 9 to the queue
Removed 9 from the queue
我对C不太熟悉,我的问题是:
如何设置队列限制,例如,只有5个数字 可以一次装进缓冲区吗?如果尝试其他项目 在此之后添加,我应该能够检测到它并做一些事情 关于它(忽略它,等待,退出程序等)。
似乎我的代码从缓冲区中移除了最后一项 - 我怎么能 让它从尾部删除项目(数字0而不是9,在我的 例子)?
我已阅读http://linux.die.net/man/3/queue,但似乎并不清楚如何完成上述两件事。
答案 0 :(得分:1)
如果你看一下circular-buffer的描述,这种缓冲区的一个主要好处是它使用一个固定的分配,而你的基本只是一个循环链接列表。创建时使用的固定大小指定了环形缓冲区可以容纳的元素数量的限制。
如果你有一个正确实现的循环缓冲区,删除一个项目只需要推进尾部指针,必要时回到前面。
表示循环缓冲区的示例结构可能如下所示:
struct circleq
{
int* buf;
int head;
int tail;
int size;
};
void init(struct circleq* q, int size)
{
q->buf = malloc(sizeof(int) * size);
q->head = 0;
q->tail = size - 1;
q->size = size;
}
void insert(struct circleq* q, int val)
{
if(q->head == q->tail) { } // queue full, error
else
{
q->buf[q->head] = val;
q->head = (q->head + 1) % q->size;
}
}
int remove(struct circleq* q)
{
if((q->tail + 1) % q->size == q->head) { return 0; } // queue empty, error
else
{
int val = q->buf[q->tail];
q->tail = (q->tail + 1) % q->size;
return val;
}
}
void destroy(struct circleq* q)
{
free(q->buf);
}