Implementing a ring buffer
I see that the user is asking about implementing a ring buffer in C, likely focusing on high-speed data acquisition. I should prepare an explanation that includes code, emphasizing efficiency like lock-free and low-latency designs. First, I need to gather requirements around single-producer single-consumer setups.
I'll assume a typical setup with a power-of-two buffer size, using modulo indexing. Implementing with C11 atomics is important too, as well as addressing cache alignment, memory barriers, and providing a complete C implementation with a header and source. I'll outline those details clearly.Implementing a ring buffer in C
In C, since there's no built-in support for generics, I can implement a ring buffer for bytes or user-defined structs using macros. It might be best to allow for arbitrary element types, though a straightforward example with int16_t ADC samples is solid too.
For efficiency in high-speed scenarios, I'll avoid memmove and copy element-by-element instead. I’ll define a ring buffer to hold uint16_t items with the appropriate structure, including thread-safe access for a single producer and consumer, using memory ordering for indices.Considering concurrency in ring buffer
If I don't include <stdatomic.h>, I can mention volatile, but it's not enough for high-speed scenarios. Since the user is interested in C11 atomics, I'll aim for portability, although some embedded compilers may not fully support it. I need to follow concurrency best practices using _Atomic size_t head; and others.
I'll provide functions for ring_buffer_spsc_push and pop, while also noting any restrictions. Even though the user didn't ask for an explanation, it's important to be concise but still include necessary usage notes and considerations for DMA, as it requires contiguous memory.Drafting ring buffer code
Let's draft the code for the ring buffer, which will include a header file defining the buffer structure, its size (must be a power of two), and atomic indices for reading and writing.
I’ll implement functions for initializing the buffer, checking its capacity, counting items, and calculating free space. The write function will handle non-blocking writes, returning the number of bytes actually written while following a high-speed approach with minimal branches. It’ll ensure the correct use of power-of-two for efficient modulo operations. Overall, this should make for a smooth implementation!Designing the ring buffer implementation
I need to revise the ring buffer code to include <string.h> and verify that the capacity stays in line with the design's constraints. Since the user is interested in high-speed data acquisition, I’ll focus on maintaining a separate head and tail that won't overflow. I must specify relevant functions like rb_init, rb_push, and rb_pop for single producer single consumer contexts and document potential pitfalls, particularly with concurrency.
I'll keep explanations concise while ensuring correct usage of atomic operations. For efficiency, the ring buffer size should preferably be a power of two, and I’ll include checks for that. I also need to make provisions for bulk operations while ensuring portability and performance. It's important to mention assumptions but maintain a focus on the core implementation without diving too deep into the nitty-gritty.Defining the ring buffer structure
I'm structuring the ring buffer implementation using _Alignas for proper alignment of the head, tail, and data array to optimize performance. I’m taking into account that some embedded MCUs may have smaller caches, so I'll mention alignment as an optional optimization without overcomplicating the code.
For a single-producer, single-consumer setup, I need to ensure atomic operations are used appropriately. The producer will update the head after writing data, while the consumer will update the tail after reading. I’ll also clarify that these counters should remain within safe limits to avoid ambiguity even with wrap-around behavior.
The ring buffer will include basic operations like writing and reading data while ensuring modular arithmetic works correctly across increments. I'll provide the code in a single translation unit for clarity and simplicity. It’s crucial to document usage, especially in high-speed data acquisition contexts, while keeping explanations concise to focus on functionality.Structuring the response
I'm thinking it’s best to mark the functions as static inline to make including the header file straightforward for the user. Now, it’s time to craft my final message.
I want to start with a brief introductory text explaining what the code does. Then, I’ll include the code itself, ensuring it’s clear and easy to read. Finally, I’ll wrap things up with some closing bullet points that highlight the main features or usage notes for the ring buffer. That's the plan! Below is a compact, high-speed, single-producer/single-consumer (SPSC) ring buffer implementation in C, suitable for data-acquisition pipelines (e.g., ISR/DMA or producer thread feeding a consumer thread).
It uses:
- Fixed power-of-two size for fast index masking
- C11 atomics for lock-free synchronization
- 16-bit sample type (easy to change to any POD type)
/*
* ring_buffer.h - SPSC lock-free ring buffer for high-speed data acquisition
*
* One producer (e.g. ISR/DMA callback) and one consumer (e.g. processing thread).
* No locks; uses C11 atomics for correctness on all architectures.
*/
#ifndef RING_BUFFER_H
#define RING_BUFFER_H
#include <stdatomic.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
/* -------- Configuration -------- */
/* Element type stored in the buffer (ADC sample, etc.) */
typedef uint16_t rb_elem_t;
/* Must be a power of two: 256, 512, 1024, 2048, ... */
#ifndef RB_SIZE
#define RB_SIZE 4096u
#endif
#if (RB_SIZE & (RB_SIZE - 1u)) != 0
#error "RB_SIZE must be a power of two"
#endif
/* For correctness with 32-bit indices, keep capacity <= 2^31 */
#if (RB_SIZE > (1u << 31))
#error "RB_SIZE too large for 32-bit indices"
#endif
#define RB_MASK (RB_SIZE - 1u)
/* -------- Data structure -------- */
typedef struct {
rb_elem_t data[RB_SIZE];
_Atomic uint32_t head; /* write index (producer only writes) */
_Atomic uint32_t tail; /* read index (consumer only writes) */
} ring_buffer_t;
/* -------- Basic operations -------- */
/* Initialize buffer to empty state */
static inline void rb_init(ring_buffer_t *rb)
{
atomic_store_explicit(&rb->head, 0u, memory_order_relaxed);
atomic_store_explicit(&rb->tail, 0u, memory_order_relaxed);
}
/* Number of elements currently stored */
static inline uint32_t rb_count(const ring_buffer_t *rb)
{
uint32_t head = atomic_load_explicit(&rb->head, memory_order_acquire);
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_acquire);
return head - tail; /* modulo-2^32 arithmetic */
}
/* Capacity (maximum storable elements) */
static inline uint32_t rb_capacity(const ring_buffer_t *rb)
{
(void)rb;
return RB_SIZE;
}
/* Remaining free slots */
static inline uint32_t rb_free_space(const ring_buffer_t *rb)
{
return RB_SIZE - rb_count(rb);
}
/* -------- Single-element API (fast paths) -------- */
/* Try to push one element; returns false if buffer is full */
static inline bool rb_push(ring_buffer_t *rb, rb_elem_t value)
{
uint32_t head = atomic_load_explicit(&rb->head, memory_order_relaxed);
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_acquire);
if ((head - tail) == RB_SIZE) {
/* Buffer full */
return false;
}
rb->data[head & RB_MASK] = value;
/* Publish the new head after the data write */
atomic_store_explicit(&rb->head, head + 1u, memory_order_release);
return true;
}
/* Try to pop one element; returns false if buffer is empty */
static inline bool rb_pop(ring_buffer_t *rb, rb_elem_t *out)
{
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_relaxed);
uint32_t head = atomic_load_explicit(&rb->head, memory_order_acquire);
if (head == tail) {
/* Buffer empty */
return false;
}
*out = rb->data[tail & RB_MASK];
/* Publish the new tail after reading */
atomic_store_explicit(&rb->tail, tail + 1u, memory_order_release);
return true;
}
/* -------- Bulk read/write (for higher throughput) -------- */
/*
* Write up to 'n' elements from 'src' into the buffer.
* Returns the number of elements actually written (0..n).
*/
static inline size_t rb_write(ring_buffer_t *rb, const rb_elem_t *src, size_t n)
{
uint32_t head = atomic_load_explicit(&rb->head, memory_order_relaxed);
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_acquire);
uint32_t used = head - tail;
uint32_t free = RB_SIZE - used;
if (n > free)
n = free;
if (n == 0)
return 0;
/* First contiguous chunk before wrap */
uint32_t idx = head & RB_MASK;
uint32_t first = RB_SIZE - idx;
if (first > n)
first = (uint32_t)n;
memcpy(&rb->data[idx], src, first * sizeof(rb_elem_t));
/* Second chunk (wrap-around) */
size_t second = n - first;
if (second) {
memcpy(&rb->data[0], src + first, second * sizeof(rb_elem_t));
}
atomic_store_explicit(&rb->head, head + (uint32_t)n, memory_order_release);
return n;
}
/*
* Read up to 'n' elements from buffer into 'dst'.
* Returns the number of elements actually read (0..n).
*/
static inline size_t rb_read(ring_buffer_t *rb, rb_elem_t *dst, size_t n)
{
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_relaxed);
uint32_t head = atomic_load_explicit(&rb->head, memory_order_acquire);
uint32_t available = head - tail;
if (n > available)
n = available;
if (n == 0)
return 0;
/* First contiguous chunk before wrap */
uint32_t idx = tail & RB_MASK;
uint32_t first = RB_SIZE - idx;
if (first > n)
first = (uint32_t)n;
memcpy(dst, &rb->data[idx], first * sizeof(rb_elem_t));
/* Second chunk (wrap-around) */
size_t second = n - first;
if (second) {
memcpy(dst + first, &rb->data[0], second * sizeof(rb_elem_t));
}
atomic_store_explicit(&rb->tail, tail + (uint32_t)n, memory_order_release);
return n;
}
#endif /* RING_BUFFER_H */
Usage example (conceptual):
#include "ring_buffer.h"
static ring_buffer_t rb;
/* Producer: e.g. ISR or acquisition thread */
void adc_isr(void)
{
rb_elem_t sample = /* read from ADC */;
(void)rb_push(&rb, sample); /* drop if full, or handle overflow */
}
/* Consumer: processing thread/main loop */
void process_loop(void)
{
rb_elem_t buf[256];
for (;;) {
size_t got = rb_read(&rb, buf, 256);
for (size_t i = 0; i < got; ++i) {
/* process buf[i] */
}
/* optional: sleep/yield if got == 0 */
}
}
To adapt:
- Change
rb_elem_t to your sample type (e.g., float, struct sample, etc.).
- Adjust
RB_SIZE to your desired power-of-two capacity.
- If you are on bare-metal without
<stdatomic.h>, you can:
- Remove atomics, make head/tail
volatile, and
- Protect cross-context access with interrupt disable/enable or other platform-specific barriers.