环形缓冲区的实现

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

#pragmaonce
#include
"stdio.h"
#include
"stdlib.h"
#include
"memory.h"

namespaceLinker
{

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

boolPut(ElementType&e)
{
if(!IsFull())
{
_elements[_last
++]=e;
_last
%=_size;
returntrue;
}
else
{
returnfalse;
}
}

boolGet(ElementType&e)
{
if(IsEmpty())
{
returnfalse;
}
else
{
e
=_elements[_first++];
_first
%=_size;
returntrue;
}
}

unsigned
intInUse()
{
if(_last>_first)
{
return_last-_first;
}
elseif(_first>_last)
{
return_size-(_first-_last);
}
else
{
return0;
}
}

unsigned
intFreeElementNum()
{
return_fullSize-InUse();
}

unsigned
intTotalSize()
{
return_fullSize;
}

boolIsFull()
{
returnInUse()==_fullSize;
}
boolIsEmpty()
{
returnInUse()==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"

usingnamespaceLinker;

intmain()
{
unsigned
intj=1;
Ring
<unsignedint,12>clockRing;
printf(
"StartInUse:%d ",clockRing.InUse());
clockRing.Put(j);
clockRing.Put(j);
printf(
"AfterPut1,1InUse:%d ",clockRing.InUse());
clockRing.Get(j);
for(unsignedinti=0;i<12;i++)
clockRing.Put(i);
clockRing.Get(j);
j
=100;
clockRing.Put(j);
for(unsignedinti=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、付费专栏及课程。

余额充值