Skip to content
systemcoding.dev
RTOS

Pass Messages Between Threads With Zephyr k_msgq

Send fixed-size messages between Zephyr threads and from ISRs with k_msgq, using K_MSGQ_DEFINE, put and get with timeouts, peek, purge and sizing rules.

7 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the C, Erlang and C++ logos.

When two threads need to exchange data, the safest design copies the data from one to the other through a kernel object and shares nothing else. Zephyr's message queue, k_msgq, is that object. It is a ring buffer of fixed-size slots with blocking put and get calls, so a fast producer waits when the buffer is full, a slow producer lets the consumer sleep when it is empty, and no one needs a mutex. This post defines a queue in Zephyr 4.2, shows every call you will use, builds a sensor producer and a logger consumer, and covers the rules for sizing the queue and using it from an interrupt. It belongs between the semaphore and the work queue in the threads ladder.

What a message queue holds

A message queue stores up to N messages, each exactly the same size, which you choose when you define it. A message is copied into the queue on put and copied out on get, so the sender's buffer is free to reuse the moment put returns. That removes ownership questions: no one holds a pointer into someone else's memory. The cost is the copy, which is cheap for small structures and wasteful for kilobyte-sized buffers, where a FIFO of pointers or a memory slab is better, as the later comparison post explains.

The reference is the message queue documentation.

Define a queue

c
#include <zephyr/kernel.h>

struct sample {
	uint32_t seq;
	int16_t  temp_decic;
	int16_t  humidity;
};

K_MSGQ_DEFINE(sample_q, sizeof(struct sample), 8, 4);

K_MSGQ_DEFINE(name, msg_size, max_msgs, align) creates the queue and its storage at build time. Here it holds eight struct sample messages, aligned to 4 bytes. The storage is msg_size * max_msgs bytes, 64 here, and lives in RAM. The alignment must match the strictest alignment of the message type, and 4 is right for a structure whose largest member is a 32-bit integer. Use K_MSGQ_DEFINE for statics. At run time, k_msgq_init(&q, buffer, msg_size, max_msgs) initializes a queue over a buffer you provide.

The calls

CallPurposeFrom an ISR
k_msgq_put(&q, &msg, timeout)Copy a message in, waiting if fullOnly with K_NO_WAIT
k_msgq_get(&q, &msg, timeout)Copy the oldest message out, waiting if emptyOnly with K_NO_WAIT
k_msgq_peek(&q, &msg)Copy the oldest message without removing itYes
k_msgq_peek_at(&q, &msg, idx)Look at the message at an indexYes
k_msgq_purge(&q)Discard all messages and wake waitersYes
k_msgq_num_used_get(&q)Messages currently storedYes
k_msgq_num_free_get(&q)Free slotsYes

put and get return 0 on success, -ENOMSG when K_NO_WAIT found the queue full or empty, and -EAGAIN when a timeout expired. k_msgq_purge makes waiting put and get calls return -ENOMSG. Messages leave in first in, first out order. To insert at the front, use k_msgq_put_front, available in recent releases, for urgent messages.

A producer and a consumer

A producer thread creates samples every 200 ms and a consumer prints them:

src/main.cc
#include <zephyr/kernel.h>

struct sample {
	uint32_t seq;
	int16_t  temp_decic;
	int16_t  humidity;
};

K_MSGQ_DEFINE(sample_q, sizeof(struct sample), 4, 4);

static void producer(void *p1, void *p2, void *p3)
{
	uint32_t seq = 0;

	while (1) {
		struct sample s = {
			.seq = seq++,
			.temp_decic = 215 + (seq % 5),
			.humidity = 480,
		};

		int ret = k_msgq_put(&sample_q, &s, K_NO_WAIT);

		if (ret != 0) {
			printk("queue full, dropped %u\n", s.seq);
		}
		k_msleep(200);
	}
}

static void consumer(void *p1, void *p2, void *p3)
{
	struct sample s;

	while (1) {
		k_msgq_get(&sample_q, &s, K_FOREVER);
		printk("sample %u: %d.%d C, %d.%d %%RH\n", s.seq,
		       s.temp_decic / 10, s.temp_decic % 10,
		       s.humidity / 10, s.humidity % 10);
		k_msleep(500);
	}
}

K_THREAD_DEFINE(prod_id, 1024, producer, NULL, NULL, NULL, 5, 0, 0);
K_THREAD_DEFINE(cons_id, 1024, consumer, NULL, NULL, NULL, 6, 0, 0);

int main(void)
{
	return 0;
}
prj.confText
CONFIG_PRINTK=y

