C++11风格的FIFO

一种C++11风格的FIFO,支持任意长度的数据读写。

做单元测试的时候发现支持的类型不够通用,所以改为模板类型。

当时用的编辑器不支持中文,没办法,就用英文写了点简单的注释,代码也很好懂,不多说,直接上代码。

template <typename T> //para T is fifo store type

class  XyFifo
{
public:
    // initial fifo size
    XyFifo(unsigned int size)                   
    {
        _fifoInputIndex = 0;
        _fifoOutputIndex = 0;
        _currentFifoHead = 0;
        _bufferSize = size+1;
        _fifoBuffer = new T[_bufferSize];
    };

    ~XyFifo()
    {
        delete[]_fifoBuffer;
        _fifoBuffer = nullptr;
    };

    //check whether the fifo is write full
    bool isWriteFull()
    {
        auto inputIndex = _fifoInputIndex;

        auto temp = (++inputIndex >= _bufferSize) ? 0 : inputIndex;

        if (temp == _fifoOutputIndex)
        {
            return true;
        }

        return false;
    };
    //check whether the fif
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当在多个任务同时读写同一资源的时候,就需要使用多线程管理。而其中的FIFO算法就是一种先进先出的调度算法。 在C语言中,实现FIFO算法的核心是一个队列结构。队列结构是一种线性结构,遵循先进先出的原则。在FIFO算法中,我们将需要执行的任务依次加入到队列中,然后按照队列中的顺序依次进行调度。当一个任务完成后,它将被从队列中移除,下一个任务将被执行。 以下是一个简单的用C语言实现FIFO算法的代码示例: #include<stdio.h> #define MAX 5 int queue[MAX]; int front=-1,rear=-1; void insert(int); int delete(); void display(); void main() { int choice, num; clrscr(); do { printf("\n MENU"); printf("\n 1. INSERT"); printf("\n 2. DELETE"); printf("\n 3. DISPLAY"); printf("\n 4. EXIT"); printf("\n Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: printf("\n Enter the element to be inserted: "); scanf("%d", &num); insert(num); break; case 2: num = delete(); if(num!=-1) printf("\n The deleted element is: %d", num); break; case 3: display(); break; case 4: exit(0); break; default: printf("\nInvalid Choice"); break; } }while(choice!=4); } void insert(int element) { if(rear==MAX-1) printf("\n Queue is full"); else { if(front==-1) front=0; rear++; queue[rear]=element; printf("\n Element inserted successfully"); } } int delete() { int value; if(front==-1 || front>rear) { printf("\n Queue is empty"); return -1; } else { value=queue[front]; front++; if(front>rear) front=rear=-1; printf("\n Deletion operation successful"); return (value); } } void display() { int i; if(rear==-1) printf("\n Queue is empty"); else { printf("\n Queue elements are: "); for(i=front;i<=rear;i++) printf("%d \n", queue[i]); } } 希望这段代码能够帮助你理解FIFO算法的实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值