Examining Circular Queues
I'm now zeroing in on the data logging aspect, and its implications on the circular queue design. The embedded nature of the application really influences my approach. I'm focusing on low memory footprint and speed. The goal is to balance efficiency with reliability in such a constrained environment. I'm considering potential trade-offs between different queue implementations.
Assessing Data Structure Choice
Now I'm evaluating the optimal data structure. An array-based circular queue appears suitable, given the embedded constraints. Considering indices instead of pointers for safer, more portable code. I'm leaning toward using indices to manage head and tail positions, prioritizing speed.
Evaluating Implementation Strategies
I'm now deep-diving into the actual C code structure. A critical point is the volatile keyword, which is essential. I'm focusing on atomic operations for thread-safety. Thinking now about power-of-two sizes and bitwise operations to optimize modulo calculations, and how this simplifies indexing. Considering Single-Producer-Single-Consumer (SPSC) lock-free implementations for maximal speed.
Considering Concurrency Challenges
I'm now contemplating how to synchronize access to the queue, especially concerning the ISR interaction. The SPSC model makes a lock-free design feasible. I'm focusing on guaranteeing atomic updates of the head and tail indices, ensuring data integrity during both enqueue and dequeue operations. Considering memory barriers may be needed for certain architectures and how to use volatile correctly.
Refining Implementation Choices
I'm now iterating through the C implementation, and I'm homing in on the struct definition. I'm prioritizing thread safety while keeping it fast. I'm focusing on the best way to copy the data safely. I've decided to keep the generic implementation for maximum flexibility. The struct needs to be aligned.
Reflecting on the Design
I'm now consolidating the entire process. I'm focusing on providing the user the most understandable implementation. The key aspects are the array-based structure, the indices for thread-safety, the use of volatile, and the power-of-two optimization. I'm deciding between macros versus inline functions, and which will be easiest for the user.
Here is a robust design for a Circular Queue (Ring Buffer) tailored for an embedded data logging application.
Design Principles for Embedded Efficiency
- Static Allocation: Avoid
malloc/free to prevent memory fragmentation and ensure deterministic startup.
- Single-Producer, Single-Consumer (SPSC) Safety: Designed so that the Interrupt Service Routine (Producer) and the Main Loop (Consumer) generally do not need mutex locks, provided read/write operations are atomic on the MCU architecture.
- Power-of-Two Size: Allows the use of bitwise
AND (&) instead of the modulus (%) operator. Modulo is computationally expensive (taking many CPU cycles) on many microcontrollers; bitwise AND takes one cycle.
- Volatile Qualifier: Ensures the compiler does not cache index values, forcing it to read from RAM every time (crucial for ISR interaction).
The Implementation (C Code)
This example assumes we are logging a LogEntry structure (e.g., timestamp + sensor value), not just raw bytes, which is typical for logging.
1. Header Definition (logger_queue.h)
#include <stdint.h>
#include <stdbool.h>
// CONFIGURATION
// MUST be a power of 2 (e.g., 16, 32, 64, 128, 256)
#define QUEUE_SIZE_MAX 64
// Mask is used for fast wrapping: (SIZE - 1)
#define QUEUE_MASK (QUEUE_SIZE_MAX - 1)
// The data structure to log
typedef struct {
uint32_t timestamp;
int16_t sensor_id;
float value;
} LogEntry_t;
typedef struct {
// The actual data storage
LogEntry_t buffer[QUEUE_SIZE_MAX];
// Head: Index where the next data will be written (Producer owned)
volatile uint32_t head;
// Tail: Index where the next data will be read (Consumer owned)
volatile uint32_t tail;
} LogQueue_t;
// Prototypes
void LogQueue_Init(LogQueue_t *q);
bool LogQueue_Push(LogQueue_t *q, const LogEntry_t *item);
bool LogQueue_Pop(LogQueue_t *q, LogEntry_t *item);
bool LogQueue_IsEmpty(LogQueue_t *q);
bool LogQueue_IsFull(LogQueue_t *q);
2. Source Implementation (logger_queue.c)
#include "logger_queue.h"
void LogQueue_Init(LogQueue_t *q) {
q->head = 0;
q->tail = 0;
// Note: Buffer contents generally don't need clearing if we respect head/tail
}
// PRODUCER: Typically called from ISR or High Priority Task
// Returns true if successful, false if queue is full
bool LogQueue_Push(LogQueue_t *q, const LogEntry_t *item) {
// Calculate next head position using Bitwise AND
// Equivalent to: (q->head + 1) % QUEUE_SIZE_MAX
uint32_t next_head = (q->head + 1) & QUEUE_MASK;
// Check if full
// We leave exactly one slot empty to distinguish Empty vs Full states
if (next_head == q->tail) {
return false; // Drop data or handle error
}
// Copy data to buffer
// NOTE: If LogEntry_t is huge, consider passing pointers,
// but for logging < 32 bytes, copy is fine.
q->buffer[q->head] = *item;
// Memory Barrier (Optional/Arch specific):
// Ensure data write completes before index update.
// __DMB(); // ARM Cortex-M instruction
// Atomic update of head index
q->head = next_head;
return true;
}
// CONSUMER: Typically called from Background Loop or Storage Task
// Returns true if data retrieved, false if queue is empty
bool LogQueue_Pop(LogQueue_t *q, LogEntry_t *item) {
// Check if empty
if (q->head == q->tail) {
return false;
}
// Read data
*item = q->buffer[q->tail];
// Memory Barrier (Optional):
// Ensure data read completes before index update.
// __DMB();
// update tail using Bitwise AND
q->tail = (q->tail + 1) & QUEUE_MASK;
return true;
}
bool LogQueue_IsEmpty(LogQueue_t *q) {
return (q->head == q->tail);
}
bool LogQueue_IsFull(LogQueue_t *q) {
return (((q->head + 1) & QUEUE_MASK) == q->tail);
}
Why This is Efficient
A. The "Power of 2" Math
In standard queues: head = (head + 1) % SIZE;
If SIZE is 60, the CPU has to perform integer division.
In this design: head = (head + 1) & (64 - 1);
This compiles to a single assembly instruction.
B. Lock-Free Operation
In a scenario where an ISR Pushes and the Main Loop Pops:
- The ISR only modifies
head and only reads tail.
- The Main Loop only modifies
tail and only reads head.
Because reads and writes to aligned 32-bit integers are atomic on most embedded architectures (ARM Cortex-M, AVR, PIC32), you do not need to disable interrupts (__disable_irq()) to push or pop. This reduces interrupt latency.
Note: If your architecture is 8-bit and indices are 16-bit, you do need critical sections to ensure the high/low bytes of the index aren't read while being updated.
C. The "One Slot Wasted" Strategy
You might notice we define Full as (head + 1) == tail. This effectively wastes 1 array slot.
- Benefit: We do not need a separate
count variable.
- Why: If we used a
count variable, both the Producer (increment) and Consumer (decrement) would try to write to it. This creates a Race Condition requiring heavy locking. Wasting one slot is a cheap price for lock-free speed.
Advanced Optimization: Zero-Copy (Pointer Access)
If your LogEntry is large (e.g., 512 bytes of IMU data), copying the data q->buffer[q->head] = *item is too slow for an ISR.
Instead, use a Reserve/Commit pattern:
// 1. Get pointer to writing slot (Reserve)
LogEntry_t* LogQueue_Reserve(LogQueue_t *q) {
uint32_t next_head = (q->head + 1) & QUEUE_MASK;
if (next_head == q->tail) return NULL; // Full
return &(q->buffer[q->head]);
}
// 2. ISR writes directly to memory
// my_entry->data = ...
// 3. Commit the write (updates the index)
void LogQueue_Commit(LogQueue_t *q) {
q->head = (q->head + 1) & QUEUE_MASK;
}
This eliminates the memcpy overhead entirely, allowing you to fill the buffer directly from hardware registers or via DMA.