现在的位置: 首页 > 综合 > 正文

C语言实现队循FIFO缓冲区-《30天自制操作系统》

2013年08月08日 ⁄ 综合 ⁄ 共 1271字 ⁄ 字号 评论关闭

本代码整理自《30天自制操作系统》P135的整理FIFO缓冲区

写的很好,所以记录一下(增加了一个fifo8_free函数,用于查询剩余容量,觉得有用)。作者实现的是char类型的缓冲区,但是可以用你要传的任意结构体来替换~~~

fifo8.h

/*溢出标志:0-正常,-1-溢出*/
#define FLAGS_OVERRUN 0x0001
/*
        buf- 缓冲区地址
        size- 大小
        free- 空余容量
        putP- 下一个数据写入位置
        getP- 下一个数据独处位置
*/
struct FIFO8{
         unsigned char *buf;
         int putP,getP,size,free,flags;
};

void fifo8_init(struct FIFO8 *fifo,int size, unsigned char *buf);
int fifo8_put(struct FIFO8 *fifo,unsigned char data);
int fifo8_get(struct FIFO8 *fifo);
int fifo8_status(struct FIFO8 *fifo);
int fifo8_free(struct FIFO7 *fifo);

fifo8.c

#include "fifo8.h"
void fifo8_init(struct FIFO8 *fifo,int size, unsigned char *buf)
/*初始化*/
{
        fifo->buf=buf;
        fifo->flags=0;          
        fifo->free=size;
        fifo->size=size;
        fifo->putP=0;                   
        fifo->getP=0;                   

         return;
}
int fifo8_putPut(struct FIFO8 *fifo,unsigned char data)
/*向FIFO 中写入数据 */
{
         if(fifo->free==0){
                fifo->flags |= FLAGS_OVERRUN;
                 return -1;
        }
        fifo->buf[fifo->putP] = data;
        fifo->putP++;
         //循环队列缓冲区
         if(fifo->putP == fifo->size){
                fifo->putP = 0;
        }
        fifo->free--;

         return 0;
}
int fifo8_get(struct FIFO8 *fifo)
/*从FIFO 中取出一个数据 */
{
         int data;
         if(fifo->free == fifo->size){
                 return -1;
        }
        data = fifo->getP;
        fifo->getP++;
         if(fifo->getP == fifo->size){//用来实现循环
                fifo->getP = 0;
        }
        fifo->free++;
        
         return data;
}
int fifo8_status(struct FIFO8 *fifo)
/*缓冲区被使用容量*/
{
         return fifo->size-fifo->free;
}
int fifo8_free(struct FIFO8 *fifo)
/*缓冲区剩余容量*/
{
         return fifo->free;
}

学习的地方:返回值为void时可以return;循环缓冲区的构造;溢出标志设定;

【上篇】
【下篇】

抱歉!评论已关闭.