The Complete Guide to FreeRTOS Queues, Stream Buffers and Message Buffers
Learn FreeRTOS queues, stream buffers and message buffers: when to use each, ISR sends, sizing, pointer ownership, patterns and the failures that lose data.

Tasks that never exchange data are rare, and the way they exchange it decides whether a firmware is easy to reason about or full of races. FreeRTOS gives you three kernel objects for moving data: the queue, which carries fixed-size items; the stream buffer, which carries a flow of bytes; and the message buffer, which carries variable-length messages. A fourth tool, the task notification, wakes a task cheaply, and it comes up here because it competes with all three. This guide covers each object in FreeRTOS Kernel V11.3.3 on a Cortex-M4F, with complete code: creating and sizing, sending and receiving, blocking and timeouts, using them from interrupts, passing large buffers safely, the common patterns and the failures that lose data without a trace. It is the hub for the queue posts in this series, and each section points to the deeper post.
The answer in brief
Use a queue for items of one size, especially with several senders or receivers, and for anything you may want to peek at. Use a stream buffer for a byte flow with exactly one writer and one reader, such as a UART. Use a message buffer for variable-length framed messages with exactly one writer and one reader. Use a task notification to wake one task with a signal or a number. All of them copy data, all of them have FromISR variants and all of them need a decision about what happens when they are full.
Choosing the right object
| Property | Queue | Stream buffer | Message buffer | Task notification |
|---|---|---|---|---|
| Unit | Fixed-size item | Byte | Variable-size message | 32-bit value or event |
| Senders | Many | One | One | Any |
| Receivers | Many | One | One | The target task only |
| Boundaries kept | Yes | No | Yes | Not applicable |
| Memory | Storage plus control block | Buffer plus control block | Buffer plus control block | None |
| Peek | Yes | No | No | No |
| Wakes the reader | On each item | At the trigger level | On each message | On each notification |
Two rows settle most decisions. If more than one task sends or receives, only a queue qualifies, because the buffers assume a single writer and a single reader. If the data is a continuous byte flow or messages of mixed sizes, a buffer is cheaper than a queue padded to its largest item. The comparison post puts the same job through all four with code, and the primitives cheat sheet adds semaphores, mutexes and event groups to the picture.
Queues
What a queue is
A queue is a first-in, first-out buffer with a fixed capacity and item size chosen at creation. Sending copies an item in at the back. Receiving copies the oldest item out and removes it. A task that receives from an empty queue can wait, Blocked and using no CPU, until an item arrives. A task that sends to a full queue can wait until there is room.
#include "FreeRTOS.h"
#include "queue.h"
typedef struct {
uint8_t channel;
uint16_t value;
} adc_sample_t;
static QueueHandle_t xSampleQueue;
void queue_init(void)
{
xSampleQueue = xQueueCreate(8, sizeof(adc_sample_t));
configASSERT(xSampleQueue != NULL);
}xQueueCreate takes the length and the item size in bytes, allocates length x size bytes plus a control structure from the heap and returns a handle, or NULL on failure. Always use sizeof on the type you send: creating a queue of uint8_t and sending a uint32_t copies only one byte, with no warning.
Sending and receiving
BaseType_t xQueueSend ( QueueHandle_t q, const void *item, TickType_t ticksToWait );
BaseType_t xQueueReceive( QueueHandle_t q, void *buffer, TickType_t ticksToWait );xQueueSend is a macro for xQueueSendToBack, and xQueueSendToFront puts an urgent item at the head. Both return pdPASS on success and errQUEUE_FULL if the queue stayed full for the whole wait. xQueueReceive returns pdPASS if an item arrived and errQUEUE_EMPTY if the wait expired. The wait is in ticks: 0 returns at once, a finite value waits up to that long and portMAX_DELAY waits forever, which needs INCLUDE_vTaskSuspend set to 1.
A complete producer and consumer:
static void vProducer(void *p)
{
uint16_t counter = 0;
(void) p;
for (;;)
{
adc_sample_t s = { .channel = 1, .value = counter++ };
if (xQueueSend(xSampleQueue, &s, pdMS_TO_TICKS(10)) != pdPASS)
{
printf("producer: queue full, sample %u dropped\n", s.value);
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
static void vConsumer(void *p)
{
adc_sample_t s;
(void) p;
for (;;)
{
if (xQueueReceive(xSampleQueue, &s, portMAX_DELAY) == pdPASS)
{
printf("consumer: channel %u value %u\n", s.channel, s.value);
}
}
}consumer: channel 1 value 0
consumer: channel 1 value 1
consumer: channel 1 value 2One line appears every 100 ms, and the consumer uses no CPU between lines. When several tasks wait to receive from the same queue, the highest-priority waiter gets the next item, and among equals the one that has waited longest. The first post on xQueueSend and xQueueReceive covers the basics line by line, including the wait-time policy for each call.
Why a queue copies
A queue copies uxItemSize bytes in and out. That sounds wasteful, and it solves three problems that pointers create in a multitasking system. A pointer to a stack variable dangles as soon as the function returns, so the receiver reads garbage. A pointer to a shared buffer lets the sender rewrite it while the receiver reads, so reads tear. And a pointer raises the question of who frees the buffer. Copying lets the sender reuse its variable the moment the call returns, and makes the transfer a unit.
The price is time and RAM proportional to the item size. A queue of 16 items of 1,024 bytes holds 16 KB whether or not it is ever full, and the copy runs partly inside a critical section, which lengthens latency for others. Keep items small: commands, events, readings, small structs. The post on why queues copy data covers the reasoning and a table of the trade-offs.
Peeking and the mailbox pattern
xQueuePeek has the shape of receive and leaves the item in place, so any number of tasks can read the same item. Combined with xQueueOverwrite, which writes to a queue of length one whether or not it is full, it gives a latest-value mailbox with no mutex:
typedef struct { int16_t temperature_c10; uint32_t tick; } reading_t;
static QueueHandle_t xLatest;
void mailbox_init(void)
{
xLatest = xQueueCreate(1, sizeof(reading_t));
configASSERT(xLatest != NULL);
}
static void vSensorTask(void *p)
{
int16_t t = 200;
(void) p;
for (;;)
{
reading_t r = { .temperature_c10 = t++, .tick = xTaskGetTickCount() };
xQueueOverwrite(xLatest, &r);
vTaskDelay(pdMS_TO_TICKS(500));
}
}
static void vDisplayTask(void *p)
{
reading_t r;
(void) p;
for (;;)
{
if (xQueuePeek(xLatest, &r, pdMS_TO_TICKS(1000)) == pdPASS)
{
printf("display: %d.%d C\n", r.temperature_c10 / 10, r.temperature_c10 % 10);
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}The writer never waits, and every reader gets a consistent snapshot, because the kernel copies the whole struct inside its critical section. A shared global with a plain assignment risks a torn read, where a reader sees the new temperature and the old timestamp. Add a timestamp to the item and check its age, since a peek always returns the last value, even if the writer has died. Peek-then-receive is safe only with a single consumer: another task can take the item between your two calls. The peek post has a monotonic-value test you can drop in.
Inspecting and clearing
UBaseType_t waiting = uxQueueMessagesWaiting(xSampleQueue);
UBaseType_t spaces = uxQueueSpacesAvailable(xSampleQueue);
xQueueReset(xSampleQueue);Use the counts for diagnostics and high-water logging. Do not base logic on them: the value can change the instant after you read it. vQueueAddToRegistry with a name, when configQUEUE_REGISTRY_SIZE is set, lets a kernel-aware debugger list queues by name.
Static queues
xQueueCreateStatic takes a storage array and a StaticQueue_t you declare, so creation cannot fail for lack of heap and the memory map shows the cost:
#define QUEUE_LEN 8
static uint8_t ucStorage[QUEUE_LEN * sizeof(adc_sample_t)];
static StaticQueue_t xControl;
QueueHandle_t xQ = xQueueCreateStatic(QUEUE_LEN, sizeof(adc_sample_t), ucStorage, &xControl);
configASSERT(xQ != NULL);Using queues from interrupts
An interrupt cannot block, so it uses the FromISR functions. They take an extra argument, a pointer to a flag the kernel sets to pdTRUE if the call made a higher-priority task ready, and the handler finishes by passing the flag to portYIELD_FROM_ISR.
void USART2_IRQHandler(void)
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if (USART2->SR & USART_SR_RXNE)
{
uint8_t byte = (uint8_t) USART2->DR;
if (xQueueSendFromISR(xRxQueue, &byte, &xHigherPriorityTaskWoken) != pdTRUE)
{
rx_overflow_count++;
}
}
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}Three rules cover almost every bug here. Initialize the flag to pdFALSE; an uninitialized flag decides the yield from stack junk. Use one flag for all the FromISR calls in a handler and yield once at the end. And set the interrupt's priority explicitly, at or below configMAX_SYSCALL_INTERRUPT_PRIORITY: every FromISR function asserts it, and an interrupt left at the reset default of 0 trips the assertion in vPortValidateInterruptPriority the first time it runs. Without the final yield the data still arrives, and a higher-priority consumer waits for the next tick.
Decide what a full queue means, since the handler cannot wait. Drop the new item and count it, which favors old data; overwrite with a length-one queue and xQueueOverwriteFromISR, which keeps the newest; or defer by sending a small descriptor and letting a task do the heavy part. The ISR post covers each policy, and the post on the priority assertion lists six causes of a failure.
Passing large buffers
Copying a 1,500-byte frame twice per hop is wasteful at high rates. The standard answer is to queue a pointer, and the standard failure is a pointer to memory that is reused, freed twice or modified while someone reads it. The safe version has three parts: a fixed pool of equal buffers, a small descriptor that travels through the queue and one rule that never bends, that exactly one party owns a buffer at any moment.
The pool is itself a queue of free buffer pointers, so it gets blocking and ISR safety from the kernel:
#define POOL_COUNT 8
#define POOL_BUF_LEN 1536
static uint8_t s_storage[POOL_COUNT][POOL_BUF_LEN] __attribute__((aligned(4)));
static QueueHandle_t xFreeQueue;
void pool_init(void)
{
xFreeQueue = xQueueCreate(POOL_COUNT, sizeof(uint8_t *));
configASSERT(xFreeQueue != NULL);
for (int i = 0; i < POOL_COUNT; i++)
{
uint8_t *p = s_storage[i];
xQueueSend(xFreeQueue, &p, 0);
}
}
uint8_t *pool_alloc(TickType_t xWait)
{
uint8_t *p = NULL;
(void) xQueueReceive(xFreeQueue, &p, xWait);
return p;
}
void pool_free(uint8_t *p)
{
configASSERT(p >= &s_storage[0][0] && p < &s_storage[POOL_COUNT][0]);
configASSERT(((p - &s_storage[0][0]) % POOL_BUF_LEN) == 0);
if (xQueueSend(xFreeQueue, &p, 0) != pdPASS)
{
configASSERT(0); /* free queue full: a double free */
}
}The two assertions in pool_free turn the classic bugs into a stop at the offending line: a pointer from outside the pool, and a double free, which can only happen if the free queue is already full. The producer takes a buffer, fills it and sends a descriptor, and on a failed send it still owns the buffer and must return it. The consumer receives the descriptor, processes the data and always frees:
typedef struct { uint8_t *data; uint16_t length; uint8_t source; } frame_t;
/* producer */
uint8_t *buf = pool_alloc(pdMS_TO_TICKS(50));
if (buf != NULL)
{
frame_t f = { .data = buf, .length = radio_receive(buf, POOL_BUF_LEN), .source = 1 };
if (xQueueSend(xFrameQueue, &f, pdMS_TO_TICKS(10)) != pdPASS)
{
pool_free(buf); /* send failed: still ours */
}
}
/* consumer */
frame_t f;
if (xQueueReceive(xFrameQueue, &f, portMAX_DELAY) == pdPASS)
{
handle_frame(f.data, f.length);
pool_free(f.data);
}After a successful send, even reading buf[0] is a bug. Null your own pointer right away so a stray use crashes immediately. A pointer queue needs one more care on a part with data caches, where a DMA-filled buffer must sit in non-cacheable memory or be cleaned and invalidated. The post on queues of pointers builds this out with a pool-health counter.
Sizing a queue
A queue exists to absorb the difference between the producer's timing and the consumer's, so its length follows from three numbers: R, the producer's peak rate in items per second; L, the consumer's worst-case latency in seconds, including the time it spends processing an item; and B, the largest burst. The minimum length is:
length >= ceil(R x L) + B + 1For a sensor posting 500 items per second to a consumer that can be away for 38 ms, R x L is 19, a burst of 0 adds nothing and the extra slot gives 20, or 30 with a 50 percent margin. For a command port that delivers 8 commands in under a millisecond and then stays quiet for 200 ms, the burst term dominates and a length of 11 is enough.
Check the long-run rates first: if the consumer processes 200 items per second and the producer sends 250, no length helps, and a longer queue only delays the overflow. Then decide the full-queue policy in advance (block, drop, overwrite or assert) and keep a high-water mark and a drop counter in the shipping build:
sensor queue: length 30, high water 17, dropped 0That is an example of a healthy report: the margin held. A high-water mark that reaches the length means the queue is at its limit even if nothing dropped yet. The sizing post works both examples with the constants documented in a header.
Stream buffers
What they are for
A UART delivers a continuous stream of bytes, and a queue of single bytes pays the full item overhead and a wake-up for each. A stream buffer is a byte FIFO built for this. You create it with a capacity in bytes and a trigger level, the number of bytes that must be present before a task blocked on an empty buffer is woken:
StreamBufferHandle_t xRxStream = xStreamBufferCreate(256, 1);The functions mirror the queue ones with byte counts: xStreamBufferSend, xStreamBufferSendFromISR, xStreamBufferReceive, xStreamBufferReceiveFromISR, xStreamBufferBytesAvailable, xStreamBufferSpacesAvailable, xStreamBufferSetTriggerLevel and xStreamBufferReset.
The one-writer, one-reader rule
A stream buffer is lock-free and safe only with exactly one writer and one reader. Two writers can interleave bytes and corrupt the internal indices. If you need several writers, serialize them with a mutex, or give each its own buffer and merge in the reader. The UART's receive interrupt is one writer and a task is one reader, which fits.
A UART receive path
void USART2_IRQHandler(void)
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if (USART2->SR & USART_SR_RXNE)
{
uint8_t byte = (uint8_t) USART2->DR;
size_t sent = xStreamBufferSendFromISR(xRxStream, &byte, 1, &xHigherPriorityTaskWoken);
if (sent != 1)
{
rx_dropped++;
}
}
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
static void vLineTask(void *p)
{
char line[80];
size_t used = 0;
uint8_t chunk[32];
(void) p;
for (;;)
{
size_t n = xStreamBufferReceive(xRxStream, chunk, sizeof chunk, portMAX_DELAY);
for (size_t i = 0; i < n; i++)
{
char c = (char) chunk[i];
if (c == '\n')
{
line[used] = '\0';
printf("line: %s\n", line);
used = 0;
}
else if (c != '\r' && used < sizeof line - 1)
{
line[used++] = c;
}
}
}
}xStreamBufferSendFromISR returns the bytes actually written, so a short count means the buffer was full and the shortfall is lost. A stream has no message boundaries: hello\n may arrive as hel then lo\n, and the parser must collect bytes until a delimiter. Typing hello then ok into a terminal prints:
line: hello
line: okTrigger level and timeout
A trigger of 1 wakes the reader for every byte, which at 115,200 baud means up to about 11,500 wake-ups a second. Raise the trigger to batch, and read with a finite timeout so the task also wakes after a quiet period with whatever arrived:
size_t n = xStreamBufferReceive(xRxStream, chunk, sizeof chunk, pdMS_TO_TICKS(20));That gives batching during bursts and bounded latency at the end of one. Size the buffer for rate times worst-case task latency: at 11,520 bytes per second and a 20 ms worst case, you need at least 231 bytes, so 256 leaves a small margin. At high baud rates, use the UART's DMA in circular mode and send blocks from the idle-line interrupt, which changes nothing on the reader side.
V11.1.0 added a stream batching buffer, created with xStreamBatchingBufferCreate, which differs when a task reads from a non-empty buffer: a plain stream buffer returns immediately with what is there, while a batching buffer blocks until the data exceeds the trigger level or the timeout expires. It suits readers that want whole batches, such as a block-oriented codec. V11.1.0 also added reset functions callable from an interrupt, and V11.3.0 added an assertion for overflow in xStreamBufferSendFromISR. The UART post has the full wiring.
Message buffers
Variable-length messages, delivered whole
A message buffer is a stream buffer that stores each message with a length prefix, so a receive returns exactly one whole message or nothing, and order is preserved. It keeps the one-writer, one-reader rule. You create one with a size in bytes and no trigger level, since the unit is the message:
static MessageBufferHandle_t xCmdBuffer;
void commands_init(void)
{
xCmdBuffer = xMessageBufferCreate(512);
configASSERT(xCmdBuffer != NULL);
}The cost of a message
Each message carries a length field of type configMESSAGE_BUFFER_LENGTH_TYPE, which defaults to size_t: 4 bytes on a 32-bit core. A 10-byte message occupies 14 bytes of the buffer, so five messages of up to 40 bytes need at least 5 x (40 + 4) = 220 bytes. The creation function asserts that the buffer is larger than the length field alone.
Sending and receiving
typedef struct { uint8_t type; uint8_t len; uint8_t payload[38]; } packet_t;
static void send_packet(uint8_t type, const uint8_t *data, uint8_t len)
{
packet_t p = { .type = type, .len = len };
size_t total = 2u + len;
memcpy(p.payload, data, len);
if (xMessageBufferSend(xCmdBuffer, &p, total, pdMS_TO_TICKS(10)) != total)
{
packets_dropped++;
}
}
static void vCommandTask(void *p)
{
packet_t pkt;
(void) p;
for (;;)
{
size_t n = xMessageBufferReceive(xCmdBuffer, &pkt, sizeof pkt, portMAX_DELAY);
if (n >= 2u)
{
printf("packet type=%u len=%u (stored bytes=%u)\n", pkt.type, pkt.len, (unsigned) n);
}
}
}packet type=7 len=3 (stored bytes=5)
packet type=9 len=12 (stored bytes=14)The send is all or nothing: it returns the message length on success and 0 if the message did not fit within the wait. Sending only the used bytes, as above, is the benefit over a fixed-item queue. The receive returns the message length, or 0 if nothing arrived, and it also returns 0 if the next message is larger than the buffer you passed. The message then stays queued, and a loop that treats 0 as "nothing yet" spins forever. Size the receive buffer for the largest allowed message, or call xMessageBufferNextLengthBytes first, from the single reader, to check. Avoid zero-length messages, which confuse the 0-means-empty convention. The message buffer post covers sizing, the interrupt variant and the pitfalls.
Task notifications as the fourth option
A notification lives inside the task control block, so it needs no object and no allocation:
/* interrupt */
vTaskNotifyGiveFromISR(xWorker, &xWoken);
portYIELD_FROM_ISR(xWoken);
/* worker */
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);It targets exactly one task, carries one 32-bit value (or counts, when used like a counting semaphore), cannot buffer separate values and cannot make a sender wait for the receiver. It is the cheapest wake-up there is, and the right choice for a one-to-one signal. For a payload, or for several senders or receivers, use a queue. A common arrangement mixes them: an interrupt places bytes in a stream buffer, a parser turns them into messages and posts them to a queue several workers read, and notifications carry completion events back.
Patterns worth knowing
The gatekeeper
When several tasks need a resource that is not thread safe, such as a UART transmitter or a display, give it one owner task and let the others send requests through a queue. No lock is needed, because only the owner touches the hardware, and a slow resource slows only its own task.
typedef struct { char text[64]; } print_req_t;
static QueueHandle_t xPrintQueue;
void print_line(const char *s)
{
print_req_t r;
strncpy(r.text, s, sizeof r.text - 1);
r.text[sizeof r.text - 1] = '\0';
xQueueSend(xPrintQueue, &r, pdMS_TO_TICKS(20));
}
static void vPrintGatekeeper(void *p)
{
print_req_t r;
(void) p;
for (;;)
{
if (xQueueReceive(xPrintQueue, &r, portMAX_DELAY) == pdPASS)
{
uart_write_blocking(r.text);
}
}
}Request and reply
When a requester needs an answer, put a reply queue handle in the request. The server sends the answer to that queue, so replies never mix between requesters:
typedef struct {
uint8_t op;
int32_t arg;
QueueHandle_t xReply;
} request_t;
int32_t call_server(uint8_t op, int32_t arg)
{
QueueHandle_t xMine = xQueueCreate(1, sizeof(int32_t));
request_t req = { .op = op, .arg = arg, .xReply = xMine };
int32_t answer = -1;
if (xQueueSend(xServerQueue, &req, pdMS_TO_TICKS(10)) == pdPASS)
{
(void) xQueueReceive(xMine, &answer, pdMS_TO_TICKS(100));
}
vQueueDelete(xMine);
return answer;
}Creating a queue per call is expensive, so a long-lived requester creates its reply queue once. The timeout on the receive turns a dead server into an error value instead of a hang.
Fan-out with a dispatcher
One producer feeding several consumers needs either one queue per consumer, fed by a dispatcher task, or a queue of tagged items that each consumer filters. Do not point several tasks at one stream buffer, which has a single reader.
Blocking behavior in detail
Every blocking call follows the same rules, and knowing them removes a class of surprises.
Who wakes first. When several tasks wait to receive from one queue, the kernel keeps them on an event list ordered by priority. An arriving item wakes the highest-priority waiter, and among equals the one that has waited longest. The woken task becomes Ready, and whether it runs immediately depends on its priority against the running task. If the sender is a lower-priority task and the receiver outranks it, the receiver preempts the sender inside the xQueueSend call, and the sender continues only after the receiver blocks again. This explains outputs that appear "out of order" in a demo: the consumer printed before the producer's next line, because it ran as soon as the item arrived.
Timeouts are minimums of patience, not guarantees of timing. A receive with a 100 ms timeout returns errQUEUE_EMPTY after about 100 ms of waiting, quantized to ticks, and the task then has to win the CPU back before it runs again. A task blocked behind a long higher-priority burst notices its timeout late.
Deadlock through queues. Two tasks that each wait for a message from the other, with infinite timeouts, wait forever. The classic shape: task A sends a request to B and waits for the reply, while B is blocked sending a status message into A's full queue. Finite timeouts turn the hang into a logged error. A design rule helps: a task that serves a queue should never block indefinitely on a queue that the requester drains.
Blocking while holding a lock. Waiting on a queue with a mutex held is the other way queues join a deadlock. If task A holds a mutex and waits for an item, and the only task that can send that item needs the mutex, nothing moves. Release locks before blocking.
/* avoid: holds the bus lock while waiting for data */
xSemaphoreTake(xBus, portMAX_DELAY);
xQueueReceive(xQ, &item, portMAX_DELAY); /* the sender may need xBus */
xSemaphoreGive(xBus);
/* prefer: wait first, lock only for the transfer */
xQueueReceive(xQ, &item, portMAX_DELAY);
xSemaphoreTake(xBus, pdMS_TO_TICKS(50));
bus_use(&item);
xSemaphoreGive(xBus);The scheduler lock. A queue operation runs part of its work with interrupts masked or the scheduler locked, which is why large items hurt latency and why you must not call queue functions from inside your own critical sections or with the scheduler suspended and expect to block. A call that would block while the scheduler is suspended asserts or fails.
Waiting on several sources
A task often needs to react to whichever of several inputs arrives first: a command queue, a sensor queue and a stop signal. A task cannot block on two queues at once with plain receives. There are three ways out.
A queue set. With configUSE_QUEUE_SETS set to 1, you create a set whose length is the sum of the lengths of its members, add queues and semaphores to it and block on the set. It returns the handle of the member that has data, and you then receive from that member without waiting:
static QueueSetHandle_t xSet;
void set_init(void)
{
xSet = xQueueCreateSet(CMD_QUEUE_LEN + SENSOR_QUEUE_LEN);
configASSERT(xSet != NULL);
xQueueAddToSet(xCmdQueue, xSet);
xQueueAddToSet(xSensorQueue, xSet);
}
static void vMuxTask(void *p)
{
(void) p;
for (;;)
{
QueueSetMemberHandle_t xReady = xQueueSelectFromSet(xSet, portMAX_DELAY);
if (xReady == xCmdQueue)
{
cmd_t c;
xQueueReceive(xCmdQueue, &c, 0);
handle_command(&c);
}
else if (xReady == xSensorQueue)
{
sensor_msg_t m;
xQueueReceive(xSensorQueue, &m, 0);
handle_sensor(&m);
}
}
}Queue sets add RAM and per-operation cost, and the documentation discourages them where a simpler design works. Add members before they hold data, size the set generously and remember that V11.3.3 added a type check on the handle you pass to xQueueSelectFromSet.
One queue of tagged messages. Give every producer the same message type, with a tag, and let the consumer dispatch on the tag. This is usually the simplest design, and it preserves the order across sources, which a set does not. The active-object style, where each task owns one event queue, is the same idea.
An event group plus separate queues. Producers set a bit when they queue something, and the consumer waits on the group and then drains whichever queues the bits name. It suits cases where "something is ready" matters more than ordering.
Backpressure and flow control
A queue that fills up is a symptom. Decide where the pressure goes.
Block the producer. If the producer is a task that can wait, a finite send timeout slows it to the consumer's pace. That is flow control by blocking, and it propagates delay upstream. It is right for batch work and wrong for a producer that has a deadline of its own.
Drop with a count. An interrupt producer cannot wait, so it drops and counts. The count is the measure of how undersized the system is.
Shed by priority. For a mix of important and routine messages, use two queues, or send routine messages with a zero wait and important ones with a long wait. When the consumer is overwhelmed, the routine ones are lost first.
Coalesce. For a stream of readings where only the latest matters, a length-one queue with xQueueOverwrite is lossy by design and never fills.
Throttle the source. A peripheral that supports flow control, such as UART RTS, can be told to pause when the buffer passes a watermark. Check xStreamBufferSpacesAvailable or uxQueueSpacesAvailable in the producer and assert the hardware line below a threshold.
Write the policy down beside the queue. A queue without a stated policy is a latent bug that appears first in the field.
Memory accounting
Every object costs RAM, and the costs differ.
| Object | Storage | Control structure | Allocated from |
|---|---|---|---|
| Queue | length x item size | A queue control block | The heap, or your buffers with xQueueCreateStatic |
| Stream buffer | The byte capacity you give | A stream buffer control block | The heap, or xStreamBufferCreateStatic |
| Message buffer | The byte capacity, including 4-byte prefixes | The same control block as a stream buffer | The heap, or xMessageBufferCreateStatic |
| Task notification | None | Fields in the task control block | The task's own allocation |
Account for them at design time. A system with ten queues of 16 items of 32 bytes uses 5,120 bytes of storage before control blocks, which is a meaningful share of a 32 KB part. The static variants make the cost visible in the linker map, and the dynamic ones make it a heap-size decision. A common review rule is that every queue creation has a comment giving length, item size and the sizing inputs.
For stream and message buffers, the usable capacity is slightly below the byte count because the implementation needs to distinguish full from empty, so test with the largest burst you expect, not with an exact fit. The message buffer's length prefix means small messages waste a larger fraction: a 1-byte message costs 5 bytes on a 32-bit port.
A worked system: sensor, parser and logger
Here is a design that uses each object where it fits. A device receives framed packets over a UART, parses them, and logs the decoded readings to flash while also publishing the latest reading to a display.
UART interrupt to stream buffer. The receive interrupt, the single writer, places each byte in a stream buffer. A DMA circular buffer would do the same with fewer interrupts.
Parser task from stream buffer to message buffer. The parser, the single reader of the stream buffer, collects bytes until it sees a frame delimiter, validates the frame and sends the decoded packet, whole, into a message buffer. It is the message buffer's only writer.
Dispatcher task from message buffer to queues. The dispatcher, the message buffer's single reader, reads each packet and, depending on its type, sends a log record to a queue consumed by the logger and overwrites the display mailbox.
Logger task from queue to flash. The logger blocks on its queue. Since the logger is the only reader and the dispatcher the only writer, this could also be a message buffer, and a queue is chosen here because the log records have a fixed size and a future second source is likely.
Display task peeks at the mailbox. A length-one queue holds the latest reading, the display peeks at it at its own rate.
static StreamBufferHandle_t xRxStream; /* ISR -> parser */
static MessageBufferHandle_t xPackets; /* parser -> dispatcher */
static QueueHandle_t xLogQueue; /* dispatcher -> logger */
static QueueHandle_t xLatest; /* dispatcher -> display (length one) */
void pipeline_init(void)
{
xRxStream = xStreamBufferCreate(256, 1);
xPackets = xMessageBufferCreate(512);
xLogQueue = xQueueCreate(16, sizeof(log_rec_t));
xLatest = xQueueCreate(1, sizeof(reading_t));
configASSERT(xRxStream && xPackets && xLogQueue && xLatest);
xTaskCreate(vParserTask, "parse", 384, NULL, 3, NULL);
xTaskCreate(vDispatcherTask, "disp", 256, NULL, 2, NULL);
xTaskCreate(vLoggerTask, "log", 384, NULL, 1, NULL);
xTaskCreate(vDisplayTask, "lcd", 256, NULL, 1, NULL);
}
static void vDispatcherTask(void *p)
{
uint8_t pkt[64];
(void) p;
for (;;)
{
size_t n = xMessageBufferReceive(xPackets, pkt, sizeof pkt, portMAX_DELAY);
if (n > 0)
{
reading_t r;
log_rec_t l;
if (decode_reading(pkt, n, &r) && make_log_record(&r, &l))
{
xQueueOverwrite(xLatest, &r);
if (xQueueSend(xLogQueue, &l, 0) != pdPASS)
{
log_dropped++;
}
}
}
}
}Each hop satisfies its object's rules: one writer and one reader for the buffers, a zero-wait send with a counter where the dispatcher must not stall, and a mailbox for the shared latest value. Priorities follow urgency: the parser, which turns interrupt bytes into packets, is highest, and the logger and the display, which tolerate delay, are lowest.
When something fails, the counters point at the hop. Drops in the stream buffer mean the parser is too slow or too low in priority. Drops in the message buffer mean the dispatcher cannot keep up. Drops in the log queue mean flash stalls longer than the queue absorbs, which the sizing formula predicts from the stall length.
Counters and observability
Keep a small statistics module in the shipping build. For every channel, record the number of items sent, the number dropped and the high-water mark of occupancy. These cost a few instructions per operation and tell you more in the field than any amount of testing.
typedef struct {
uint32_t sent;
uint32_t dropped;
uint32_t high_water;
} channel_stats_t;
static inline void stats_record_send(channel_stats_t *s, BaseType_t ok, UBaseType_t occupancy)
{
if (ok == pdPASS)
{
s->sent++;
if (occupancy > s->high_water)
{
s->high_water = occupancy;
}
}
else
{
s->dropped++;
}
}Print or report the statistics periodically, and alert on any non-zero drop count that you did not design in. Treat the high-water mark as a design input: if it sits at a small fraction of the length for weeks, shrink the queue, and if it approaches the length, grow it before a burst fills it.
Failures that lose data silently
| Symptom | Likely cause |
|---|---|
| Bytes missing from a UART stream | Buffer or queue too small, or the reader too slow; check the drop counter |
| Garbage values at the receiver | Wrong item size at creation, or a pointer to a stack variable that was queued |
| A task wakes late after an interrupt | Missing portYIELD_FROM_ISR |
Assertion in vPortValidateInterruptPriority | Interrupt priority above the syscall limit, or left at 0 |
| Message buffer receive loops forever | The receive buffer is smaller than the next message |
| Two writers corrupt a buffer | Stream or message buffer used with more than one writer |
| A producer stalls | A full queue with an infinite send wait |
| Pool shrinks over time | A path forgets to free, or a failed send does not return the buffer |
| Null handle crash | The interrupt fired before the queue was created |
Testing the data path
Test with a known sequence and check order and loss. Send the numbers 0 to 9,999 from the producer and verify in the consumer that each value is exactly one more than the last, then print the counters:
received 10000 items, in order, overflow count 0, queue high water 17 of 30Run the test under the worst load the system will see, including the slowest peripheral, since overflows appear only when something that normally returns at once starts to wait. Keep the high-water mark and drop counters in the production build: they tell you in the field whether your sizing was right. A kernel-aware debugger that lists queues by name, using the registry, shows each queue's contents and blocked tasks directly.
Designing the message type
The item you put in a queue is an interface between tasks, and it deserves the care of an API. A few habits keep it healthy.
Tag every message. One queue that carries several kinds of event needs a discriminator. A tagged union keeps the item a fixed size and lets the consumer switch on the tag:
typedef enum { EV_BUTTON, EV_SENSOR, EV_TIMEOUT } event_kind_t;
typedef struct {
event_kind_t kind;
union {
struct { uint8_t id; bool pressed; } button;
struct { int16_t temperature_c10; } sensor;
struct { uint32_t timer_id; } timeout;
} u;
} event_t;The item is as large as its largest member, so keep the variants small. If one variant is much larger than the rest, send it by descriptor instead.
Keep items free of pointers unless you mean it. A struct that contains a char * into another task's buffer copies the pointer, and every dangling-pointer problem returns. When a pointer is intended, document who owns the target and who frees it.
Include a sequence number or timestamp where order or age matters. A reader that sees a gap knows an item was dropped, and one that sees an old timestamp knows the data is stale. Both cost a few bytes and answer questions that counters alone cannot.
Version the format if it leaves the device. A message buffer that carries packets from a driver to a protocol task is internal, and the same bytes written to flash or sent over a link outlive the build that produced them. Put a version byte at the front.
Mind alignment and padding. The queue copies bytes, and a struct with padding copies the padding too. That is harmless between tasks of one build, and a leak of uninitialized stack bytes if the struct crosses a trust boundary. Zero the struct first with an initializer, as the examples do with designated initializers.
Prefer small, fixed items. A queue item of 8 to 32 bytes keeps the copy cost trivial and the RAM predictable. Anything bigger is a candidate for a descriptor and a pool.
Questions that come up in review
Should a driver expose a queue or a callback? A queue decouples timing: the driver's interrupt never runs application code, and the application chooses its own priority and pace. A callback is simpler and runs in the driver's context, so it must be short and must not block. For anything beyond a flag, the queue is safer.
Where should the queue handle live? Create it in an init function that runs before the scheduler and before the interrupt is enabled, store the handle in a file-scope variable and expose it through a function or a header. A handle created lazily on the first use invites a race between the first sender and the creator.
Is it ever right to use a global variable instead? For a single word written by one context and read by another, with no need for ordering or history, a volatile variable with a single writer works. The moment a struct, a second writer or a need to avoid lost updates appears, move to a queue or a notification.
Can I send from a timer callback? Yes, with a zero block time, because callbacks run in the timer task and must not wait. Count the failures.
Do queues work before the scheduler starts? Creation does. A send to a queue with room works. A call that would block has nothing to wake it, so avoid blocking until the scheduler runs.
Version notes
V11.0.0 changed nothing in the queue API that application code must adapt to, and its release notes list default static-memory callbacks that matter for static queues' siblings, the idle and timer tasks. V11.1.0 added the stream batching buffer, reset-from-ISR functions for stream and message buffers, configUSE_STREAM_BUFFERS and configSTACK_DEPTH_TYPE in the APIs that take stack sizes. V11.3.0 added the overflow assertion in xStreamBufferSendFromISR. V11.3.3 added a check that the object passed to xQueueSelectFromSet really is a queue set, so passing a plain queue handle now fails the check. The version post lists each with its release.
The boundary of this guide
This guide covers single-core Cortex-M usage. On SMP builds, the ISR-safe calls use spinlocks across cores, with extra rules in the port documentation. Queues copy their items, so they are the wrong tool for multi-megabyte transfers, where a shared buffer and a descriptor, as in the pool pattern, is the better design. Stream and message buffers do not support several writers or readers, and a task notification cannot buffer separate values. Event groups, semaphores and mutexes, covered in the next clusters, handle waiting for conditions and locking.
A route through the posts
Start with sending and receiving on a queue, then read why queues copy. Add the peek and overwrite mailbox, then sending from an ISR. Move on to the pool pattern, then the stream buffer and message buffer posts for byte flows and packets. Finish with queue sizing and the comparison post that chooses among all four objects.


