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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With