Module 10 · Lesson 66 of 112

Priority scheduling

Implement priority scheduling with aging, demonstrate progress under sustained CPU demand, and measure response and turnaround under round-robin and priority policies.

  • Beginner to advanced
  • 9 min read
  • 45 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM and a Rust toolchain for a host-side scheduler simulator

Your place in the module
By the end you can 4 objectives
  • Select the next ready task by effective priority and FIFO order.
  • Compare the selection and insertion costs of ready-queue layouts.
  • Implement aging and verify that a continuously ready low-priority task receives CPU time.
  • Measure response time and turnaround time for a CPU and I/O workload.
Video coming soonPriority scheduling
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Preemptive round-robin
  • The ready queue holds runnable tasks waiting for the CPU in FIFO order.
  • The timer handler rearms the timer and calls schedule() when the running user task's slice reaches zero.
  • swtch restores the incoming kernel context, and the trap return restores the incoming user context before sret.
01

Choose the highest-priority ready task

3 min read

The last lesson gave every task the same slice. Now you rank tasks by priority, add aging to stop starvation, and measure response against turnaround versus round-robin.

A CPU-bound thread can keep a lower-priority thread waiting even when both have work to do. Linux provides a concrete example in sched(7). Under its real-time SCHED_RR policy, round-robin rotation applies among runnable threads at the same static priority. A higher-priority runnable real-time thread on the same CPU takes precedence over a lower-priority one. The time quantum determines when equal-priority threads take turns. It gives a lower-priority thread no claim to the next turn. sched(7): overview of CPU scheduling

In the single-CPU teaching scheduler, give each task a base priority and an effective priority. A larger value means a higher priority. The base priority is the task's usual rank, and the effective priority is the rank used for selection. Initially they are equal. At each scheduling decision, choose the ready task with the highest effective priority. Within that priority, choose the task that has been queued there longest. This is first in, first out, or FIFO. A task that uses its quantum and can still run returns to the tail of its queue.

Suppose a high-priority task and a low-priority task are both ready. The high-priority task runs first. At the end of its quantum it still has work, so it becomes ready again. The next decision sees the same priorities and selects it again. For as long as the higher-priority task stays runnable, the lower-priority task receives no CPU time. This is . Adding a second high-priority task allows the two high-priority tasks to rotate while the lower-priority task still waits.

A priority rule also needs a policy for when to reconsider the current task. In the simulator, let a newly ready task with strictly higher effective priority preempt at a tick boundary. Requeue the interrupted task with its unused quantum at the front of its own priority queue. A task that ties the running task waits for rotation. If the running task has already used its whole quantum when a higher-priority task becomes ready, handle the expiry first and requeue the expired task at the tail. Use the same boundary rules every time so the same workload gives the same trace.

Priority order at dispatchHighest priorityEmptyMiddle prioritySelect the FIFO headLowest priorityTasks remain readyHighest priorityEmptyMiddle prioritySelect the FIFO headLowest priorityTasks remain ready
The scheduler considers ready tasks in descending priority and chooses the FIFO head of the highest nonempty queue
02

Age waiting tasks and maintain the ready queues

4 min read

Use a fixed range of priorities and choose a positive aging interval measured in ticks. On each tick, credit one tick of waiting to each task that spent the preceding tick Ready. When its waiting counter reaches the interval, clear the counter and raise its effective priority one level, capped at the highest level. Move a promoted task to the tail of its new queue. If multiple tasks qualify at the same tick, process them in their existing queue order within each level and move each task at most once. Collect the promotions before changing the queues so a task moved to a higher queue cannot be processed again on the same tick.

Clear the waiting counter on dispatch. Keep the effective priority for the current quantum, including any unexpired portion if the task is interrupted. When the task exhausts that quantum, reset its effective priority to its base before requeuing it. A task that blocks gives up the rest of its quantum and returns at its base priority with a fresh quantum when it wakes. Retaining the boost through the awarded quantum matters. If you removed it at dispatch, the next priority comparison could immediately put the task below a ready competitor and undo the service the boost was meant to provide.

The progress guarantee follows from two rules. First, a continuously ready task reaches the highest level after a finite number of aging intervals unless it runs sooner. Second, once it joins that queue, only the running task's remaining quantum and the entries already ahead of it can delay it. Each gets a finite turn. Arrivals, further promotions, and tasks requeued after expiry join behind it. This guarantees CPU service when the queue has finitely many entries at promotion and scheduling continues to enforce finite quanta. It does not give every task the same CPU share or guarantee an application deadline. A periodic global boost can serve the same purpose if it puts waiting tasks into a common highest-priority FIFO order and preserves their place long enough for them to rotate through.

The ready-queue layout determines where the work happens. With an unsorted list, appending can be O(1), but each pick must scan up to all n ready entries for the highest rank, so the pick is O(n). With a priority-sorted linked queue, the head is the next task, so selection and removal at the head are O(1). Finding the right insertion point can take O(n), including finding the end of an equal-priority group to preserve FIFO order. Aging requires repositioning entries whose new rank changes their place.

