Time slicing

How tasks of equal priority share the CPU, and why the first slice in Zephyr is one tick longer.

Time slicing on FreeRTOS V11.3.3

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.

Priorities decide between tasks of different urgency. Time slicing (also called round-robin scheduling) decides between tasks of the same priority: each one runs for a slice of time, then goes to the back of the queue.

The simulator above runs three tasks, A, B and C, with the same priority. Each has four ticks of work.

On FreeRTOS

With configUSE_TIME_SLICING set to 1, a slice is always one tick. At every tick, xTaskIncrementTick() looks at the ready list of the running task’s priority. If it holds more than one task, a context switch is requested, and vTaskSwitchContext() takes the next task in the list. The list’s pxIndex pointer, shown in the simulator, walks round the list one task per switch.

The order you see is C, A, B, C, A, B… C goes first because of how the scheduler is started: each newly created task of equal or higher priority becomes the task to run first, so the last one created wins.

On Zephyr

Zephyr’s slice length is configurable (CONFIG_TIMESLICE_SIZE, in milliseconds). The simulator sets it to one tick so the two kernels can be compared; with Zephyr selected you can change Slice length.

Zephyr does not check the run queue on every tick. It arms a timer when a thread starts running, and you can see that timer as the slice_timeout entry in the timeout list. When it fires, z_time_slice() moves the running thread behind the other threads of its priority:

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

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

The threads start in the order of their names, so A runs first. Look at the timeline: A runs for two ticks, and every slice after that is one tick. The first slice was started from thread context, somewhere inside tick 0, and a Zephyr timeout started that way gets an extra tick so that it is never short. Later slices are started from inside the tick interrupt, exactly on a tick edge, and need no extra tick. This was confirmed on the real kernel.

Without time slicing

Untick Time slicing. Now a task that has the CPU keeps it until it blocks, yields or ends, even though other tasks of the same priority are ready. Each task runs its four ticks in one piece.

Higher priorities still preempt. Time slicing only concerns equals.

What it costs

Every slice boundary is a context switch, which takes time and disturbs the CPU caches. With slicing on, three tasks that each need four ticks all finish late: on Zephyr, at ticks 10, 11 and 12. On FreeRTOS their work also ends at 10, 11 and 12, but a task whose work ends exactly on a tick edge is sliced out before it can return, so the timeline shows all three ending at 12. Without slicing they finish at 4, 8 and 12. The total is the same, but the average is worse with slicing. What slicing buys is that no task waits long for its first turn, which matters when the tasks serve different users or devices.

What to try

  • Raise the urgency of B. It runs alone until it ends, and the other two share what is left.
  • On Zephyr, set the slice length to 3 and count the ticks of the first slice.