The producer is faster than the consumer, 200 ms against 500 ms, and uses K_NO_WAIT, so when the queue of four fills up it drops the newest sample and says so. The beginning of a run looks like this:

Text
*** Booting Zephyr OS build v4.2.0 ***
sample 0: 21.6 C, 48.0 %RH
sample 1: 21.7 C, 48.0 %RH
sample 2: 21.8 C, 48.0 %RH
sample 3: 21.9 C, 48.0 %RH
sample 4: 21.5 C, 48.0 %RH
queue full, dropped 9
sample 5: 21.6 C, 48.0 %RH

The exact sequence of drops depends on timing. This is a deliberate demonstration of backpressure. The producer never blocks, and the consumer sees a bounded backlog. Whether to drop new data, drop old data, or block the producer depends on the application, and the next section discusses it.

Choosing the full-queue policy

When the queue is full, a producer has three options, and each is right for a different source.

Drop the newest. k_msgq_put with K_NO_WAIT fails, and you discard the sample you hold. This keeps old data. It suits a source that you cannot slow down, such as an ISR.

Drop the oldest. Make room by removing the head, then put:

c
if (k_msgq_put(&q, &s, K_NO_WAIT) != 0) {
	struct sample old;

	k_msgq_get(&q, &old, K_NO_WAIT);
	k_msgq_put(&q, &s, K_NO_WAIT);
}

This keeps the freshest data, which is usually right for a sensor. The two calls are not atomic relative to the consumer, so a consumer thread may take the slot between them, and the second put can still fail. Check the second return value if the order matters.

Block the producer. k_msgq_put(&q, &s, K_FOREVER) waits for space. This applies backpressure to a producer that can wait, such as a thread reading from a file. Never block in an ISR, and be careful about blocking a producer that also services hardware.

Using a queue from an interrupt

An ISR may call k_msgq_put with K_NO_WAIT and k_msgq_get with K_NO_WAIT. It must not wait. The standard pattern is to push a small event from the interrupt and let a thread process it:

c
struct button_event {
	uint8_t pin;
	uint8_t level;
	uint32_t when_ms;
};

K_MSGQ_DEFINE(button_q, sizeof(struct button_event), 16, 4);

static void button_isr(const struct device *dev, struct gpio_callback *cb,
		       uint32_t pins)
{
	struct button_event ev = {
		.pin = 11,
		.level = 1,
		.when_ms = k_uptime_get_32(),
	};

	if (k_msgq_put(&button_q, &ev, K_NO_WAIT) != 0) {
		/* queue full: count the loss */
	}
}

Compared with a work item, a queue keeps every event, with its own data, in order. A work item merges repeated submits. Use the queue when each event matters, and the work item when only "something changed" matters.

Sizing the queue

Choose the depth from the worst case, not the average. The queue must hold the messages produced during the longest stretch the consumer cannot run. Estimate it as producer_rate * longest_consumer_pause, rounded up, plus a margin. If a sensor fires 100 times a second and the consumer can be blocked for up to 150 ms by a flash write, the queue needs at least 15 slots, and 20 is sensible. Then verify with the free-space call, logging the minimum free count seen:

c
uint32_t free_slots = k_msgq_num_free_get(&sample_q);

if (free_slots < min_free) {
	min_free = free_slots;
}

A queue that is often near full is a sign of an undersized queue or a consumer that is too slow. Fix the consumer before enlarging the queue, since a larger buffer only delays the same overflow.

Messages that carry pointers

A message may hold a pointer, which is useful for large payloads allocated from a slab or heap. The queue copies the pointer, not the data:

c
struct msg {
	uint8_t *data;
	size_t len;
};

K_MSGQ_DEFINE(rx_q, sizeof(struct msg), 8, 4);

You then own the ownership rules: the sender allocates, the receiver frees, and a dropped message must be freed by the dropper. This is the same discipline as a FIFO, and it is the point where the choice between the objects in the comparison post becomes real.

Mistakes to avoid

Wrong message size. sizeof(msg) must match what you copy. Passing a pointer to a smaller object reads beyond it, and passing a larger one truncates.

Using the queue before initialization. K_MSGQ_DEFINE initializes at build time. A queue built with k_msgq_init must be initialized before any thread or ISR uses it.

**Blocking put from an ISR.** A non-zero timeout in an ISR asserts on debug builds and hangs on release builds.

Ignoring return values. A failed put is a lost message. Count and report them.

Strings and variable-length data. The size is fixed. Store a fixed-size buffer plus a length, or pass a pointer to a buffer from a slab.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.