Implement a lock-free ring buffer in C for single-producer/single-consumer using C11 stdatomic.h memory barriers. It should support overwriting the oldest data when full in circular mode.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Designing SPSC lock-free ring buffer with overwrite
The plan is to implement a single-producer/single-consumer ring buffer using C11 atomic operations with acquire/release semantics, where the producer can advance the tail to overwrite the oldest data when full. This approach slightly breaks the usual exclusive-tail-write rule but is controlled via atomic fetch-add on tail for dropping elements, ensuring safe concurrent updates without locks.Confirming atomic tail updates safe for overwriting
Using atomic_fetch_add for both producer and consumer tail increments safely avoids lost updates despite concurrent increments; this may cause extra skipped items if consumer is slow, which fits the intended overwrite semantics. The plan is to implement the ring buffer with monotonic head/tail counters using acquire/release memory orders and modular indexing without assuming power-of-two capacity.
c
/*
* Lock–free single–producer/single–consumer ring buffer.
*
* - Uses C11 stdatomic.h for index variables.
* - Monotonic head/tail counters; index into the array with modulo capacity.
* - Optional overwrite mode: when full, the producer drops the oldest element.
*/
#include <stdatomic.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
/* Ring buffer of fixed-size elements */
struct spsc_ring {
atomic_size_t head; /* Next position to write (monotonic counter) */
atomic_size_t tail; /* Next position to read (monotonic counter) */
size_t capacity; /* Number of slots */
size_t elem_size; /* Size of each element in bytes */
bool overwrite; /* If true, overwrite oldest when full */
void *storage; /* Pointer to raw storage buffer */
};
/* Initialize a ring buffer with given capacity and element size. */
static inline bool
spsc_ring_init(struct spsc_ring *rb, size_t capacity,
size_t elem_size, bool overwrite)
{
if (!rb || capacity == 0 || elem_size == 0) {
return false;
}
rb->storage = malloc(capacity * elem_size);
if (!rb->storage) {
return false;
}
rb->capacity = capacity;
rb->elem_size = elem_size;
rb->overwrite = overwrite;
atomic_init(&rb->head, 0);
atomic_init(&rb->tail, 0);
return true;
}
/* Destroy/free resources. */
static inline void
spsc_ring_destroy(struct spsc_ring *rb)
{
if (!rb) return;
free(rb->storage);
rb->storage = NULL;
rb->capacity = 0;
}
/* Return true if buffer is empty. */
static inline bool
spsc_ring_empty(const struct spsc_ring *rb)
{
size_t head = atomic_load_explicit(&rb->head, memory_order_acquire);
size_t tail = atomic_load_explicit(&rb->tail, memory_order_acquire);
return head == tail;
}
/* Return true if buffer is full. */
static inline bool
spsc_ring_full(const struct spsc_ring *rb)
{
size_t head = atomic_load_explicit(&rb->head, memory_order_relaxed);
size_t tail = atomic_load_explicit(&rb->tail, memory_order_acquire);
return (head - tail) >= rb->capacity;
}
/*
* Push one element into the ring.
* Returns true if element was enqueued. If the buffer is full and overwrite is
* false, returns false. If overwrite is true, the oldest element is dropped and
* the new element is written.
*/
static inline bool
spsc_ring_push(struct spsc_ring *rb, const void *elem)
{
size_t head = atomic_load_explicit(&rb->head, memory_order_relaxed);
size_t tail = atomic_load_explicit(&rb->tail, memory_order_acquire);
if ((head - tail) >= rb->capacity) {
if (!rb->overwrite) {
return false; /* full and not overwriting */
}
/* Drop the oldest element: advance tail by one. */
atomic_fetch_add_explicit(&rb->tail, 1, memory_order_release);
tail++;
}
/* Copy element into slot */
size_t idx = head % rb->capacity;
void *dest = (char *)rb->storage + idx * rb->elem_size;
memcpy(dest, elem, rb->elem_size);
/* Publish the new head with release semantics */
atomic_store_explicit(&rb->head, head + 1, memory_order_release);
return true;
}
/*
* Pop one element from the ring.
* Returns true if an element was dequeued and written to out_elem.
* Returns false if buffer is empty.
*/
static inline bool
spsc_ring_pop(struct spsc_ring *rb, void *out_elem)
{
size_t tail = atomic_load_explicit(&rb->tail, memory_order_relaxed);
size_t head = atomic_load_explicit(&rb->head, memory_order_acquire);
if (tail == head) {
return false; /* empty */
}
size_t idx = tail % rb->capacity;
void *src = (char *)rb->storage + idx * rb->elem_size;
memcpy(out_elem, src, rb->elem_size);
/* Advance tail */
atomic_store_explicit(&rb->tail, tail + 1, memory_order_release);
return true;
}
/* Example usage:
#include <stdio.h>
int main(void) {
struct spsc_ring rb;
if (!spsc_ring_init(&rb, 8, sizeof(int), true)) {
return 1;
}
int val = 42;
spsc_ring_push(&rb, &val);
int out;
if (spsc_ring_pop(&rb, &out)) {
printf("Got %d\n", out);
}
spsc_ring_destroy(&rb);
return 0;
}
*/