Topics / RTOS & Real-Time Systems / Q14
What is a message queue and when should you use one?
Short answer: A message queue is a thread-safe FIFO that copies fixed-size items from senders to receivers, with blocking and timeouts on both ends. Queues decouple producers and consumers, absorb bursts, and avoid shared global data and locks. In FreeRTOS, xQueueSend copies the item into the queue, so for large data send a pointer (and define who owns and frees the buffer).
typedef struct { uint8_t type; int16_t value; uint32_t timestamp; } sensor_msg_t;
QueueHandle_t q = xQueueCreate(16, sizeof(sensor_msg_t));
/* producer task */
sensor_msg_t m = { .type = 1, .value = read_temp(), .timestamp = xTaskGetTickCount() };
if (xQueueSend(q, &m, pdMS_TO_TICKS(5)) != pdTRUE) { /* queue full: count/drop/handle */ }
/* consumer task */
sensor_msg_t r;
if (xQueueReceive(q, &r, portMAX_DELAY) == pdTRUE) process(&r);
When to use a queue
- One or more producers send data/commands to a task that owns a resource (e.g. all display updates go to the display task).
- Interrupts hand data to tasks (
xQueueSendFromISR). - You want back-pressure: a full queue blocks or fails the sender instead of losing data silently.
Design points
- Sizing: depth = worst-case burst rate × worst-case consumer delay, plus margin. Monitor the high-water mark (
uxQueueMessagesWaiting). - Copy vs reference: copying small items (≤ 16–32 bytes) is simple and safe; for large buffers, send pointers from a pool and pass ownership.
- Timeouts: always choose a timeout and handle failure.
- Queue sets (FreeRTOS) or
k_poll(Zephyr) let one task wait on several queues/semaphores.
Related FreeRTOS objects
- Stream buffers: a byte stream (like a pipe) for one writer and one reader, efficient for UART data.
- Message buffers: variable-length messages built on stream buffers.
- Mailbox: a queue of length 1 that is overwritten (
xQueueOverwrite) to always hold the latest value.