`
suoyihen
  • 浏览: 1360841 次
文章分类
社区版块
存档分类
最新评论

环形缓冲区的实现

 
阅读更多

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

#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 -_-! 还请告诉我一下哈~

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics