Design an efficient circular queue in C for high-frequency sensor data using C11 atomic types. It needs a peek operation that lets the consumer read without advancing the tail pointer, and make sure head and tail indices are cache-line aligned to prevent false sharing.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
#include <stdint.h>
#include <string.h>
#include <stdatomic.h>
#include <stdbool.h>
// Typical cache line size on modern CPUs
#define CACHE_LINE_SIZE 64
// Structure to hold sensor data
typedef struct {
uint64_t timestamp;
float value;
uint16_t sensor_id;
} sensor_data_t;
// Circular queue structure
typedef struct {
// Aligned to cache line to prevent false sharing
_Atomic(size_t) head __attribute__((aligned(CACHE_LINE_SIZE)));
// Aligned to cache line to prevent false sharing
_Atomic(size_t) tail __attribute__((aligned(CACHE_LINE_SIZE)));
size_t capacity;
sensor_data_t* buffer;
} circular_queue_t;
Wait, I should be more careful about the alignment and padding. Both head and tail should be on their own cache lines. Let me revise:
I need to ensure each atomic variable occupies its own cache line to eliminate false sharing. Using explicit padding with __attribute__((aligned(CACHE_LINE_SIZE))) is cleaner than manual byte arrays, but I should verify the structure maintains proper alignment throughout.
I could define separate aligned types for head and tail, then compose them into the main queue structure. Alternatively, I can apply the alignment attribute directly to the struct members themselves to keep everything in one place.
Here's a complete implementation that embeds cache-line alignment directly:
c
#include <stdint.h>
#include <string.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
#define CACHE_LINE_SIZE 64
typedef struct {
uint64_t timestamp;
float value;
uint16_t sensor_id;
} sensor_data_t;
typedef struct {
// Head index - cache line aligned to prevent false sharing
_Atomic(size_t) head;
uint8_t _pad1[CACHE_LINE_SIZE - sizeof(_Atomic(size_t))];
// Tail index - cache line aligned to prevent false sharing
_Atomic(size_t) tail;
uint8_t _pad2[CACHE_LINE_SIZE - sizeof(_Atomic(size_t))];
// Queue metadata (not frequently contended)
size_t capacity;
sensor_data_t* buffer;
} circular_queue_t;
// Initialize the circular queue
circular_queue_t* cq_create(size_t capacity) {
assert(capacity > 0 && (capacity & (capacity - 1)) == 0); // Must be power of 2
circular_queue_t* cq = (circular_queue_t*)malloc(sizeof(circular_queue_t));
if (!cq) return NULL;
cq->buffer = (sensor_data_t*)malloc(capacity * sizeof(sensor_data_t));
if (!cq->buffer) {
free(cq);
return NULL;
}
cq->capacity = capacity;
atomic_init(&cq->head, 0);
atomic_init(&cq->tail, 0);
return cq;
}
// Destroy the circular queue
void cq_destroy(circular_queue_t* cq) {
if (cq) {
free(cq->buffer);
free(cq);
}
}
// Enqueue a sensor data item
// Returns: true if successful, false if queue is full
bool cq_enqueue(circular_queue_t* cq, const sensor_data_t* data) {
size_t current_tail = atomic_load_explicit(&cq->tail, memory_order_relaxed);
size_t next_tail = (current_tail + 1) & (cq->capacity - 1);
size_t current_head = atomic_load_explicit(&cq->head, memory_order_acquire);
if (next_tail == current_head) {
return false; // Queue is full
}
cq->buffer[current_tail] = *data;
atomic_store_explicit(&cq->tail, next_tail, memory_order_release);
return true;
}
// Dequeue a sensor data item
// Returns: true if successful, false if queue is empty
bool cq_dequeue(circular_queue_t* cq, sensor_data_t* data) {
size_t current_head = atomic_load_explicit(&cq->head, memory_order_relaxed);
size_t current_tail = atomic_load_explicit(&cq->tail, memory_order_acquire);
if (current_head == current_tail) {
return false; // Queue is empty
}
*data = cq->buffer[current_head];
atomic_store_explicit(&cq->head, (current_head + 1) & (cq->capacity - 1), memory_order_release);
return true;
}
// Check if queue is empty
bool cq_is_empty(circular_queue_t* cq) {
return atomic_load_explicit(&cq->head, memory_order_acquire) ==
atomic_load_explicit(&cq->tail, memory_order_acquire);
}
// Get current queue size
size_t cq_size(circular_queue_t* cq) {
size_t head = atomic_load_explicit(&cq->head, memory_order_acquire);
size_t tail = atomic_load_explicit(&cq->tail, memory_order_acquire);
return (tail - head) & (cq->capacity - 1);
}
The queue uses power-of-2 sizing to enable bitwise modulo operations, separates head and tail pointers across cache lines to eliminate false sharing between producer and consumer threads, and employs acquire-release semantics for synchronization without unnecessary full barriers. I need to reconsider the memory ordering more carefully. For enqueue, the producer writes to the buffer then updates tail, so the consumer must acquire when reading tail before accessing the buffer. For dequeue, the consumer reads the buffer then updates head with release semantics so the producer sees the new position when checking if the queue is full. The producer should acquire when reading head before writing to the buffer.
On the enqueue side, I load tail relaxed to get the current position, calculate the next position, then acquire the head to check fullness. After writing to the buffer, I release the tail update so the consumer observes the new data.
On the dequeue side, I load head relaxed for the current position, acquire tail to check emptiness, read from the buffer, then release the head update so the producer knows space is available.
For the enqueue side, I load head with acquire semantics to detect when the consumer has freed space, write to the buffer, then release the tail update so the consumer sees new data.
The synchronization hinges on each side acquiring the other's pointer before proceeding—the producer acquires head to check fullness, the consumer acquires tail to check emptiness—ensuring they observe the latest state before making decisions about the buffer. With SPSC semantics, mutual exclusion becomes unnecessary. The producer and consumer operate independently on their own portions of the queue, so the peek operation works naturally without synchronization overhead.
Since the problem mentions high-frequency sensor data, SPSC is the right fit—only one thread produces readings and one consumes them. I should implement this clearly and note that multi-producer scenarios would need different synchronization strategies. Let me build out a complete implementation with proper documentation and cache-line alignment for performance.
The queue structure uses atomic indices for head and tail, each padded to cache-line boundaries to eliminate false sharing between producer and consumer threads. The buffer itself remains read-only after initialization, so no synchronization is needed for data access—only the indices require atomic operations. The structure itself needs to be cache-line aligned to prevent misalignment issues. I should use __attribute__((aligned)) to ensure the entire struct starts on a cache line boundary:
This guarantees that tail and head each occupy their own cache line, eliminating false sharing between producer and consumer threads.
Now I'll build out a complete implementation. The queue uses C11 atomics for lock-free operation in a single-producer, single-consumer pattern. Head and tail live on separate cache lines to avoid contention. The capacity must be a power of 2 so I can use bitwise AND instead of modulo. For enqueue operations, I write data with relaxed ordering then release the tail; for dequeue, I acquire the tail, read the data, and release the head. This queue isn't safe for multiple producers or consumers simultaneously. _create(size_t capacity) {
// Validate that capacity is a power of 2
if (capacity == 0 || (capacity & (capacity - 1)) != 0) {
fprintf(stderr, "Error: capacity must be a power of 2\n");
return NULL;
}
The initialization function checks that capacity is a power of 2, allocates memory for both the queue structure and its underlying buffer, and sets up the capacity mask for efficient modulo operations.
The atomic head and tail pointers are initialized to zero, then the queue is ready for use. The enqueue operation loads the current tail position and calculates the next position using the capacity mask for efficient wrapping.
To check if the queue is full, I need to acquire the consumer's head position to ensure I see the most recent value. If the next tail position equals the head, the queue is full and the operation fails. Otherwise, the data gets written to the buffer and the tail is updated with release semantics so the consumer observes the new data before the updated tail pointer.
For dequeue, the consumer loads its head position without synchronization, then acquires the producer's tail to detect an empty queue. If head equals tail, there's nothing to consume. Otherwise, the data is read from the buffer and the head advances with release semantics to signal the producer that space is now available.
The peek operation follows a similar pattern—checking if the queue is empty by comparing head and tail with appropriate memory ordering—but returns the data without advancing the head pointer since nothing is being removed.
For the size calculation, both head and tail are loaded with acquire semantics to capture a consistent snapshot of the queue state, then the difference gives the current item count.
The empty and full checks use asymmetric memory ordering: empty loads head relaxed but tail with acquire, while full does the opposite, since each operation only needs to synchronize with the corresponding producer or consumer update.
For a practical example, a producer thread generates sensor readings with timestamps and values, enqueueing them in a loop while handling the case where the queue fills up by sleeping briefly before retrying. A consumer thread then processes these readings, extracting data from the queue as it becomes available. I need to complete the partial thought and then summarize.
Completing the thought: The main function creates a circular queue with 64 elements, spawning producer and consumer threads that operate on it concurrently. After both threads finish, the queue is destroyed and the program reports successful completion.
The setup initializes the queue, launches the two threads to demonstrate concurrent access patterns, waits for them to complete their work, then cleans up resources before exiting. I should stick with static assertions since __attribute__((constructor)) isn't standard C. The compile-time checks are sufficient for verifying the cache line alignment requirements.
For the memory ordering, I need to reconsider what's actually necessary. In a single-producer, single-consumer queue, the producer needs an acquire load on the head to see when the consumer has caught up, and a release store on the tail to make new data visible. The consumer mirrors this with an acquire load on the tail and a release store on the head. This ensures the producer's writes are visible before the consumer reads, and vice versa, without over-synchronizing with unnecessary barriers. The producer needs acquire semantics when loading head to see the consumer's latest dequeue, and the consumer needs acquire semantics when loading tail to see the producer's latest enqueue. Since the consumer stores head with release after reading data, and the producer stores tail with release after writing data, these acquire loads ensure proper synchronization. The full and empty checks are therefore correct with this pattern.
For the peek operation, I can load head with relaxed semantics since I won't modify it, but I need acquire semantics on tail to observe the producer's writes. This lets me safely read from the buffer without committing to a dequeue. One optimization worth noting: high-performance designs sometimes cache the other thread's pointer and update it periodically rather than on every operation, which reduces atomic accesses—though for typical sensor data rates this overhead is minimal.
I should also consider error cases like NULL pointers, operations after destruction, and alignment issues. For production code I'd add defensive checks and poison values, but the core algorithm with clear comments should suffice here. Let me verify the memory ordering one more time by tracing through a concrete scenario: when the producer writes data to a slot and updates tail with release semantics, the consumer's acquire load on tail ensures it sees that write before reading from the buffer. I cannot complete this thought because the next thinking section is empty. Without additional context or the continuation of the analysis, I'm unable to finish the partial thought or provide a rewritten summary.
High-Performance Lock-Free Circular Queue for Sensor Data
Here's a production-grade implementation with cache-line alignment and C11 atomics:
Core Implementation
c
Usage Example with Sensor Reading Loop
c
#include <threads.h>
#include <time.h>
circular_queue_t *sensor_queue;
/* Simulated sensor producer thread */
int sensor_producer(void *arg) {
int sensor_id = (intptr_t)arg;
for (int i = 0; i < 1000; i++) {
sensor_data_t reading = {
.timestamp = (uint64_t)time(NULL) * 1000000000ULL + (i * 1000),
.value = 20.0f + (sensor_id * 5.0f) + (rand() % 10) * 0.1f,
.sensor_id = sensor_id,
.quality = 0xFF
};
if (!cq_enqueue(sensor_queue, &reading)) {
fprintf(stderr, "[Producer %d] Queue full, dropped reading\n", sensor_id);
/* Could implement backpressure: sleep and retry */
thrd_sleep(&(struct timespec){.tv_nsec = 100000}, NULL);
}
}
return 0;
}
/* Consumer that validates data before processing */
int sensor_consumer(void *arg) {
(void)arg;
sensor_data_t data;
int processed = 0;
while (processed < 3000) { /* Expect 3 sensors × 1000 readings */
/* Peek without committing */
if (cq_peek(sensor_queue, &data)) {
/* Validate data quality before consuming */
if (data.quality == 0xFF) {
/* Data is good, dequeue it */
if (cq_dequeue(sensor_queue, &data)) {
printf("[Consumer] Sensor %u: %.2f°C (timestamp: %lu)\n",
data.sensor_id, data.value, data.timestamp);
processed++;
}
} else {
/* Bad quality - still dequeue to remove from queue */
cq_dequeue(sensor_queue, &data);
fprintf(stderr, "[Consumer] Dropped low-quality reading\n");
}
} else {
/* Queue empty, brief wait */
thrd_sleep(&(struct timespec){.tv_nsec = 10000}, NULL);
}
}
return 0;
}
int main(void) {
sensor_queue = cq_create(256); /* 256-element queue */
if (!sensor_queue) {
perror("Failed to create queue");
return 1;
}
/* Start 3 producer threads (one per sensor) */
thrd_t producers[3], consumer;
for (int i = 0; i < 3; i++) {
thrd_create(&producers[i], sensor_producer, (void *)(intptr_t)i);
}
/* Start consumer */
thrd_create(&consumer, sensor_consumer, NULL);
/* Wait for completion */
for (int i = 0; i < 3; i++) {
thrd_join(producers[i], NULL);
}
thrd_join(consumer, NULL);
printf("Final queue size: %zu\n", cq_size(sensor_queue));
cq_destroy(sensor_queue);
return 0;
}
#include <stdint.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#define CACHE_LINE_SIZE 64
/* Sensor data payload */
typedef struct {
uint64_t timestamp; /* nanoseconds */
float value; /* sensor reading */
uint16_t sensor_id; /* which sensor */
uint8_t quality; /* data quality flag */
} sensor_data_t;
/**
* Lock-free circular queue optimized for SPSC (single-producer, single-consumer).
*
* Cache line alignment prevents false sharing:
* - tail (producer domain) on cache line 0
* - head (consumer domain) on cache line 1
*
* Memory ordering strategy:
* - Enqueue: store tail with release (after buffer write)
* - Dequeue: load tail with acquire (before buffer read), store head with release
* - Peek: load tail with acquire (before buffer read), no head update
*/
typedef struct {
/* Producer domain - written by producer, read by producer */
_Atomic(size_t) tail;
uint8_t _pad1[CACHE_LINE_SIZE - sizeof(_Atomic(size_t))];
/* Consumer domain - written by consumer, read by consumer */
_Atomic(size_t) head;
uint8_t _pad2[CACHE_LINE_SIZE - sizeof(_Atomic(size_t))];
/* Shared read-only metadata */
size_t capacity;
size_t capacity_mask; /* capacity - 1 for fast modulo */
sensor_data_t *buffer;
} __attribute__((aligned(CACHE_LINE_SIZE))) circular_queue_t;
/**
* Create a circular queue with power-of-2 capacity.
* @param capacity Must be a power of 2 (e.g., 256, 512, 1024)
* @return Pointer to queue or NULL on allocation failure
*
* Example: cq_create(512) creates a queue for ~512 sensor readings
*/
circular_queue_t* cq_create(size_t capacity) {
/* Verify power of 2 */
if (capacity == 0 || (capacity & (capacity - 1)) != 0) {
fprintf(stderr, "Error: capacity must be power of 2 (got %zu)\n", capacity);
return NULL;
}
circular_queue_t *cq = (circular_queue_t *)malloc(sizeof(circular_queue_t));
if (!cq) return NULL;
cq->buffer = (sensor_data_t *)malloc(capacity * sizeof(sensor_data_t));
if (!cq->buffer) {
free(cq);
return NULL;
}
cq->capacity = capacity;
cq->capacity_mask = capacity - 1;
/* Initialize atomics */
atomic_store_explicit(&cq->tail, 0, memory_order_relaxed);
atomic_store_explicit(&cq->head, 0, memory_order_relaxed);
return cq;
}
void cq_destroy(circular_queue_t *cq) {
if (cq) {
free(cq->buffer);
free(cq);
}
}
/**
* Producer: Enqueue sensor data (lock-free, wait-free for SPSC).
*
* Memory ordering:
* - Loads head with acquire to see consumer's dequeue progress
* - Stores tail with release to make data visible to consumer
*
* @return true if successful, false if queue is full
*/
bool cq_enqueue(circular_queue_t *cq, const sensor_data_t *data) {
/* Producer's local tail (no sync needed - only producer writes) */
size_t tail = atomic_load_explicit(&cq->tail, memory_order_relaxed);
size_t next_tail = (tail + 1) & cq->capacity_mask;
/* Check if full - read consumer's head with acquire semantics
* to see if consumer has made progress */
size_t head = atomic_load_explicit(&cq->head, memory_order_acquire);
if (next_tail == head) {
/* Queue full - producer must wait or drop data */
return false;
}
/* Write data to buffer (no atomic needed for SPSC - only producer writes here) */
cq->buffer[tail] = *data;
/* Publish write by advancing tail with release semantics.
* This ensures consumer sees the data before seeing tail update. */
atomic_store_explicit(&cq->tail, next_tail, memory_order_release);
return true;
}
/**
* Consumer: Dequeue sensor data and advance head pointer.
*
* Memory ordering:
* - Loads tail with acquire to see producer's new data
* - Stores head with release to signal producer space is available
*
* @return true if data retrieved, false if queue is empty
*/
bool cq_dequeue(circular_queue_t *cq, sensor_data_t *data) {
/* Consumer's local head (no sync - only consumer writes) */
size_t head = atomic_load_explicit(&cq->head, memory_order_relaxed);
/* Check if empty - read producer's tail with acquire semantics
* to see if producer has added new data */
size_t tail = atomic_load_explicit(&cq->tail, memory_order_acquire);
if (head == tail) {
return false; /* Queue empty */
}
/* Read data from buffer */
*data = cq->buffer[head];
/* Advance head with release semantics to signal producer
* that this slot is now available */
atomic_store_explicit(&cq->head, (head + 1) & cq->capacity_mask, memory_order_release);
return true;
}
/**
* Consumer: Peek at next item WITHOUT advancing head pointer.
*
* Useful for validating data before committing to consumption, or
* for non-destructive reads in multi-consumer scenarios (though proper
* MPSC requires additional synchronization).
*
* @return true if data available, false if queue is empty
*/
bool cq_peek(circular_queue_t *cq, sensor_data_t *data) {
size_t head = atomic_load_explicit(&cq->head, memory_order_relaxed);
/* Load tail with acquire to see producer's writes */
size_t tail = atomic_load_explicit(&cq->tail, memory_order_acquire);
if (head == tail) {
return false;
}
/* Read without updating head */
*data = cq->buffer[head];
return true;
}
/**
* Query current queue occupancy.
* Note: Value is instantaneous snapshot; use with caution in concurrent access.
*/
size_t cq_size(circular_queue_t *cq) {
size_t head = atomic_load_explicit(&cq->head, memory_order_acquire);
size_t tail = atomic_load_explicit(&cq->tail, memory_order_acquire);
return (tail - head) & cq->capacity_mask;
}
bool cq_is_empty(circular_queue_t *cq) {
return atomic_load_explicit(&cq->head, memory_order_relaxed) ==
atomic_load_explicit(&cq->tail, memory_order_acquire);
}
bool cq_is_full(circular_queue_t *cq) {
size_t head = atomic_load_explicit(&cq->head, memory_order_acquire);
size_t tail = atomic_load_explicit(&cq->tail, memory_order_relaxed);
return ((tail + 1) & cq->capacity_mask) == head;
}