Click to See Complete Forum and Search --> : handling buffers efficiently
cppdud
March 17th, 2005, 07:50 PM
i am loosing data and feel like i need some little
good tutorial on how to implement an efficient circular buffer.
If i got a buffer of size k. how to add data to it
and at the same time read data out?. I hope this
make it real time like process so that data would
not get lost. any example,..??
cilu
March 18th, 2005, 08:14 AM
At the point when the buffer gets fulled with written data, you must override the first elements.
Can you explain what are you actually trying to do?
T.G.
March 18th, 2005, 08:26 AM
something like this?
class CircularBuffer
{
int size, front, back;
vector<int> data;
public:
CircularBuffer() : size(0), data(1), front(0), back(0) {}
CircularBuffer(int k) : size(k-1), data(k), front(0), back(0) {}
void push_back(int i) { if (++back>size) back=0; data[back]=i;}
void pop_back(int &i) { i=data[back];if (--back<0) back=size;}
void push_front(int i) { if (--front<0) front=size; data[front]=i;}
void pop_front(int &i) { i=data[front];if (++front>size) front=0;}
}
cppdud
March 18th, 2005, 09:57 AM
can you add main() that uses this class as a ring or circular buffer?. i created template based of a ring buffer that works ok. i have to clean it up , then i 'll post it.
cppdud
March 18th, 2005, 01:54 PM
two examples of circular buffer appliction that handles:
1) simultaneous read and write operations.
2) serialized read and write.
this is very important to me to understand if one has an exmples of each.
cppdud
March 19th, 2005, 04:21 PM
like to fit "writetobuf" and "readnextbuf" into threads for fast speed
write / read but not quite sure how.
Any changes and adds that improve things be nice.
int InsertNextIndex = 0;
int ReadNextIndex = 0;
#define imgIndex 20
BYTE *images[imgIndex];
bool imgIndexUsed[imgIndex];
void SetImageSize(int height, int width,
int numofbytesPerPixel = 4)
{
imagesz = height*width*numofbytesPerPixel;
}
void BufInit(void)
{
int i;
for (i=0; i<imgIndex; i++)
{
imgIndexUsed[i] = false;
images[i] = new BYTE[imagesz];
}
}
bool WriteToBuf(BYTE *pdata)
{
if (imgIndexUsed[InsertNextIndex])
return(false);
imgIndexUsed[InsertNextIndex] = true;
memcpy(images[InsertNextIndex], pdata, imagesz);
InsertNextIndex++;
if (InsertNextIndex==imgIndex) InsertNextIndex = 0;
return(true);
}
BYTE *ReadNextBuf(void)
{
if (!imgIndexUsed[ReadNextIndex])
return null;
return(images[ReadNextIndex]);
}
void NextBufPrep(void)
{
if (!imgIndexUsed[ReadNextIndex]) return;
imgIndexUsed[ReadNextIndex] = false;
ReadNextIndex++;
if (ReadNextIndex==imgIndex) ReadNextIndex = 0;
}
void bufdestroy()
{
int i;
for (i=0; i<imgIndex; i++)
delete [] images[i];
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.