如何实现在C循环列表(环形缓冲区)? [英] How do I implement a circular list (ring buffer) in C?

查看:192
本文介绍了如何实现在C循环列表(环形缓冲区)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何实现一个覆盖最早的条目时,它的全循环列表?

How do I implement a circular list that overwrites the oldest entry when it's full?

有关的一些背景,我想使用GWT内循环列表;所以使用第三方lib目录为不可以我想要什么。

For a little background, I want to use a circular list within GWT; so using a 3rd party lib is not what I want.

推荐答案

在C. pssed一个非常简单的实现,前$ P $实现一个环形缓冲区风格FIFO队列。可以作出通过创建包含队列大小的结构更通用的,排队的数据,和队列索引(输入和输出),这将与数据传递中从队列中添加或删除。然后,这些相同的程序可以处理多个队列。另外请注意,这使得任何规模的队列,虽然可以加速比,如果您使用的2权力和自定义code再被使用。

A very simple implementation, expressed in C. Implements a circular buffer style FIFO queue. Could be made more generic by creating a structure containing the queue size, queue data, and queue indexes (in and out), which would be passed in with the data to add or remove from the queue. These same routines could then handle several queues. Also note that this allows queues of any size, although speedups can be used if you use powers of 2 and customize the code further.

/* Very simple queue
 * These are FIFO queues which discard the new data when full.
 *
 * Queue is empty when in == out.
 * If in != out, then 
 *  - items are placed into in before incrementing in
 *  - items are removed from out before incrementing out
 * Queue is full when in == (out-1 + QUEUE_SIZE) % QUEUE_SIZE;
 *
 * The queue will hold QUEUE_ELEMENTS number of items before the
 * calls to QueuePut fail.
 */

/* Queue structure */
#define QUEUE_ELEMENTS 100
#define QUEUE_SIZE (QUEUE_ELEMENTS + 1)
int Queue[QUEUE_SIZE];
int QueueIn, QueueOut;

void QueueInit(void)
{
    QueueIn = QueueOut = 0;
}

int QueuePut(int new)
{
    if(QueueIn == (( QueueOut - 1 + QUEUE_SIZE) % QUEUE_SIZE))
    {
        return -1; /* Queue Full*/
    }

    Queue[QueueIn] = new;

    QueueIn = (QueueIn + 1) % QUEUE_SIZE;

    return 0; // No errors
}

int QueueGet(int *old)
{
    if(QueueIn == QueueOut)
    {
        return -1; /* Queue Empty - nothing to get*/
    }

    *old = Queue[QueueOut];

    QueueOut = (QueueOut + 1) % QUEUE_SIZE;

    return 0; // No errors
}

这篇关于如何实现在C循环列表(环形缓冲区)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