环形缓冲区的实现

一个简单的环形缓冲区,没有写加解锁的部分,用于多线程的话还是自己加吧.

#pragma once
#include
" stdio.h "
#include
" stdlib.h "
#include
" memory.h "

namespace Linker
{

template
< typenameElementType,unsigned int Size /* ,typenameLockName */ >
class Ring
{
public :
Ring()
{
//::memset(_elements,
0 , sizeof (ElementType));
_first
= 0 ;
_last
= 0 ;
_size
= Size;
_fullSize
= Size - 1 ;
}
~ Ring(){}

bool Put(ElementType & e)
{
if ( ! IsFull())
{
_elements[_last
++ ] = e;
_last
%= _size;
return true ;
}
else
{
return false ;
}
}

bool Get(ElementType & e)
{
if (IsEmpty())
{
return false ;
}
else
{
e
= _elements[_first ++ ];
_first
%= _size;
return true ;
}
}

unsigned
int InUse()
{
if (_last > _first)
{
return _last - _first;
}
else if (_first > _last)
{
return _size - (_first - _last);
}
else
{
return 0 ;
}
}

unsigned
int FreeElementNum()
{
return _fullSize - InUse();
}

unsigned
int TotalSize()
{
return _fullSize;
}

bool IsFull()
{
return InUse() == _fullSize;
}
bool IsEmpty()
{
return InUse() == 0 ;
}
protected :
unsigned
int _size;
unsigned
int _fullSize;
ElementType_elements[Size];
unsigned
int _first;
unsigned
int _last;
// LockName_lock;
};






测试代码:

#include " Ring.h "
#include
" stdio.h "

using namespace Linker;

int main()
{
unsigned
int j = 1 ;
Ring
< unsigned int , 12 > clockRing;
printf(
" StartInUse:%d " ,clockRing.InUse());
clockRing.Put(j);
clockRing.Put(j);
printf(
" AfterPut1,1InUse:%d " ,clockRing.InUse());
clockRing.Get(j);
for (unsigned int i = 0 ;i < 12 ;i ++ )
clockRing.Put(i);
clockRing.Get(j);
j
= 100 ;
clockRing.Put(j);
for (unsigned int i = 0 ;i < 12 ;i ++ )
{
if (clockRing.Get(j))
printf(
" %d " ,j);
else
printf(
" Empty! " );

}
printf(
" Get1,Put0-11,Get1,Put100,Get*12timesInUse:%d " ,clockRing.InUse());
}

说实话,这个类刚刚出炉没有仔细测试,如果有Bug -_-! 还请告诉我一下哈~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值