Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 501 of 9367. Real-Time Operating Systems (RTOS)Free lesson

Implementing Preemptive Priority-Based Scheduling

Design scheduling logic that ensures the highest priority task always gains CPU access by preempting lower priority execution threads.

Implementing Preemptive Priority-Based Scheduling

In this lesson, you will learn how to design scheduling logic that enforces strict priority hierarchies, ensuring that the most critical task always commands the CPU.

The Mechanism of Preemption

In a preemptive priority-based system, the kernel’s scheduler is responsible for ensuring that the processor is always executing the task with the highest priority among those currently ready to run. Unlike cooperative scheduling, where a task must voluntarily yield control, a preemptive system uses the hardware timer interrupt (or a system call) to force a context switch if a higher-priority task transitions into a READY state.

The Decision Logic

The core logic resides within the Scheduler() function, which is typically invoked at the end of every interrupt service routine (ISR) or system call. The scheduler performs three primary steps:

  1. Identify: It scans the Task Control Blocks (TCBs) to find the task with the highest priority that is currently in the READY state.
  2. Compare: It compares this priority against the priority of the currently running task.
  3. Switch: If the ready task has a higher priority, the scheduler saves the current context (registers, stack pointer) and restores the context of the high-priority task.

Consider this simplified conceptual logic:

void Scheduler(void) {
    Task *highestReadyTask = GetHighestPriorityReadyTask();
    
    if (highestReadyTask->priority > RunningTask->priority) {
        // Trigger a context switch
        SaveContext(RunningTask);
        RunningTask = highestReadyTask;
        RestoreContext(RunningTask);
    }
}

Ensuring Consistency

To maintain stability, the scheduler must be atomic—meaning it cannot be interrupted by another task switch while it is in the middle of re-linking the task lists. We achieve this by disabling interrupts briefly during the decision logic. If a hardware interrupt occurs while the scheduler is mid-swap, the resulting context save would corrupt the kernel state. By keeping the logic tight and the critical section short, we ensure the system remains responsive to high-priority events while maintaining deterministic execution.

Key Takeaway: Preemptive priority-based scheduling enforces system determinism by ensuring that the highest-priority ready task immediately displaces any lower-priority task, keeping the CPU focused on the most critical workload at all times.