Designing a Circular Queue
The user wants an efficient circular queue for data logging in an embedded application. Although they didn't specify the microcontroller type or language, I'm assuming C due to its common use in embedded systems. I need to provide detailed yet concise information, aiming for clarity without overwhelming the user. I can focus on key design decisions, typical ring buffer patterns, API, concurrency issues, and power-fail strategies. I’ll consider static allocation and interrupt safety as well.Structuring Circular Queue Design
I need to lay out a structure for the circular queue focused on data logging. First, I’ll consider requirements and constraints, likely using RAM for buffering before writing to flash or SD. The data structure will be a ring buffer with power-of-2 sizes and head/tail indices. I'll define a simple API for initialization, logging, reading, and checking states.
For implementation, if there's a single writer and reader, I can employ lock-free methods, but multiple producers may require mutexes. I’ll aim for efficiency by masking indices and considering record-based logging for variable-length entries, along with C implementation examples.Ensuring Data Integrity and Design
I want to focus on data integrity, ensuring that multi-byte records are logged fully and written atomically. In embedded systems, it's crucial to avoid malloc and handle memory statically, with a compile-time defined queue size, and ensure that reading and writing are safe during interrupts.
I'll propose a ring buffer design with fixed-size log records, such as a structure containing a timestamp, ID, length, and data array. I’m considering making this design more flexible by using macros for user-defined types. While I could discuss different logging strategies, I prefer focusing on the RAM buffer for efficiency, keeping persistent storage separate.Designing an SPSC Queue
I can consider using a double-pointer or count for differentiating full and empty states in the circular queue. The design will involve head and tail indices. I might keep a count variable or designate a slot as empty to indicate fullness. It’s simpler to use a count, but I need to ensure proper handling of concurrency. With a single producer and single consumer, I can avoid disabling interrupts, letting the writer (ISR) and reader (main) update their respective indices without conflict, ensuring atomic updates to prevent race conditions. Let’s design this SPSC queue!Designing an Efficient Circular Queue
For the circular queue design, I’ll propose using a buffer array of size N, where N is a power of 2. I plan to define volatile head and tail indices and implement methods to determine when the queue is full or empty without relying on modulo.
The enqueue and dequeue operations will ensure proper memory access, especially in single-producer, single-consumer contexts. I’ll elaborate on key requirements for logging, provide a concise C implementation, and discuss policies for managing overflow while keeping the design suitable for embedded applications without dynamic memory.
Let's ensure all operations are constant time, using static allocations and pointer arithmetic! Below is a practical design for an efficient circular queue (ring buffer) suitable for data logging in an embedded system, with static allocation, O(1) operations, and interrupt-safe single-producer/single-consumer behavior.
1. Design goals
For an embedded data logger, the circular queue should:
- Use fixed, statically allocated memory (no malloc).
- Have O(1) enqueue/dequeue operations.
- Be interrupt-safe with minimal or no locking.
- Avoid expensive operations (e.g., division/modulo).
- Be simple enough to verify and debug.
Typical use case:
- Producer: ISR or fast task that generates log records.
- Consumer: Background task that drains the queue to UART, flash, SD card, etc.
2. Data structure
Use a ring buffer with:
- A power-of-two size so index wrap uses a bitmask instead of modulo.
- Two indices:
head – where the next item will be written (producer only).
tail – where the next item will be read (consumer only).
- Buffer for fixed-size log records.
Queue layout
buffer[0] ... buffer[N-1]
head: index of next write
tail: index of next read
Empty: head == tail
Full: next_head == tail (i.e., one slot kept empty)
3. Overflow policy
For logging you usually choose one of:
- Drop new entries when full (loss of newest):
- Simple, you know you didn’t overwrite old data.
- Overwrite oldest entries when full (loss of oldest):
- You always keep the most recent logs (common in crash logging).
Both are easy with a ring buffer. I’ll show the “drop new on full” version, and note the change for overwrite.
4. Concurrency model (SPSC, interrupt-safe)
Assume:
- Single producer (e.g., ISR), only writes
head and buffer at head.
- Single consumer (e.g., main loop), only writes
tail and reads buffer at tail.
- Both read the other’s index but never write it.
If the index fits in a single machine word and is properly aligned, reads/writes of head and tail are atomic on typical MCUs.
Key rules:
-
Producer:
- Read
tail.
- Check for space.
- Write the log record into
buffer[head].
- Only then advance
head.
-
Consumer:
- Read
head.
- Check if queue is non-empty.
- Read the log record at
buffer[tail].
- Then advance
tail.
This avoids race conditions without disabling interrupts in most single-core MCUs.
5. Example: Fixed-size log record queue in C
Configuration
#include <stdint.h>
#include <stdbool.h>
#define LOG_QUEUE_SIZE (1u << 8) // 256 entries, must be power-of-two
#define LOG_QUEUE_MASK (LOG_QUEUE_SIZE - 1u)
// Example log record. Customize as needed.
typedef struct {
uint32_t timestamp;
uint16_t id;
uint16_t len;
uint8_t data[16]; // fixed-size payload
} log_record_t;
typedef struct {
volatile uint16_t head; // next write index
volatile uint16_t tail; // next read index
log_record_t buf[LOG_QUEUE_SIZE];
} log_queue_t;
Initialization
static log_queue_t g_logq;
void log_queue_init(log_queue_t *q)
{
q->head = 0;
q->tail = 0;
// Buffer content can be left uninitialized.
}
Call log_queue_init(&g_logq); once at startup.
Helper: capacity checks
static inline bool log_queue_is_empty(const log_queue_t *q)
{
return (q->head == q->tail);
}
// "Full" means we leave 1 slot always unused to distinguish full/empty
static inline bool log_queue_is_full(const log_queue_t *q)
{
uint16_t next_head = (q->head + 1u) & LOG_QUEUE_MASK;
return (next_head == q->tail);
}
static inline uint16_t log_queue_count(const log_queue_t *q)
{
// Works for power-of-two size
return (uint16_t)((q->head - q->tail) & LOG_QUEUE_MASK);
}
static inline uint16_t log_queue_free(const log_queue_t *q)
{
return (uint16_t)(LOG_QUEUE_SIZE - 1u - log_queue_count(q));
}
Enqueue (producer, e.g. ISR context)
Policy: drop new when full
bool log_queue_push(log_queue_t *q, const log_record_t *rec)
{
uint16_t head = q->head;
uint16_t next_head = (head + 1u) & LOG_QUEUE_MASK;
if (next_head == q->tail) {
// Queue is full: drop new record
return false;
}
q->buf[head] = *rec; // Copy record
q->head = next_head; // Publish
return true;
}
To overwrite oldest when full, change this function to:
bool log_queue_push_overwrite(log_queue_t *q, const log_record_t *rec)
{
uint16_t head = q->head;
uint16_t next_head = (head + 1u) & LOG_QUEUE_MASK;
if (next_head == q->tail) {
// Buffer full: advance tail to drop oldest
q->tail = (q->tail + 1u) & LOG_QUEUE_MASK;
}
q->buf[head] = *rec;
q->head = next_head;
return true; // never fails
}
Dequeue (consumer, e.g. main loop task)
bool log_queue_pop(log_queue_t *q, log_record_t *out)
{
uint16_t tail = q->tail;
if (tail == q->head) {
// Empty
return false;
}
*out = q->buf[tail];
q->tail = (tail + 1u) & LOG_QUEUE_MASK;
return true;
}
6. Typical usage pattern
Producer (ISR):
void ADC_IRQHandler(void)
{
log_record_t rec;
rec.timestamp = get_time_us();
rec.id = 1;
rec.len = 2;
rec.data[0] = read_adc_low();
rec.data[1] = read_adc_high();
(void)log_queue_push(&g_logq, &rec); // ignore failure or set a flag
}
Consumer (main loop):
void log_task(void)
{
log_record_t rec;
while (log_queue_pop(&g_logq, &rec)) {
// Write to UART / flash / SD
write_log_record(&rec);
}
}
Run log_task() periodically in your main loop or an RTOS task.
7. Extensions / variations
- Variable-length records:
- Store a small header (
len) and treat the ring as a byte buffer.
- Need logic to wrap records that cross the end (or always store contiguous).
- Multiple queues:
- One queue per log source or severity, drained by a single consumer.
- DMA-friendly draining:
- Add a function that returns the largest contiguous block starting at
tail for direct DMA transfer.
This design gives you an efficient, predictable circular queue with static memory, constant-time operations, and minimal synchronization overhead, well-suited for embedded data logging.