I am implementing the circular buffer as below:
long windex = 0, rindex = 0, count = 0;
producer_ISR() /* whenever the data avail, then gets the interrupt */
{
/* store the data in array buffer */
array[windex] = data;
windex++;
count = count + 1; /* Increment the count */
if (windex == 32) /* overflow condition */
windex = 0;
}
consumer
{
while(1)
{
if(count > 0)
{
/* process the data */
data1 = array[rindex];
rindex++;
count = count - 1; /* decrement the count */
if (rindex == 32 ) /* overflow condition */
rindex = 0;
}
}
}
Does this code requires the semaphore to protect the shared variable "count" between the above two functions?
As per my analysis, the semaphore is not required, please share your ideas.
If there can be multiple consumers, you need a semaphore since 2 consumers can check the count, then consume the same element, or one can try to consume an element that doesn't exist.
Similarly for producers.
If there can only be 1 consumer and 1 producer, you only need a semaphore if
count = count + 1
and/orcount = count - 1
is not atomic. If it's not atomic, something like this can happen:Then you have
count = 0
when there's actually an item waiting.Also note that the code probably needs some error checking if the buffer fills up.