Does this circular buffer implementation require a semaphore?

1.1k views Asked by At

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.

1

There are 1 answers

1
Bernhard Barker On

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/or count = count - 1 is not atomic. If it's not atomic, something like this can happen:

count = 1 // initial value
Get count for "count = count + 1" as 1
Get count for "count = count - 1" as 1
count = 1 + 1 = 2
count = 1 - 1 = 0

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.