Hi
This implementation and the one suggested by Mr Benry above have a
flaw .
If the writing and reading are happening at different speeds which
would be the case
and which is the whole idea behind the circular queues (to discard the
old data and to get the old data first and then the new data of the
sna shot we have in the queue ).
After the buffer is full and the write starts writing in the beginning
, but the reader
in the situation where it gets to the beginning and start reading from
there could find the
latest data there and after some time when it gets to the next index it
could find old data
there , i.e it could get latest data at some time and a little later
could get old data which should not be the case .
please clarify if iam wrong
Please don't top-post (i.e., you reply goes after what you're replying
to). You are correct that the code below may read data out of order.
To get around this you need to keep track of more information. Here's
one approach off the top of my head-- it may not be optimal.
Keep a couple boolean state variables:
bool bufferEmpty; // initially true
bool bufferFull; // initially false
bufferEmpty = true means there's nothing available to read.
bufferFull = true means the entire contents of the buffer have been
written to but not been read.
Now you have to devise rules for reading and writing that update these
quantities appropriately:
If bufferEmpty:
read = error
write = advance write index, unset bufferEmpty
If bufferFull:
read = advance read index; unset bufferFull
write = advance read and write indices
If !bufferEmpty && !bufferFull:
read = advance read index; if read index = write index, set bufferEmpty
write = advance write index; if read index = write index, set bufferFull
Like I said, this is improvised so you should check it and correct it if
needed. Hope that helps.
-Mark
Thanks
subra
Depends upon design, and how fluffy you want your component to be,
in either case, here's a fixed sized circular queue/buffer:
int CQ[1024];
void write(int t) {
static unsigned int idx = 0;
CQ[idx++%1024] = t;
}
int read() {
static unsigned int idx = 0;
return CQ[idx++%1024];
}
TB