How Zephyr chooses the next thread
Zephyr's run queue, next_up and the cache, and how a time slice moves a thread behind its equals, in the real kernel source.
Simulated kernel: 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.
Every context switch needs an answer to one question: which thread runs next? The scheduling lesson gives the rule, the most urgent ready thread. This page reads how Zephyr v4.5.0 keeps its ready threads so that the answer costs almost nothing, and how time slicing makes threads of one priority take turns.
The scenario: three threads A, B and C, all priority 14, each with four ticks of work, and a
time slice of one tick. In the simulator, set the step level to
Line, open the Kernel tab and watch _kernel.ready_q.runq.
One sorted queue
Zephyr offers several run queue implementations. The simulated configuration uses the default for
small systems, CONFIG_SCHED_SIMPLE: one doubly linked list, _kernel.ready_q.runq, holding every
ready thread sorted by priority. (CONFIG_SCHED_SCALABLE uses a balanced tree for systems with
many threads, and CONFIG_SCHED_MULTIQ an array of lists, one per priority, much like FreeRTOS.)
A thread joins the queue here:
static ALWAYS_INLINE void z_priq_simple_add(sys_dlist_t *pq, struct k_thread *thread)
{
struct k_thread *t;
SYS_DLIST_FOR_EACH_CONTAINER(pq, t, base.qnode_dlist) {
if (z_sched_prio_cmp(thread, t) > 0) {
sys_dlist_insert(&t->base.qnode_dlist, &thread->base.qnode_dlist);
return;
}
}
sys_dlist_append(pq, &thread->base.qnode_dlist);
}
kernel/include/priority_q.h, lines 114–126 · Zephyr v4.5.0 · Apache-2.0 license
It walks the queue from the front and inserts the new thread before the first thread that is less
urgent (z_sched_prio_cmp() returns a positive number when its first argument is more urgent). It
never stops at a thread of the same priority, so a thread joins behind its equals: among threads
of one priority the queue is first come, first served.
At start-up the main thread starts the three static threads in the order of their names.
B is added behind A, and C behind B. The queue is then main, A,
B, C: the main thread, at priority 0, is still running and still in the queue.
That last point is a uniprocessor detail worth knowing: the running thread stays in the run
queue. It is not taken out when it starts running, only when it stops being ready. You can see
A in the queue the whole time it runs.
The answer: next_up
static ALWAYS_INLINE struct k_thread *next_up(void)
{
#ifdef CONFIG_SMP
bool ipi_idle_target_rebound = false;
struct k_thread *ipi_idle_target = ipi_idle_reserved_take();
if (z_is_thread_halting(_current)) {
/* NULL key: scheduler context, no retry possible. _current
* cannot have an in-flight timeout (a running thread's
* timeout already fired and its handler returned), so the
* abort inside halt_thread won't see -EAGAIN.
*/
halt_thread(_current, z_is_thread_aborting(_current) ?
_THREAD_DEAD : _THREAD_SUSPENDED, NULL);
}
#endif /* CONFIG_SMP */
struct k_thread *thread = runq_best();
thread = metairq_preempt_recover(thread);
#ifndef CONFIG_SMP
/* In uniprocessor mode, we can leave the current thread in
* the queue (actually we have to, otherwise the assembly
* context switch code for all architectures would be
* responsible for putting it back in z_swap and ISR return!),
* which makes this choice simple.
*/
return (thread != NULL) ? thread : _current_cpu->idle_thread;
#else
/* Under SMP, the "cache" mechanism for selecting the next
* thread doesn't work, so we have more work to do to test
* _current against the best choice from the queue. Here, the
* thread selected above represents "the best thread that is
* not current".
*
* Subtle note on "queued": in SMP mode, neither _current nor
* metairq_premepted live in the queue, so this isn't exactly the
* same thing as "ready", it means "the thread already been
* added back to the queue such that we don't want to re-add it".
*/
bool queued = z_is_thread_queued(_current);
bool active = z_is_thread_ready(_current);
if (thread == NULL) {
thread = _current_cpu->idle_thread;
}
if (active) {
int32_t cmp = z_sched_prio_cmp(_current, thread);
/* Ties only switch if state says we yielded */
if ((cmp > 0) || ((cmp == 0) && !_current_cpu->swap_ok)) {
thread = _current;
}
if (!should_preempt(thread, _current_cpu->swap_ok)) {
thread = _current;
}
}
if (thread != _current) {
update_metairq_preempt(thread);
/*
* Put _current back into the queue unless it is ..
* 1. not active (i.e., blocked, suspended, dead), or
* 2. already queued, or
* 3. the idle thread, or
* 4. preempted by a MetaIRQ thread
*/
if (active && !queued && !z_is_idle_thread_object(_current)
&& metairq_current_requeue_allowed()) {
queue_thread(_current);
}
}
/* Take the new _current out of the queue */
if (z_is_thread_queued(thread)) {
/* Remove or transfer the selected thread's idle CPU coverage. */
if (ipi_idle_target != NULL &&
thread != ipi_idle_target &&
z_is_thread_queued(ipi_idle_target)) {
ipi_idle_target_rebound =
ipi_idle_thread_rebind(thread, ipi_idle_target);
} else {
ipi_idle_thread_unreserve(thread);
}
dequeue_thread(thread);
}
_current_cpu->swap_ok = false;
/* If this CPU consumed a different thread, preserve coverage for the
* runnable thread covered by this CPU's reservation.
*/
if (!ipi_idle_target_rebound &&
ipi_idle_target != NULL && z_is_thread_queued(ipi_idle_target)) {
flag_ipi(ipi_mask_create(ipi_idle_target));
}
return thread;
#endif /* CONFIG_SMP */
}
kernel/sched.c, lines 57–158 · Zephyr v4.5.0 · Apache-2.0 license
Most of the function is for multiprocessor systems and is compiled out (greyed). What remains is
one line: the first thread in the run queue, or the CPU’s idle thread if the queue is empty. Because
the running thread is in the queue too, “the first thread” is already the right answer, and nobody
has to compare it with _current. The cost of choosing is constant; the cost moves to insertion,
which walks the queue.
next_up() is called by update_cache(), which also asks should_preempt() whether the chosen
thread may take the CPU now, and records the answer in _kernel.ready_q.cache. The
context switch walkthrough reads both. The short version:
- A preemptible thread that is running loses the CPU as soon as a more urgent one is first in the queue.
- A cooperative thread (negative priority), or one that holds
the scheduler lock, keeps the CPU until it gives it up, even
when it is no longer first. At start-up you can see this: the main thread has locked the
scheduler, and
should_preempt()answers no each time a thread is started.
Taking turns: the slice
The first switch gives the CPU to A, the first of the three in the
queue, and starts its slice: slice_timeout appears in the timeout list (see
the tick and k_sleep for that list). When the slice timer fires,
its function only sets the flag slice_expired. At the end of the tick’s processing the kernel calls:
void z_time_slice(void)
{
/*
* Atomic context switches need no scheduler work until this CPU's
* time slice expires. Non-atomic context switches must still take
* the scheduler lock to synchronize pending_current.
*/
if (!IS_ENABLED(CONFIG_SWAP_NONATOMIC) &&
!atomic_get(&slice_expired[_current_cpu->id])) {
return;
}
k_spinlock_key_t key = z_sched_spinlock_lock();
struct k_thread *curr = _current;
#ifdef CONFIG_SWAP_NONATOMIC
if (pending_current == curr) {
z_time_slice_reset(curr);
z_sched_spinlock_unlock(key);
return;
}
pending_current = NULL;
#endif
int slice_size = 0;
if (atomic_get(&slice_expired[_current_cpu->id])) {
slice_size = z_time_slice_size(curr);
}
if (slice_size != 0) {
#ifdef CONFIG_TIMESLICE_PER_THREAD
k_thread_timeslice_fn_t handler = curr->base.slice_expired;
if (handler != NULL) {
z_sched_spinlock_unlock(key);
handler(curr, curr->base.slice_data);
key = z_sched_spinlock_lock();
/* The handler ran with the lock dropped and may have
* changed this thread's slice configuration, so the
* cached size is stale; recompute before rearming.
*/
slice_size = z_time_slice_size(curr);
}
#endif
if (!z_is_thread_prevented_from_running(curr)) {
move_current_to_end_of_prio_q();
/* If the rotation kept curr at the front (no other
* runnable thread of equal-or-higher priority is
* waiting), no swap will happen and we must rearm
* here. Otherwise the dispatch path will rearm for
* the new thread with slice_expired still set,
* picking up the tick-aligned delay.
*/
#ifdef CONFIG_SMP
struct k_thread *next = runq_best();
if (next == NULL || z_is_idle_thread_object(next)) {
slice_reset(slice_size);
}
#else
if (_kernel.ready_q.cache == curr) {
slice_reset(slice_size);
}
#endif
}
}
z_sched_spinlock_unlock(key);
}
kernel/timeslicing.c, lines 151–220 · Zephyr v4.5.0 · Apache-2.0 license
If the slice has expired and the current thread can still run, it calls
move_current_to_end_of_prio_q():
void move_current_to_end_of_prio_q(void)
{
runq_yield();
update_cache(1);
}
kernel/sched.c, lines 160–165 · Zephyr v4.5.0 · Apache-2.0 license
runq_yield() is, for the simple queue:
static ALWAYS_INLINE void z_priq_simple_yield(sys_dlist_t *pq)
{
#ifndef CONFIG_SMP
sys_dnode_t *n;
n = sys_dlist_peek_next_no_check(pq, &_current->base.qnode_dlist);
sys_dlist_dequeue(&_current->base.qnode_dlist);
struct k_thread *t;
/*
* As it is possible that the current thread was not at the head of
* the run queue, start searching from the present position for where
* to re-insert it.
*/
while (n != NULL) {
t = CONTAINER_OF(n, struct k_thread, base.qnode_dlist);
if (z_sched_prio_cmp(_current, t) > 0) {
sys_dlist_insert(&t->base.qnode_dlist,
&_current->base.qnode_dlist);
return;
}
n = sys_dlist_peek_next_no_check(pq, n);
}
sys_dlist_append(pq, &_current->base.qnode_dlist);
#endif
}
kernel/include/priority_q.h, lines 135–164 · Zephyr v4.5.0 · Apache-2.0 license
It takes the current thread out of the queue and walks on from where it was, putting it back before
the first less urgent thread: behind every thread of its own priority. Then update_cache(1) picks
the new first thread, with preempt_ok set because the current thread is giving way on its own.
At tick 2 this happens to A. The queue goes from A, B, C to
B, C, A. next_up() returns B, which gets a fresh slice, and the switch itself happens on
the way out of the tick interrupt. At tick 3 B moves behind A, at tick 4 C moves behind B,
and so on.
Where FreeRTOS leaves its ready list in place and moves a walking index (see how FreeRTOS chooses the next task), Zephyr physically moves the thread to the back. The effect is the same rotation.
If no other thread of the same priority is ready, z_priq_simple_yield() puts the thread back where
it was, the cache does not change, and z_time_slice() simply starts a new slice for it.
Why A gets two ticks first
A runs ticks 0 and 1, and every slice after that lasts one tick. A slice is a timeout like any
other. A’s first slice was started from a thread (the main thread, as it ended), so
z_add_timeout() added its usual extra tick: due at 0 + 1 + 1 = 2. Later slices are started inside
the tick’s own processing, right on a tick edge, where slice_reset() asks for one tick less to
cancel that extra tick, so they last exactly one tick. This was checked on the real kernel.
The extra tick has a visible effect at the end. A has done its four ticks of work at tick 8, but at
that moment its slice is also over and it moves behind the others. It only gets the CPU again, and
ends, at tick 10.
What to try
- Set the slice length to 2.
Aruns ticks 0 to 2, then each thread gets two ticks. - Turn Time slicing off. No slice timer is ever started:
Aruns until it ends at tick 4, thenB, thenC. A thread of the same priority that becomes ready joins the back of the queue and waits. - Give
Ban urgency of 2 (priority 13). When it is started it is inserted ahead ofA, and it runs ticks 0 to 3 alone. ThenAandCtake turns.