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?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
bruce12
  • 85
  • 1
  • 4

3 Answers3

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.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
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.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • 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. */ ` – bruce12 Sep 19 '11 at 22:11
  • consume an item means retrieve it's value and no longer access it. – Heisenbug Sep 19 '11 at 22:13
  • 1
    "The comment refers to the previously two lines." - which, I'd add, ought to be illegal. – Steve Jessop Sep 19 '11 at 23:11
0

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

nulvinge
  • 1,600
  • 8
  • 17