What are stream buffers and message buffers, and when are they better than queues?
Short answer: FreeRTOS stream buffers pass a continuous stream of bytes from exactly one writer to exactly one reader (like a pipe), and the reader can block until a trigger level of bytes is available. Message buffers are built on stream buffers and pass variable-length messages (each with a length prefix). Both are lighter than queues because they assume a single writer and single reader (no locking among multiple writers), and they copy only as many bytes as needed rather than fixed-size items.
| Queue | Stream buffer | Message buffer | |
|---|---|---|---|
| Item | fixed size | bytes | variable-length messages |
| Writers/readers | many/many | one/one | one/one |
| Typical use | commands, events | UART/USB byte streams, audio | packets, variable-size records |
| ISR use | yes | yes (one side in an ISR) | yes |
| Overhead | higher | low | low |
StreamBufferHandle_t rx = xStreamBufferCreate(256, 1); /* size, trigger level */
void USART2_IRQHandler(void)
{
BaseType_t woken = pdFALSE;
uint8_t b = (uint8_t)USART2->DR;
xStreamBufferSendFromISR(rx, &b, 1, &woken);
portYIELD_FROM_ISR(woken);
}
void rx_task(void *p)
{
uint8_t buf[64];
for (;;) {
size_t n = xStreamBufferReceive(rx, buf, sizeof buf, portMAX_DELAY);
parse(buf, n);
}
}
Rules: if more than one task (or ISR) writes, protect the writes with a critical section or a mutex, because the implementation assumes one writer. With message buffers, the receive buffer must be large enough for the next message, or the call returns 0 and the message stays.
Zephyr equivalents: k_pipe, k_msgq (fixed size), and ring_buf with semaphores.