Ring buffer
In short: A ring buffer is a fixed-size memory region used like a circle. When the end is reached, it continues at the start.
In more detail: Two pointers (read and write) travel around the circle. New data is placed at the write position, older data taken at the read position. No copying or reallocating of memory is needed.
In Depth
- Full or empty: Both states have equal pointers. Distinguish them with a counter or a free gap.
- Overflow: Either writing stops or the oldest data is overwritten (for example for “the last 100 log lines”).
- Use: Audio buffers, network cards, keyboard input, logging, producer-consumer queues.
- Trick: With power-of-two sizes, a bit mask replaces the costly modulo operation.
See also: Semaphore