Queue handoff: who gets an item sent to a waiting task
Zephyr copies an item straight to the task waiting for it; FreeRTOS puts it in the queue and lets the woken task try again. One program, two outcomes.
Simulated kernel: FreeRTOS V11.3.3 and Zephyr v4.5.0. This scenario and every other one are in the scheduler playground. The simulator and its data files are not covered by the site's CC BY-SA license; see their license notices.
A task waits on an empty queue. Another task sends an item. The waiting task obviously gets it, doesn’t it? Not necessarily. When an item is sent to a queue that has a waiting receiver, the kernel can do one of two things, just as with a mutex that is unlocked:
- Put the item in the queue and wake the receiver. The woken task still has to take the item out when it gets the CPU. If another task receives from the queue first, it gets the item.
- Hand the item over. The kernel copies the item straight into the waiting receiver’s buffer inside the send call. The item never sits in the queue, so nobody else can take it.
FreeRTOS does the first, Zephyr the second. The program above makes the difference visible.
The program
Earlyis the least urgent task. It asks for an item at tick 0, findsQempty and waits.Senderis the most urgent. From tick 2 it sendsSender#1, works for two ticks and sendsSender#2.Late, more urgent thanEarly, also starts at tick 2 and asks for an item.
Early has waited longest, and Sender#1 is sent while it waits. Who receives it?
On FreeRTOS
- Tick 0:
SenderandLatesleep until tick 2.EarlycallsxQueueReceive(), finds the queue empty and joins itsxTasksWaitingToReceivelist. - Tick 2:
Senderruns first and sendsSender#1.xQueueGenericSend()copies it into the queue, then sees a task waiting to receive and movesEarlyto its ready list.Earlyis less urgent thanSender, so nothing switches. The kernel panel showsSender#1in the queue, andEarlyready but without an item. Senderworks during ticks 2 and 3 and sendsSender#2at tick 4. Nobody is waiting now, so the item simply joins the queue.Senderends.Lateis the most urgent task that is ready. ItsxQueueReceive()finds two items and takes the oldest:Sender#1.- At tick 5
Earlyfinally runs. It is still inside thexQueueReceive()it called at tick 0; the loop in that function goes round, findsSender#2and returns it.
Waking a task does not give it the item. Had Sender sent only one item, Early would have found
the queue empty when it ran, and gone back to waiting, having been “woken” for nothing.
On Zephyr
- Tick 0: the same, with
Earlyin the message queue’swait_q. Its call left the address of its buffer in the thread’sswap_data. - Tick 3 (Zephyr’s sleeps are one tick longer):
Sendercallsk_msgq_put(). The queue is not full, so the kernel first takes the most urgent waiter off the wait queue,Early, and copiesSender#1straight intoEarly’s buffer.Earlybecomes ready with its item already received. The queue stays empty. Senderworks during ticks 3 and 4 and sendsSender#2at tick 5. Nobody waits, so it goes into the queue.Senderends.Lateruns and receivesSender#2, the only item there is.- At tick 6
Earlyruns, and itsk_msgq_get()returns at once withSender#1.
static inline int put_msg_in_queue(struct k_msgq *msgq, const void *data,
k_timeout_t timeout, bool put_at_back)
{
__ASSERT(!arch_is_in_isr() || K_TIMEOUT_EQ(timeout, K_NO_WAIT), "");
struct k_thread *pending_thread = NULL;
k_spinlock_key_t key;
int result;
bool resched = false;
key = k_spin_lock(&msgq->lock);
if (put_at_back) {
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_msgq, put, msgq, timeout);
} else {
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_msgq, put_front, msgq, timeout);
}
if (msgq->used_msgs < msgq->max_msgs) {
/* message queue isn't full. Try to hand the message
* directly to the longest-waiting receiver, atomically
* under the scheduler's spinlock so a racing in-flight timeout
* handler cannot wake the receiver before the message
* has been copied into its buffer.
*/
LOCK_SCHED_SPINLOCK {
pending_thread = z_unpend_first_thread_locked(&msgq->wait_q);
if (pending_thread != NULL) {
/* copy into the receiver's buffer */
(void)memcpy(pending_thread->base.swap_data, data,
msgq->msg_size);
arch_thread_return_value_set(pending_thread, 0);
z_sched_ready_locked(pending_thread);
resched = true;
}
}
if (pending_thread == NULL) {
size_t msg_size = msgq->msg_size;
char *slot;
__ASSERT_NO_MSG((msgq->write_ptr >= msgq->buffer_start) &&
(msgq->write_ptr <= (msgq->buffer_end - 1)) &&
((size_t)(uintptr_t)(msgq->buffer_end - msgq->write_ptr) >=
msgq->msg_size));
/*
* Pick the slot and update the ring state from
* registers first: the compiler cannot tell that the
* copy leaves the queue fields alone, so copying last
* saves it re-reading them afterwards.
*/
if (put_at_back) {
/*
* to write a message to the back of the queue,
* take the slot write_ptr points at and
* advance write_ptr past it
*/
char *next;
slot = msgq->write_ptr;
next = slot + msg_size;
if (next == msgq->buffer_end) {
next = msgq->buffer_start;
}
msgq->write_ptr = next;
} else {
/*
* to write a message to the head of the queue,
* first decrement the read pointer (to open
* space at the front of the queue) then copy
* the message to the newly created space.
*/
slot = msgq->read_ptr;
if (slot == msgq->buffer_start) {
slot = msgq->buffer_end;
}
slot -= msg_size;
msgq->read_ptr = slot;
}
msgq->used_msgs++;
(void)memcpy(slot, data, msg_size);
resched = msgq_handle_poll_events(msgq);
}
result = 0;
} else if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
/* don't wait for message space to become available */
result = -ENOMSG;
} else {
if (put_at_back) {
SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_msgq, put, msgq, timeout);
} else {
SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_msgq, put_front, msgq, timeout);
}
/* wait for put message success, failure, or timeout */
_current->base.swap_data = (void *) data;
result = z_pend_curr(&msgq->lock, key, &msgq->wait_q, timeout);
if (put_at_back) {
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put, msgq, timeout, result);
} else {
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put_front, msgq, timeout, result);
}
return result;
}
if (put_at_back) {
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put, msgq, timeout, result);
} else {
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put_front, msgq, timeout, result);
}
if (resched) {
z_reschedule(&msgq->lock, key);
} else {
k_spin_unlock(&msgq->lock, key);
}
return result;
}
kernel/msg_q.c, lines 152–272 · Zephyr v4.5.0 · Apache-2.0 license
The handoff happens under the scheduler’s lock, and the comment above it says why: a timeout firing at that moment must not wake the receiver before the message is in its buffer. Once the receiver is off the wait queue with its item, no other thread can get that item.
Which is better?
Neither kernel is wrong; they make different promises.
- Zephyr’s handoff is fair: the item goes to a task that was already waiting for it, and a woken receiver always has an item. The kernel does the copy on the receiver’s behalf.
- FreeRTOS’s way is simpler, and favours urgency: an item goes to whichever task asks for it first once it is in the queue, and that is usually the most urgent one. The price is that a woken task may find nothing, so FreeRTOS’s receive is a loop that can wait again.
Most programs cannot tell the difference: one consumer per queue, or consumers that are all alike. It shows when several tasks receive from one queue and each item matters to a particular one, for example when the item is a reply. Then the order of the items alone should not decide who gets which. Give each consumer its own queue.
The same choice appears on the sending side. When a receive frees a slot in a full queue, Zephyr copies the waiting sender’s item into the queue inside the receive call; FreeRTOS wakes the sender, which sends again when it runs. The producer and consumer lesson has a sender waiting for room; step through tick 4 on each kernel to see it.
What to try
- Set Late starts at tick 6. Now nothing competes with
Early, and both kernels give itSender#1. - Set Late urgency to 1, the same as
Early. On FreeRTOSLatestill getsSender#1: the tick woke it at tick 2, beforeSenderwokeEarly, so it is ahead ofEarlyin the ready list for priority 1. - Set Early urgency to 3 and Sender urgency to 1.
Earlyis now the most urgent task and runs as soon as it is woken, so on FreeRTOS too it takesSender#1before anyone else can.