Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular buffer implementation in C

I have found pseudo code on how to implement a circular buffer.

// Producer.
while (true) {
  /* produce item v */
  while ((in+1)%n == out)
    /* Wait. */;
  b[in] = v;
  in = (in + 1) % n
}

// Consumer.
while (true) {
  while (in == out)
    /* Wait. */;
  w = b[out];
  out = (out + 1) % n;
  /* Consume item w. */
}

What I don't understand is the "Consume item w." comment, because I think that with w = b[out]; we are consuming w, aren't we?

like image 789
bruce12 Avatar asked Sep 19 '11 22:09

bruce12


People also ask

How would you implement a circular buffer?

Circular Buffers can be implemented in two ways, using an array or a linked list. An empty object array along with its capacity is initialized inside the constructor as the type of elements added is unknown. Two pointers namely head and tail are maintained for insertion and deletion of elements.

How does a circular buffer work?

A circular buffer is a utility used to transfer successive data values from a producer thread to a consumer thread, who retrieves the data in FIFO (first in first out) order. This kind of data structure will be used when pipelining threads, a subject discussed in detail in Chapter 15.

What is circular buffer in embedded system?

August 2022) In computer science, a circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams.


1 Answers

With

w = b[out];

You only grab a copy of the item to be consumed. With

out = (out + 1) % n;

You advance the index of the item to be consumed, thereby preventing it from being referenced again.

In a manner, multiple calls to w = b[out]; don't actually consume the buffer's slot, it just accesses it; while out = (out + 1) % n; prevents further access of that item. Preventing further access of the buffer item is the strongest definition of the term "consume the item" that I can think of.

like image 162
Edwin Buck Avatar answered Sep 17 '22 20:09

Edwin Buck