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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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. */ `
consume an item means retrieve it's value and no longer access it.
"The comment refers to the previously two lines." - which, I'd add, ought to be illegal.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.