With one FIFO queue per priority, ordinary insertion goes directly to the queue for the task's effective priority. With P priority levels, scanning queue heads from highest to lowest takes O(P), independent of n. A fixed small P therefore gives constant selection cost with respect to the number of ready tasks. If all levels fit in one machine word, a bitmap can record which queues are nonempty. Find the highest set bit, then pop that queue's head. Handle the empty bitmap before finding a bit, and update it when a queue changes between empty and nonempty. This makes a fixed-word pick O(1). The simple aging sweep still examines O(n) tasks each tick. A constant-time pick says nothing about that separate cost.

Ready-queue operation costsUnsorted listSorted queuePriorityqueuesPick nextScan tasksTake headFind highestqueueInsert taskAppendFind sortedpositionAppend withinpriorityWorst-case pickO(n)O(1)O(1) withbitmap
An unsorted list scans at selection, a sorted queue scans at insertion, and fixed per-priority queues bound the selection work

To demonstrate progress, give the high-priority task a CPU burst longer than the observation window. Start a low-priority task ready at the same time and compare strict priority with aging under the same workload. Record promotions, first dispatches, and CPU ticks received. With strict priority, the lower task can remain ready and receive zero ticks throughout the window. With aging, expect a promotion followed by a dispatch and positive CPU service before that same window ends. Choose the window to include the time to reach the highest level plus the turns already ahead. The finite trace shows what happened in the test. The FIFO argument explains what happens if the higher-priority demand continues.

03

Measure response and turnaround

4 min read

Start with a repeatable workload on one simulated CPU. Give a CPU-bound task one long finite CPU burst. Give an I/O-bound task several short CPU bursts separated by fixed simulated I/O delays, and assign it a higher base priority. Release the CPU-bound task first and release the I/O-bound task during its first quantum. Under ordinary round-robin, the I/O task joins the ready queue and waits for a scheduling opportunity. Under the preemptive priority rule, it can run at its release boundary. Once it begins waiting for I/O, the CPU-bound task can resume. On I/O completion, the priority rule can select the I/O task promptly again.

Going deeperExplore the mechanism

A task waits on a condition, such as the completion of a pending read. When the condition is false, the kernel arranges for the task to wait on a wait queue associated with that condition and to leave the running state. While Blocked, the task has no entry in a ready queue. The event producer updates the condition and wakes the relevant waiter or waiters. The scheduler can then move each eligible task from Blocked to Ready and enqueue it once. When dispatched, the waiter checks the condition again, because being woken does not promise that the condition still holds when it runs.

Checking the condition and arranging to sleep must be coordinated with the producer. If the event arrives after a task checks the condition but before it registers as a waiter, a wake could otherwise find nobody and the task could sleep after its event has already happened. Linux's kernel driver documentation describes wait-queue helpers that check the condition and the corresponding requirement to wake waiters after changing state that can satisfy it. In the single-threaded simulator, a scheduled I/O completion can perform the state transition directly at a tick boundary. Keep simulated I/O wait out of the aging counter since the task could do no CPU work during that interval. Linux driver basics: wait queues and wake events

Scheduling around an I/O waitRunningBlockedReadyTransitionsWait for I/ORunningBlockedI/O completesBlockedReadyDispatchReadyRunningQuantum expiresRunningReadyRunningBlockedReadyTransitionsWait for I/ORunningBlockedI/O completesBlockedReadyDispatchReadyRunningQuantum expiresRunningReady
An I/O completion makes a blocked task ready, after which the scheduling policy decides when it runs

Log each task's arrival, first dispatch, and completion. Define tick t as the start of the CPU interval from t to t + 1. If a task uses its final CPU tick in that interval, its completion timestamp is t + 1. An I/O delay starts when a burst ends, and its completion event makes the task eligible at the corresponding boundary. Process arrivals and I/O completions before selecting the task for that interval. Use a fixed order for simultaneous events, such as task ID order.

Response time is first dispatch minus arrival. Turnaround time is completion minus arrival. Turnaround includes ready-queue waiting, CPU service, and any time blocked for I/O. Log first dispatch only once. If you also want to explain the effect of priority on later I/O bursts, separately record wake-to-dispatch delay for each wake. That delay uses the wake timestamp as its origin. Report a missing dispatch or completion as such if the run ends early. A zero response time means the task really was dispatched at its arrival boundary.

Run round-robin and priority with aging using identical arrivals, burst lengths, I/O delays, and quantum. Record a per-task row for each policy and compare the differences before computing any averages. Initial response can improve for the I/O task while the CPU task, which arrived first, has zero response under both policies. The CPU task's turnaround depends on where the I/O bursts and idle intervals fall. Earlier service can start an I/O delay sooner and let that delay overlap with CPU work. This is why a trace with dispatches and wakeups explains changes that isolated totals cannot. Use simulated ticks for the metrics so host scheduling on Ubuntu cannot change the measured intervals.

The next lesson, Proportional-share and MLFQ schedulers, asks how to distribute CPU time by a target share or choose priorities from observed task behavior. Those policies give you new ways to compare response, turnaround, and progress under sustained demand.

Key takeaways

  • Strict priority can indefinitely delay a ready task while higher-priority work stays runnable.
  • Aging can guarantee CPU service when waiting tasks reach the highest priority and ties rotate in FIFO order.
  • A sorted queue and fixed per-priority queues can both select the next task in constant time with respect to the number of ready tasks.
  • Response time ends at first dispatch, while turnaround time ends at completion.
Reflect
  1. Explain to a colleague, in two sentences: select the next ready task by effective priority and FIFO order.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close