CSData StructuresDiagramIntermediate
Ring Buffer
KO: 링 버퍼 (원형 버퍼)·EN: Ring Buffer·JA: リングバッファ
A fixed-size circular array connecting end back to start for zero-allocation O(1) streaming reads and writes
Table of Contents
Structure Diagram
Ring Buffer (Circular Queue) Fixed-Size Wrap-Around Cycle
1/41. Write at Head— buffer[head] = data
buffer[head] = dataQuick Answer
What is Ring Buffer?
A fixed-size circular array connecting end back to start for zero-allocation O(1) streaming reads and writes. It is a core concept in Data Structures within CS.
Core Principles
A Ring Buffer (Circular Buffer) uses a fixed-size contiguous array with read (tail) and write (head) indices that wrap around to 0 via (idx + 1) % capacity.
- Zero-Allocation
O(1)Throughput: Reusing pre-allocated slots eliminates heap allocations and GC pauses. - Cache-Friendly Layout: Contiguous memory maximizes CPU prefetching and cache-line utilization.
- Explicit Overflow Policy: When full, systems either overwrite the oldest entries (telemetry/audio) or apply backpressure to producers (queues/IPC).
Practical Takeaways
- Use power-of-two capacities: Replace expensive modulo (
% N) with fast bitwise masking (idx & (N - 1)). - Lock-free SPSC queues: When one thread writes
headand another readstail, atomic acquire/release semantics suffice without mutexes. - Prevent False Sharing: Pad
headandtailonto separate 64-byte cache lines so producer and consumer cores don't invalidate each other's caches.
Notable Examples
- Linux
io_uring& NIC RX/TX Rings: High-throughput kernel/user-space async I/O rings. - Real-time Audio & Video Pipelines: Smoothing jitter between capture and playback hardware.
- LMAX Disruptor & Kernel
dmesg: Ultra-low-latency event buses and rolling system log buffers.