Circular buffer implementation in C
Asked Answered
H

3

8

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?

Heida answered 19/9, 2011 at 22:0 Comment(0)
M
9

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.

Mailman answered 19/9, 2011 at 22:11 Comment(0)
E
1

these two lines are both part of consuming process:

w = b[out];
out = (out + 1) % n;

The first extract the value and the second increment the out index. The comment refers to the previously two lines.

Emmett answered 19/9, 2011 at 22:6 Comment(3)
when it says /* produce item v */ we need to assign v to a random number or something like that.. i thought we need a different process for ` /* Consume item w. */ `Heida
consume an item means retrieve it's value and no longer access it.Emmett
"The comment refers to the previously two lines." - which, I'd add, ought to be illegal.Carafe
H
0

Yes, because then it's out of the buffer, which the following row says is empty. Then we can process w.

Helban answered 19/9, 2011 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.