Operating Systems · Lecture Notes
Chapter 5: CPU Scheduling
Memory holds dozens of processes that are ready to run, but a core can run only one at a time. Each time the CPU becomes free, the operating system's scheduler decides which process runs next. That decision determines how long a user waits after pressing a key, how many jobs a server finishes per hour, and whether a brake controller misses its deadline. These notes begin with the moments at which the decision is made and the criteria by which a good decision is judged. FCFS, SJF, SRTF, priority, and round-robin scheduling are then run step by step on the same set of four processes, so their results can be compared directly. Multilevel queues, proportional-share methods such as lottery and stride scheduling, load balancing on multiprocessors, and RM and EDF for real-time systems follow. The last sections cover the Linux CFS and EEVDF schedulers, Windows priority levels, and methods for evaluating algorithms. Every Gantt chart and average in the chapter was checked by actually running the algorithms.
Learning outcomes
- Concepts
- Explain the CPU–I/O burst cycle, the four situations in which a scheduling decision is made, preemptive and nonpreemptive scheduling, and the job of the dispatcher.
- Criteria
- Compute waiting, turnaround, and response times from a Gantt chart; weigh throughput, CPU utilization, and fairness goals against one another.
- Algorithms
- Apply FCFS, SJF, SRTF, priority, round-robin, MLQ, and MLFQ scheduling step by step to the same set of processes and compare the results.
- Prediction and fairness
- Predict the next CPU burst with an exponential average; prevent starvation with aging, lottery, stride, and fair-share scheduling.
- Multiprocessor and real time
- Explain load balancing and processor affinity; draw RM and EDF schedules and test schedulability with the utilization bound.
- Real systems
- Interpret Linux CFS and its successor EEVDF, Windows priority classes, and dynamic priority boosts.
5.1Basic concepts
An old single-task system has no scheduling problem: there is one program in memory and the CPU runs it. When the program waits for data from the disk, the CPU waits too. Multiprogramming systems fill this gap by keeping many processes in memory at once; when one process starts waiting, the CPU is given to another. The idea is simple, but it immediately raises a question: which of the waiting ready processes should be chosen? That question is the subject of this chapter.
5.1.1What is scheduling?
The short-term scheduler (CPU scheduler) is the kernel component that, when the CPU becomes free, selects which of the processes in the ready queue will run. The ready queue holds the processes that are ready to run and are waiting only for a CPU. Processes waiting for I/O or some other event sit in wait queues.
The scheduler has two goals. The first is to keep the CPU busy: it should never sit idle while a ready process exists. The second is to improve the system's objective. The objective depends on the environment: fast response on a desktop, high throughput on a server, fairness on a shared machine, meeting deadlines on an embedded controller. The same algorithm can be good for one objective and bad for another; this trade-off will come up again and again throughout the chapter.
During its lifetime a process moves among queues (Figure 5.1). A new process enters the ready queue. When the scheduler picks it, it runs on the CPU. If its time slice expires, a clock interrupt stops it and it returns to the ready queue. If it requests I/O, it moves to a wait queue, and when the I/O completes it becomes ready again. When its work is done it leaves the system. Each core runs at most one process at a time; every process other than the running ones sits in some queue.
Despite its name, the ready queue need not be FIFO. Depending on the algorithm it can be a priority queue, a balanced tree, or an unordered linked list. The Linux fair scheduler, for example, uses a red-black tree. The entries in the queue are not the processes themselves but their process control blocks (PCBs).
One more detail: modern kernels that support threads actually schedule kernel threads, not processes. In a multithreaded process each thread is a separate entry in the ready queue. Textbooks still use the phrase "process scheduling," and in these notes the word process means "the unit being scheduled."
5.1.2The CPU–I/O burst cycle
The success of scheduling rests on an observed property of processes: execution alternates between CPU work and I/O waiting. A process computes for a while, then reads a file and waits, then computes again.
A CPU burst is the time a process uses the CPU continuously between two I/O requests. An I/O burst is the time the process waits for an I/O operation to finish. A process begins with a CPU burst and ends with a final CPU burst that issues the termination call (Figure 5.2).
load, store, and add is followed by a file read and a wait; then a new CPU burst begins.Measured CPU burst durations on real systems always have the same shape (Figure 5.3). There are many short bursts and few long ones. The graph is exponential or similar, a curve with a long tail to the right. This observation explains why algorithms that favor processes with short bursts work well.
Processes fall into two groups by burst structure (Figure 5.4). A CPU-bound process has long CPU bursts and infrequent I/O; video encoding, compilation, and scientific computing are examples. An I/O-bound process has short CPU bursts followed by long I/O waits; a text editor, a shell, or a database client is typical. A process can move from one group to the other over time: a program that first reads files and then does a long computation lives through both phases.
What matters for scheduling is not how long the I/O wait is but how short the CPU burst is. If an I/O-bound process is run as soon as it becomes ready, it issues a new I/O request within a few milliseconds, which keeps the disk or network card busy too. If the process is kept waiting behind a long CPU job, the device sits idle. Because disk technology has improved much more slowly than CPUs, most processes have become I/O-bound over time. Not keeping I/O-bound processes waiting is therefore a common design principle of modern schedulers.
5.1.3Overlapping with I/O: treating bursts as separate jobs
Treating each CPU burst of a process as a separate short job gives the scheduler a chance to overlap I/O with computation. This idea lies behind most of the algorithms in the chapter, and it is best understood through an example.
Processes A and B each need 50 ms of CPU time. A runs 10 ms and then waits 10 ms for the disk; this cycle repeats five times. B does no I/O. Let us compare two schedules.
- Schedule without overlap. A's 50 ms of work counts as a single job, and B starts only when A ends. With five CPU bursts and four I/O waits, A finishes at 5 × 10 + 4 × 10 = 90. While A is at the disk the CPU is idle, because the next job is still A. B runs from 90 to 140. The average turnaround time is (90 + 140) / 2 = 115 ms, and CPU utilization is 100 / 140 ≈ 71%.
- Schedule with overlap. Each 10 ms burst of A counts as a separate short job. When A goes to the disk, B runs. When A's I/O completes, the new A job, with 10 ms remaining, preempts B, whose remaining time is longer. This is the behavior of the rule that picks the shortest remaining time (STCF or SRTF). The schedule goes A 0–10, B 10–20, A 20–30, and so on; A still finishes at 90, but B finishes at 100. The average turnaround time is (90 + 100) / 2 = 95 ms, and CPU utilization is 100 / 100 = 100%.
- Comment. A's finishing time did not change, but B finished 40 ms earlier and the CPU was never idle. The gain came from overlapping A's disk waits with B's computation (Figure 5.5).
A real system does not know burst lengths in advance, so the rule "put the short burst first" can be applied only indirectly. The multilevel feedback queue does exactly this: it observes the behavior of processes and keeps those with short bursts in the upper queues.
5.1.4When are scheduling decisions made?
The scheduler is not a loop that runs continuously; it is invoked at particular events. In the process state diagram, four transitions may require a decision (Figure 5.6):
- Running → waiting. The process requests I/O or waits for a child with
wait(). The CPU is free, and a new process must be chosen. - Running → ready. A clock interrupt arrives and the process's time slice has expired. Stopping the running process and choosing another is optional.
- Waiting → ready. An I/O operation completes and the waiting process wakes up. If the woken process is more important than the one currently running, it may preempt it.
- Termination. The process ends with
exit(). The CPU is free, and a choice is again required.
In situations 1 and 4 there is no other option: the CPU is idle and must be given to someone. In situations 2 and 3 the CPU is still running a process, and the scheduler may choose to let it keep running. Schedulers are divided into two kinds according to whether they decide in these two situations.
5.1.5Preemptive and nonpreemptive scheduling
In nonpreemptive (or cooperative) scheduling, decisions are made only in situations 1 and 4. The chosen process runs until it blocks, terminates, or voluntarily gives up the CPU (yield). In preemptive scheduling, decisions are also made in situations 2 and 3. A process can be suspended when its time slice expires or when a more important process becomes ready.
Nonpreemptive scheduling needs no clock interrupt and involves few context switches. Its price is that the system depends on the good will of every program. Windows 3.x and classic Mac OS (9 and earlier) used cooperative multitasking. A single program that entered an infinite loop never released the CPU and could lock up the whole system. Preemptive scheduling prevents this with the clock interrupt: the kernel takes the CPU back at regular intervals. Today all general-purpose operating systems are preemptive (Figure 5.7).
Preemption has a price too. If two processes share data, one can be interrupted while updating it, and the other may read the half-finished, inconsistent state. This risk of a race condition makes synchronization tools mandatory in preemptive systems. Moreover, every preemption means a context switch, which also consumes CPU time.
The same question arises for the kernel's own code. Can a process be preempted while running kernel code in the middle of a system call? Old UNIX kernels waited for the call to finish. Since Linux 2.6, kernel code can be preempted too; preemption happens only if the running code holds no lock. The kernel tracks this with the preempt_count counter it keeps for every task: if the counter is zero, preempting is safe. The PREEMPT_RT patches, developed for real-time use, entered the mainline kernel in Linux 6.12 in 2024 after about twenty years of work. In this configuration interrupt handlers also run as threads and can be preempted; worst-case latency drops to the microsecond range.
Which approach to choose depends on the environment. For batch jobs that run overnight, nonpreemptive or long-slice preemptive algorithms suffice, since nobody is waiting at a screen. In interactive systems and on servers preemption is essential: one process monopolizing the CPU can keep other users' requests waiting for minutes.
Believing that "a preemptive scheduler does not decide at an I/O request." A preemptive scheduler decides in all four situations; it differs from a nonpreemptive one in that it also decides in situations 2 and 3. The completion of a disk read (waiting → ready) can stop the running process only under a preemptive scheduler. Under a nonpreemptive scheduler the woken process joins the ready queue and waits its turn.
5.1.6The dispatcher and the context switch
Choosing and running the chosen process are two separate jobs. The scheduler makes the choice; that is a policy. Placing the chosen process on the CPU is a mechanism, and the dispatcher takes care of it.
The dispatcher is the kernel module that gives the CPU to the process the scheduler selected. It does three things: it switches context, it switches to user mode, and it jumps to the right address in the program. The time the dispatcher takes to stop one process and start another is called dispatch latency (Figure 5.8).
The dispatcher runs at every context switch, so it must be very fast. On today's processors the direct cost is a few microseconds. The indirect cost can be larger: the new process's data is not in the cache, and its first accesses are slowed by misses. Table 5.1 summarizes what changes in a switch between processes.
| Component | On a process switch |
|---|---|
| Registers, PC, SP | saved to the old process's PCB, loaded from the new one's |
| Memory map | the page-table base changes (the CR3 register on x86) |
| TLB | not flushed if the processor supports PCID/ASID tags |
| Caches | not flushed, but cold for the new process |
On Linux, context switches can be measured directly. The vmstat 1 command prints one line per second; its cs column is the total number of context switches in that second. For a single process, the file /proc/<pid>/status keeps two counters. voluntary_ctxt_switches counts the switches in which the process gave up the CPU itself by blocking. nonvoluntary_ctxt_switches counts the switches in which the scheduler forcibly preempted the process. For an I/O-bound process the first counter grows; for a CPU-bound process, the second.
5.1.7Goals by environment
There is no single "best" scheduler, because systems want different things. Tanenbaum groups the goals by environment (Table 5.2). Some goals apply to every system. Fairness means that similar processes get similar shares of the CPU. Policy enforcement means obeying the rule the system sets; for example, security-audit processes run first. Balance means keeping the CPU and the I/O devices busy together.
| Environment | Main goals | Suitable approach |
|---|---|---|
| All systems | Fairness, policy enforcement, balance | — |
| Batch | Throughput (jobs/hour), short turnaround time, high CPU utilization | Nonpreemptive or long-slice preemptive |
| Interactive | Short response time, proportionality (delays that match the user's expectations) | Preemptive, short time slice |
| Real-time | Meeting deadlines (no data loss), predictability (no drop in audio or video quality) | Priority- or deadline-based; tasks run briefly and block |
Proportionality is an interesting goal. A user knows that compressing a large file will take a long time and is willing to wait. But the same user will not tolerate closing a window taking several seconds. A good interactive scheduler keeps delay proportional to the perceived size of the task.
Batch jobs are not a relic of the past. Banks' overnight payroll and account-closing runs, scientific computations, training of AI models, and continuous-integration (CI) builds are still batch jobs today. In high-performance computing centers they are queued by job managers such as Slurm. Goals often conflict: switching context often to shorten response time lowers throughput because of the cost of each switch.
5.1.8Scheduling criteria
To compare algorithms, the goals have to be turned into measurable quantities. Three moments in a process's life are enough to define all of these criteria: its arrival time A in the system, the time F at which it first runs on the CPU, and its completion time C (Figure 5.9).
CPU utilization is the fraction of time the CPU is busy. Throughput is the number of processes completed per unit time. Turnaround time is the time from a process's submission to its completion: C − A. Waiting time is the total time a process spends in the ready queue; if the process does no I/O, it equals turnaround time minus CPU time. Response time is the time from submission to the first time the process gets the CPU: F − A.
The first two criteria should be large and the last three small. In real systems CPU utilization is around 40% on a lightly loaded machine and around 90% on a busy server. None of the criteria is sufficient on its own; the differences between algorithms show up most clearly in the average waiting, average turnaround, and average response times.
One of these criteria is more fundamental than the others. A process's CPU time and I/O time belong to the program itself; they do not change whichever algorithm is chosen. The only thing the scheduler can influence is the time a process waits in the ready queue. Since turnaround time = CPU time + I/O time + waiting time, the difference in turnaround between two algorithms is exactly the difference in waiting.
Response time and waiting time are easy to confuse. Response measures only the first wait: when does the user see the first reaction on screen after typing a command? Waiting time is the sum of all the intervals the process spends in the queue during its life. Under a preemptive algorithm a process may be preempted and returned to the queue many times; its response time can stay small while its waiting time grows large.
In interactive systems the variance of response time matters more than the average. If most commands are answered in 0.1 seconds and one now and then in 5 seconds, users find that more annoying than all of them being answered in 0.5 seconds. Finally, weighted (normalized) turnaround time is the ratio of turnaround time to CPU time. Its ideal value is 1, and it shows how heavily short jobs are penalized.
Suppose P1 (arrival 0, CPU 5), P2 (arrival 1, CPU 4), and P3 (arrival 2, CPU 2) are scheduled with this Gantt chart: P1 0–2, P2 2–4, P3 4–6, P1 6–8, P2 8–10, P1 10–11. Let us find the criteria for the three processes.
- Completion times. The last segment of each process in the Gantt chart: P1 finishes at 11, P2 at 10, P3 at 6.
- Turnaround = completion − arrival. P1: 11 − 0 = 11, P2: 10 − 1 = 9, P3: 6 − 2 = 4. The average is (11 + 9 + 4) / 3 = 8.
- Waiting = turnaround − CPU. P1: 11 − 5 = 6, P2: 9 − 4 = 5, P3: 4 − 2 = 2; the average is 13 / 3 ≈ 4.33. P1's waiting can also be counted directly: it is in the queue during the intervals 2–6 and 8–10, so 4 + 2 = 6.
- Response = first run − arrival. P1: 0 − 0 = 0, P2: 2 − 1 = 1, P3: 4 − 2 = 2; the average is 1.
Because P1 starts immediately, its response time is 0, but because it waited in the queue twice, its waiting time is 6. Response measures the first wait; waiting measures all waits.
Computing waiting time as "completion − CPU time." The formula is turnaround − CPU time, and turnaround is completion − arrival. If the arrival time is not zero, the two give different results. In Example 5.2, completion − CPU for P2 gives 6, while the correct waiting is 10 − 1 − 4 = 5.
5.2Basic algorithms
The best way to understand algorithms is to run them by hand. The algorithms in this section are traced step by step on the same four processes; at the end of each, the average waiting, turnaround, and response times and the number of context switches are given. This way you can see in numbers what an algorithm improves and what it makes worse.
5.2.1The common process set
Table 5.3 gives the common set used throughout the chapter. The four processes arrive one millisecond apart; their CPU times range from 4 to 9 ms. The priority column is used only in priority scheduling (Figure 5.10).
| Process | Arrival | CPU time | Priority |
|---|---|---|---|
| P1 | 0 | 8 | 2 |
| P2 | 1 | 4 | 3 |
| P3 | 2 | 9 | 1 |
| P4 | 3 | 5 | 4 |
Four rules apply in the calculations. A smaller priority number means a higher priority. In a tie, the process that arrived first wins. In round robin, if a process arrives at the same instant another process's slice expires, the newly arrived process enters the queue first. Context-switch time is taken to be zero, and the processes do no I/O. These assumptions are not realistic, but they show the differences between the algorithms plainly.
Context switches are counted as follows: if two consecutive segments in the Gantt chart belong to different processes, there is one switch. A process's first appearance on the CPU is not counted as a switch. If a process is alone in the queue at the end of its slice, moving on to a new slice is not a switch either.
5.2.2FCFS
In first-come, first-served (FCFS) scheduling, the ready queue is FIFO. A process that gets the CPU keeps it until it finishes or blocks. FCFS is nonpreemptive.
FCFS is the easiest algorithm to implement: a new process is appended to the end of the queue, and when the CPU becomes free the head is removed. Both operations are O(1). The trace on the common set goes as follows:
- t = 0. Only P1 is in the queue. P1 gets the CPU and does not release it for 8 ms. During this time P2, P3, and P4 arrive and join the queue in order.
- t = 8. P1 finishes. P2, at the head of the queue, runs. P2 had arrived at 1, so it waited 8 − 1 = 7 ms.
- t = 12. P2 finishes and P3 runs; it waited 12 − 2 = 10 ms.
- t = 21. P3 finishes and P4 runs; it waited 21 − 3 = 18 ms. P4 finishes at 26 (Figure 5.11; Table 5.4).
| Process | Arrival | CPU | First run | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|---|
| P1 | 0 | 8 | 0 | 8 | 8 | 0 | 0 |
| P2 | 1 | 4 | 8 | 12 | 11 | 7 | 7 |
| P3 | 2 | 9 | 12 | 21 | 19 | 10 | 10 |
| P4 | 3 | 5 | 21 | 26 | 23 | 18 | 18 |
| Avg. | 15,25 | 8,75 | 8,75 |
The average waiting time is 35 / 4 = 8.75 ms and the average turnaround time is 61 / 4 = 15.25 ms. In nonpreemptive algorithms, once a process first starts running it continues until it finishes, so response time equals waiting time. The Gantt chart has three switches: P1→P2, P2→P3, P3→P4.
5.2.3The convoy effect
FCFS's average waiting time is not constant; it is extremely sensitive to the arrival order of the processes. Silberschatz's classic example shows this clearly.
P1 (24 ms), P2 (3 ms), and P3 (3 ms) are ready at t = 0. What is the average waiting time under FCFS for two different arrival orders?
- Order P1, P2, P3. P1 0–24, P2 24–27, P3 27–30. The waiting times are 0, 24, 27; the average is (0 + 24 + 27) / 3 = 17 ms.
- Order P2, P3, P1. P2 0–3, P3 3–6, P1 6–30. The waiting times are P1 6, P2 0, P3 3; the average is (6 + 0 + 3) / 3 = 3 ms.
- Comment. The jobs are the same and the total time is the same (30 ms); only the order changed, and the average waiting time fell from 17 to 3. If a long job is in front, all the short jobs wait for as long as it runs (Figure 5.12).
The problem grows worse in a dynamic environment where processes do I/O. Consider one CPU-bound process C and several I/O-bound processes (I1, I2, I3). While C holds the CPU with its long burst, the I/O of the I/O-bound processes completes and they all line up in the ready queue behind C. Meanwhile the disk is idle. When C finally goes to I/O, I1, I2, and I3 quickly finish their short bursts and go to the disk. This time the CPU is idle. Then C comes back and the cycle repeats.
The convoy effect is the accumulation of processes with short bursts behind a single process with a long burst. As a result the CPU and the I/O devices are idle in turn, and their utilization drops (Figure 5.13).
There is no starvation in FCFS: every process runs once those ahead of it are done. But because it is nonpreemptive, a single long job can hold the system for a long time. This is why FCFS is not suitable for interactive systems. Still, it lives on inside many algorithms: to break ties among processes of equal priority, arrival order is usually used.
5.2.4Code trace: FCFS waiting time
FCFS's waiting-time calculation can be done with a single loop. The following C function takes an array of processes sorted by arrival time, prints each process's waiting time, and prints the average.
/* p[] sorted by arrival time */
void fcfs(Proc p[], int n) {
int t = 0, sum = 0;
for (int i = 0; i < n; i++) {
if (t < p[i].arrival) t = p[i].arrival;
int wait = t - p[i].arrival;
t += p[i].burst; /* completion */
sum += wait;
printf("%s: %d\n", p[i].name, wait);
}
printf("avg = %.2f\n", (double) sum / n);
}t is the clock holding the moment the CPU becomes free; sum is the total of the waiting times. For each process the loop first checks whether the clock is behind the process's arrival. If it is, the CPU sat idle, and the clock is advanced to the arrival time. On the common set this line never runs, because the processes arrive before the CPU becomes free, but it is necessary for sets with gaps. Then the waiting time is computed as t - p[i].arrival: the time from the process's arrival until it gets the CPU. t += p[i].burst moves the clock to the process's completion. At the end the total is divided by the number of processes; the (double) cast prevents integer division (Table 5.5).
| i | Process | t (at start) | wait | t (at end) | sum | Output |
|---|---|---|---|---|---|---|
| 0 | P1 (0, 8) | 0 | 0 − 0 = 0 | 8 | 0 | P1: 0 |
| 1 | P2 (1, 4) | 8 | 8 − 1 = 7 | 12 | 7 | P2: 7 |
| 2 | P3 (2, 9) | 12 | 12 − 2 = 10 | 21 | 17 | P3: 10 |
| 3 | P4 (3, 5) | 21 | 21 − 3 = 18 | 26 | 35 | P4: 18 |
| — | avg = 8.75 |
The function runs in O(n) time and uses no extra memory. The array must be sorted; sorting takes O(n log n). The decimal separator in the program's output is a point because printf works with the C locale.
5.2.5SJF: shortest job first
The convoy example offers a hint: putting short jobs first lowers the average waiting time. SJF turns this idea into a rule.
In shortest-job-first (SJF) scheduling, when the CPU becomes free, the ready process whose next CPU burst is shortest is chosen; ties are broken by FCFS. In these notes the name SJF denotes the nonpreemptive version; the preemptive version is called SRTF.
The name of the algorithm is slightly misleading. The choice is determined not by the total length of the job but by the length of the next CPU burst. A more accurate name would be "shortest next CPU burst."
If all jobs are ready at the same time and their lengths are known, the SJF order minimizes the average waiting time (and the average turnaround time).
The reasoning is as follows. Let four jobs have lengths a, b, c, d and run in that order. The first finishes at time a, the second at a + b, the third at a + b + c, and the fourth at a + b + c + d. The average turnaround is (4a + 3b + 2c + d) / 4. The first job's length is added to all four turnaround times, the last one's to only one. The largest coefficient belongs to a; to make the sum small, the shortest job must go first. If two adjacent jobs are swapped so that the shorter one comes first, the sum either decreases or stays the same. These swaps eventually lead the order to the SJF order (Figure 5.14).
The theorem has two conditions, and both matter. The first is that the jobs are ready at the same time. If the jobs arrive at different times, nonpreemptive SJF is not optimal: if a short job arrives right after a long job has started, SJF must make it wait. In that case the optimal version is the preemptive one, SRTF. The second condition is that the lengths are known. In batch systems the user gives a time limit when submitting a job; the --time option in Slurm is an example. A job that gives a short limit has a better chance of running first, but if the time is exceeded the job is terminated. In short-term scheduling the next burst can never be known; it can only be predicted from past bursts.
SJF also has a starvation problem. If short jobs keep arriving, a long job may never be chosen. SJF aims to minimize average waiting and turnaround time; it does not increase CPU utilization. In every algorithm in this chapter the CPU is already busy as long as there is a ready job.
Four processes are ready at t = 0: P1 = 6, P2 = 8, P3 = 7, P4 = 3 ms. Let us find the schedule and averages under SJF and compare with FCFS.
- t = 0. All are ready; P4 (3), with the shortest CPU time, is chosen.
- t = 3. P4 is done. Ready: P1 (6), P2 (8), P3 (7). The shortest is P1 (6); it runs 3–9.
- t = 9. Ready: P3 (7), P2 (8). P3 runs 9–16.
- t = 16. Only P2 is left; it runs 16–24.
- Averages. Waiting times are P1 3, P2 16, P3 9, P4 0; the average is 28 / 4 = 7 ms. Turnaround times are 9, 24, 16, 3; the average is 13 ms. Had the same set run under FCFS (in the order P1, P2, P3, P4), the waiting times would be 0, 6, 14, 21 and the average 41 / 4 = 10.25 ms (Figure 5.15).
5.2.6SJF on the common set and weighted turnaround
On the common set the processes arrive at different times, and the weakness of nonpreemptive SJF shows. At t = 0 only P1 is present and it gets the CPU. Short jobs that arrive later cannot stop P1.
- t = 0. Only P1 is ready; it runs 0–8.
- t = 8. P1 is done. Ready: P2 (4), P3 (9), P4 (5). The shortest is P2; it runs 8–12.
- t = 12. Ready: P3 (9), P4 (5). The shortest is P4; it runs 12–17.
- t = 17. Only P3 is left; it runs 17–26 (Figure 5.16; Table 5.6).
| Process | Arrival | CPU | First run | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|---|
| P1 | 0 | 8 | 0 | 8 | 8 | 0 | 0 |
| P2 | 1 | 4 | 8 | 12 | 11 | 7 | 7 |
| P3 | 2 | 9 | 17 | 26 | 24 | 15 | 15 |
| P4 | 3 | 5 | 12 | 17 | 14 | 9 | 9 |
| Avg. | 14,25 | 7,75 | 7,75 |
Compared with FCFS, SJF lowered the average waiting time from 8.75 to 7.75. The first two processes ran the same as under FCFS; the difference comes from P4 getting ahead of P3. P4's waiting dropped from 18 to 9 and P3's rose from 10 to 15: the 9 ms gained for the short job is more than the 5 ms taken from the long one.
Weighted turnaround time makes this trade more visible. Table 5.7 compares two algorithms on another set of five jobs.
| A | B | C | D | E | Avg. | ||
|---|---|---|---|---|---|---|---|
| Arrival | 0 | 1 | 2 | 3 | 4 | ||
| CPU | 4 | 3 | 5 | 2 | 4 | ||
| SJF | Completion | 4 | 9 | 18 | 6 | 13 | |
| Turnaround | 4 | 8 | 16 | 3 | 9 | 8 | |
| Weighted | 1 | 2,67 | 3,2 | 1,5 | 2,25 | 2,12 | |
| FCFS | Completion | 4 | 7 | 12 | 14 | 18 | |
| Turnaround | 4 | 6 | 10 | 11 | 14 | 9 | |
| Weighted | 1 | 2 | 2 | 5,5 | 3,5 | 2,8 |
Under SJF, A runs 0–4. At t = 4, B (3), C (5), D (2), and E (4) are ready; the shortest, D, runs 4–6. Then come B 6–9, E 9–13, and last C 13–18. C's weighted turnaround is 16 / 5 = 3.2. The average for SJF is 2.12 and for FCFS 2.8. Under FCFS the largest penalty falls on the 2 ms job D: its turnaround of 11 ms is 5.5 times its CPU time.
FCFS's penalizing of short jobs is more striking on an extreme set. In the set A (arrival 0, CPU 1), B (1, 100), C (2, 1), D (3, 100), the 1 ms job C waits 99 ms behind B. C's turnaround is 100 and its weighted turnaround is 100 / 1 = 100. D, which suffers the same wait, has a weighted turnaround of only 199 / 100 = 1.99. A 99 ms wait is negligible for a long job and a disaster for a short one.
5.2.7Predicting the next burst: the exponential average
The only way to use SJF in short-term scheduling is to predict the next burst. The usual method is the exponential average of past bursts.
The exponential average prediction of the next burst is
τn+1 = α · tn + (1 − α) · τn, 0 ≤ α ≤ 1
Here tn is the measured actual length of the n-th burst; τn is the prediction made for that burst; and τ0 is a constant chosen at the start (for example, the system average).
The formula builds the new prediction as a mixture of two pieces of information: the latest measurement and the old prediction, which summarizes the past. α sets their weights. If α = 0, the latest measurement is ignored and the prediction stays at τ0. If α = 1, only the last burst counts; the prediction equals the last measured burst. A common choice is α = ½: the latest measurement and the past get equal weight.
The name becomes clear when the formula is expanded:
τn+1 = α tn + (1 − α) α tn−1 + (1 − α)2 α tn−2 + … + (1 − α)n+1 τ0
Because 1 − α is less than one, each older measurement has a weight that is (1 − α) times that of the one before it. For α = ½ the latest measurement has weight ½, the one before it ¼, and the one before that ⅛. Tanenbaum describes the same idea under the name aging: the estimates go T0, T0/2 + T1/2, T0/4 + T1/4 + T2/2, and so on. This "aging" should not be confused with aging in priority scheduling; the latter is a method for preventing starvation.
The following program processes a sequence of seven bursts with α = 0.5 and τ0 = 10.
double tau = 10.0; /* τ0 */
const double a = 0.5; /* α */
int t[] = { 6, 4, 6, 4, 13, 13, 13 };
for (int n = 0; n < 7; n++) {
printf("%.1f %d\n", tau, t[n]);
tau = a * t[n] + (1 - a) * tau;
}
printf("next: %.1f\n", tau);At each step the loop first prints the prediction made for that burst and the actual value, then updates the prediction. The update line corresponds exactly to the formula: a * t[n] is the share of the latest measurement and (1 - a) * tau is the share of the old prediction. When the loop ends, the prediction that has seen all seven measurements is printed as "next" (Table 5.8).
| n | prediction τn | actual tn | computation | new τn+1 |
|---|---|---|---|---|
| 0 | 10 | 6 | 0,5 · 6 + 0,5 · 10 | 8 |
| 1 | 8 | 4 | 0,5 · 4 + 0,5 · 8 | 6 |
| 2 | 6 | 6 | 0,5 · 6 + 0,5 · 6 | 6 |
| 3 | 6 | 4 | 0,5 · 4 + 0,5 · 6 | 5 |
| 4 | 5 | 13 | 0,5 · 13 + 0,5 · 5 | 9 |
| 5 | 9 | 13 | 0,5 · 13 + 0,5 · 9 | 11 |
| 6 | 11 | 13 | 0,5 · 13 + 0,5 · 11 | 12 |
The program's output is the seven lines 10.0 6, 8.0 4, 6.0 6, 6.0 4, 5.0 13, 9.0 13, 11.0 13 and finally next: 12.0. In the first half of the sequence the bursts move back and forth between 4 and 6, and the prediction settles into that range. When the bursts jump to 13, the prediction catches up in a few steps, 5 → 9 → 11 → 12, closing half the remaining gap at each step. That the prediction follows reality with a delay is clearly visible in Figure 5.17.
The choice of α is a trade-off. If the same sequence is run with α = 0.75, the final prediction is ≈ 12.9 and the jump is caught faster; but a single outlying measurement also shakes the prediction that much more. With α = 0.25 the final prediction stays at ≈ 10.3: the prediction is stable but adapts slowly to change.
Let α = 0.5 and τ0 = 12 ms. The first three measured bursts are 8, 6, and 10 ms. What are τ1, τ2, and τ3? What would τ3 be if α = 1?
- τ1 = 0.5 · 8 + 0.5 · 12 = 4 + 6 = 10 ms.
- τ2 = 0.5 · 6 + 0.5 · 10 = 3 + 5 = 8 ms.
- τ3 = 0.5 · 10 + 0.5 · 8 = 5 + 4 = 9 ms.
- If α = 1, only the last measurement counts: τ3 = t2 = 10 ms. If α were 0, the prediction would never change and would stay at 12.
Confusing tn with τn in the formula, or always computing the new prediction from τ0. At each step the result of the previous step is used. In Example 5.5, τ1 = 10 is used to compute τ2, not 12.
5.2.8SRTF: shortest remaining time first
Shortest-remaining-time-first (SRTF; also called SRTN or STCF) is the preemptive version of SJF. When a new process arrives, its CPU time is compared with the remaining time of the running process; if the newcomer is shorter, the running process is preempted.
The SRTF trace on the common set:
- t = 0. Only P1 is present and it starts running.
- t = 1. P2 arrives (4 ms). P1's remainder is 8 − 1 = 7. Since 4 < 7, P1 is preempted and P2 runs.
- t = 2. P3 arrives (9). P2's remainder is 3, and 3 ≤ 9; no preemption.
- t = 3. P4 arrives (5). P2's remainder is 2, and 2 ≤ 5; no preemption.
- t = 5. P2 finishes. The remaining times are P1 7, P3 9, P4 5; the shortest, P4, is chosen and runs 5–10.
- t = 10. P4 finishes. The remaining are P1 7 and P3 9; P1 resumes where it left off, 10–17.
- t = 17. P1 finishes and P3 runs 17–26 (Figure 5.18; Table 5.9).
| Process | Arrival | CPU | First run | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|---|
| P1 | 0 | 8 | 0 | 17 | 17 | 9 | 0 |
| P2 | 1 | 4 | 1 | 5 | 4 | 0 | 0 |
| P3 | 2 | 9 | 17 | 26 | 24 | 15 | 15 |
| P4 | 3 | 5 | 5 | 10 | 7 | 2 | 2 |
| Avg. | 13 | 6,5 | 4,25 |
On this set SRTF lowers the average waiting time to 6.5 ms; it is the best of the algorithms we have examined. The price is four context switches (P1→P2, P2→P4, P4→P1, P1→P3). In preemptive algorithms, response and waiting separate: P1's response time is 0, but its waiting time is 9, because it waited in the queue from 1 to 10.
SRTF is optimal for average waiting time when jobs arrive at different times, but it inherits both problems of SJF. The remaining times must be known, and long jobs may starve. Also, because a comparison is made at every arrival, the number of switches can grow.
P1 (arrival 0, CPU 7), P2 (2, 4), P3 (4, 1), P4 (5, 4) are scheduled with SRTF. What are the Gantt chart and the average waiting time?
- t = 0–2. Only P1 is ready; it runs 2 ms, leaving 5.
- t = 2. P2 arrives: 4 < 5, so P1 is preempted. P2 runs 2–4, leaving 2.
- t = 4. P3 arrives: 1 < 2, so P2 is preempted. P3 runs 4–5 and finishes.
- t = 5. P4 arrives (4). The remaining are P1 5, P2 2, P4 4; the shortest, P2, finishes at 7 (running 5–7).
- t = 7. The remaining are P1 5 and P4 4; P4 runs 7–11. Finally P1 runs 11–16.
- Waiting times. P1: 16 − 0 − 7 = 9, P2: 7 − 2 − 4 = 1, P3: 0, P4: 11 − 5 − 4 = 2. The average is 12 / 4 = 3 ms.
5.2.9Priority scheduling
In priority scheduling each process is given a priority number, and the ready process with the highest priority runs. In these notes a small number means high priority.
The direction of the number varies from system to system, and this is a common source of confusion. In Linux's nice value and in the kernel's internal priority scale, a small number means high priority. In Windows, a large number means high priority: 31 is the highest level.
Priorities come from internal or external factors. Internal priorities rest on measurable quantities: memory requirements, the number of open files, the measured ratio of average I/O burst to CPU burst. External priorities are set outside the operating system: the importance of the job, the fee paid, the organization's policy. SJF is in fact a special case of priority scheduling; the priority is determined by the predicted next burst. If all priorities are equal, the algorithm reverts to FCFS.
Priority scheduling can be preemptive or nonpreemptive. In the preemptive version, a newly arrived process preempts the running one if it has higher priority. In the nonpreemptive version the new process is put at the head of the queue but waits for the running one to finish. Among processes at the same priority level RR can be applied; Figure 5.19(b) shows this combination.
In case (b), P4 at priority 1 runs alone from 0 to 7. At priority 2, P2 (5) and P3 (8) alternate in two-millisecond slices: P2 7–9, P3 9–11, P2 11–13, P3 13–15, P2 finishes at 16 after 15–16, and P3 finishes at 20 after 16–20. At priority 3, P1 (4) and P5 (3) share 20–27 in the same way. The waiting times are P1 22, P2 11, P3 12, P4 0, P5 24.
An important side effect of priority scheduling is priority inversion. Suppose a high-priority process H waits for a lock held by a low-priority process L. L must run to release the lock, but medium-priority processes M keep getting ahead of L. As a result H ends up waiting for all the M processes, which have lower priority than itself. The solution is priority inheritance: the process L that holds the lock temporarily takes over the priority of the waiter until the lock is released.
On the common set, preemptive priority scheduling proceeds as follows (priorities P1 2, P2 3, P3 1, P4 4):
- t = 0. Only P1 is present and it runs.
- t = 1. P2 arrives (priority 3). The running P1's priority (2) is higher; no preemption.
- t = 2. P3 arrives (priority 1). It is higher than P1; P1 is preempted and P3 runs.
- t = 3. P4 arrives (priority 4). It is lower than P3; no preemption.
- t = 11. P3 finishes. Ready: P1 (2), P2 (3), P4 (4). P1 runs its remaining 6 ms, 11–17.
- t = 17. P2 runs 17–21, then P4 runs 21–26 (Figure 5.20; Table 5.10).
| Process | Arrival | CPU | Priority | First run | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|---|---|
| P1 | 0 | 8 | 2 | 0 | 17 | 17 | 9 | 0 |
| P2 | 1 | 4 | 3 | 17 | 21 | 20 | 16 | 16 |
| P3 | 2 | 9 | 1 | 2 | 11 | 9 | 0 | 0 |
| P4 | 3 | 5 | 4 | 21 | 26 | 23 | 18 | 18 |
| Avg. | 17,25 | 10,75 | 8,5 |
With an average waiting time of 10.75 ms it is even worse than FCFS. This is not surprising: the priority algorithm aims not at waiting time but at not keeping important jobs waiting. The most important process, P3, never waited; the least important, P4, waited 18 ms.
P1 (arrival 0, CPU 5, priority 3), P2 (2, 4, 1), P3 (3, 2, 4), P4 (5, 3, 2), P5 (6, 1, 5). What are the Gantt chart and the averages under preemptive priority?
- t = 0–2. P1 runs. At t = 2, the arriving P2 (priority 1) preempts P1.
- t = 2–6. P2 runs. P3 (4) and P4 (2) arrive but are lower than P2; P2 finishes at 6.
- t = 6. Ready: P1 (3), P3 (4), P4 (2), P5 (5). P4 runs 6–9, P1 9–12, P3 12–14, P5 14–15.
- Criteria. Completion times are P1 12, P2 6, P3 14, P4 9, P5 15. Turnaround times are 12, 4, 11, 4, 9; the average is 40 / 5 = 8 ms. Waiting times are 7, 0, 9, 1, 8; the average is 25 / 5 = 5 ms.
If the same set is run with nonpreemptive priority, P1 finishes uninterrupted at 0–5, followed by P2 5–9, P4 9–12, P3 12–14, and P5 14–15. The average waiting time is 24 / 5 = 4.8 ms, which is better than the preemptive result. Preemption does not always improve the average; it only ensures that the high-priority job is not kept waiting.
5.2.10Starvation and aging
Starvation is a process continually losing out to others and never getting to run. Aging is a method of preventing starvation by gradually raising the priority of a process that waits in the ready queue.
Starvation is a real problem in priority scheduling. If high-priority jobs keep arriving, a low-priority job can wait forever. According to a rumor, when the IBM 7094 at MIT was shut down in 1973, a low-priority job submitted in 1967 that had still not run was found. Aging puts an upper bound on this wait.
Nonpreemptive priority scheduling is used. The rule: for every 4 ms spent in the ready queue, the priority number drops by 1. L (3 ms, priority 7) arrives at t = 0; a new job H (4 ms, priority 2) arrives every 4 ms. When does L run?
- t = 0. L's priority is 7, the newly arrived H1's is 2. H1 runs. When L has waited 4 ms its priority becomes 6.
- t = 4, 8, 12, 16. L's priority at these moments is 6, 5, 4, and 3 in turn. Each time, the newly arrived H (priority 2) is higher and runs; L's priority number drops by one after each round.
- t = 20. L's priority has fallen to 2, equal to that of the newly arrived H6. In a tie the one that arrived first wins: L runs and finishes at 23. L waited 20 ms.
In the worst case L waits priority difference × 4 ms = (7 − 2) × 4 = 20 ms. Without aging, L's priority would stay at 7 as long as the H stream continued, and L would never run (Figure 5.21).
Aging does not eliminate starvation, but it turns an infinite wait into a bounded one. The bound is proportional to the priority range and the time between two increments. Suppose priorities in a system range from 0 to 63 and are raised every 10 seconds. A process with priority 63 reaches the highest priority in at most 63 × 10 = 630 seconds (10.5 minutes), even if it never runs.
Counting priority values when computing the aging time. Going from 63 down to 0 takes 63 steps, not 64 values. The waiting time is the number of steps times the step interval: 63 × 10 s = 630 s, not 640 s.
5.3Round robin
FCFS is fair but nonpreemptive; SJF and SRTF are good on average but need to know the times. Interactive systems, on the other hand, need an algorithm that gives everyone a quick response without time information. Round robin is the oldest and most common answer to that need.
5.3.1Cyclic order and the time quantum
Round robin (RR) is FCFS with preemption added. The ready queue is FIFO; each process runs for at most one time slice (time quantum) q. When the slice expires, a clock interrupt arrives and the process goes to the end of the queue. If the process finishes or blocks before its slice is up, it releases the CPU at once (Figure 5.22).
The most valuable property of RR is that it gives a definite upper bound on waiting. If there are n ready processes in the queue and the slice is q, no process waits longer than (n − 1) · q for its next slice, because each process ahead of it uses at most one slice. This bound holds when the number of ready processes n stays constant and context-switch time is neglected; if a new process enters the queue, or each switch takes s, the wait grows accordingly. For example, with 5 processes and a 20 ms slice, every process gets onto the CPU at least once every 80 ms. Response time is bounded and there is no starvation.
The price is paid in turnaround time. Because RR runs the processes in turn, they all stretch out to the very end of the work; turnaround time is generally worse than under SJF. Response time, in contrast, is much better. Silberschatz's classic example shows the difference in numbers (Figure 5.23).
In this example P2 finishes its 17 ms job in the first round. P4 uses its remaining 4 ms in the second round at 117–121; this is the narrow piece in the chart. The completion times are P1 134, P2 37, P3 162, P4 121. The waiting times are P1 134 − 53 = 81, P2 20, P3 162 − 68 = 94, P4 97; the average is 292 / 4 = 73 ms. The SJF order (P2, P4, P1, P3) gives waiting times 0, 17, 41, 94, and the average drops to 38 ms. But under SJF P3 gets onto the CPU for the first time at ms 94; under RR, at ms 37.
Another weakness of RR is its attitude toward I/O-bound processes. An I/O-bound process uses a small part of its slice and blocks for I/O (moves to a wait queue), and when the I/O completes it returns to the end of the ready queue. CPU-bound processes, on the other hand, use the whole slice every time. As a result CPU-bound processes get a larger share of the CPU. This imbalance is the starting point for improvements such as MLFQ and "virtual RR" (a separate, priority auxiliary queue for a process returning from I/O).
5.3.2q = 2 and q = 5 on the common set
Let us trace RR on the common set with two different slices. Recall the rule: if new processes arrive while a process's slice is expiring, the new ones enter the queue first and the process whose slice expired enters after them.
The common set, q = 2 ms. What are the Gantt chart and the criteria?
- t = 0–2. Only P1 is present and it runs 2 ms (6 left). P2 and P3, arriving meanwhile, enter the queue before P1: the queue is P2, P3, P1.
- t = 2–4. P2 runs (2 left). P4, arriving at t = 3, enters before it: the queue is P3, P1, P4, P2.
- t = 4–6. P3 (7 left). t = 6–8. P1 (4 left). t = 8–10. P4 (3 left).
- t = 10–12. P2 uses its last 2 ms and finishes at 12.
- t = 12–20. P3 12–14 (5 left), P1 14–16 (2 left), P4 16–18 (1 left), P3 18–20 (3 left).
- t = 20–26. P1 finishes at 20–22, P4 finishes at 22–23. P3 runs 23–25, and since no other process is in the queue for the remaining 1 ms, it immediately gets a new slice and finishes at 26 (Figure 5.24; Table 5.11).
| Process | Arrival | CPU | First run | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|---|
| P1 | 0 | 8 | 0 | 22 | 22 | 14 | 0 |
| P2 | 1 | 4 | 2 | 12 | 11 | 7 | 1 |
| P3 | 2 | 9 | 4 | 26 | 24 | 15 | 2 |
| P4 | 3 | 5 | 8 | 23 | 20 | 15 | 5 |
| Avg. | 19,25 | 12,75 | 2 |
The average response time fell to 2 ms; this is the best value so far. But with an average waiting time of 12.75 and an average turnaround of 19.25 ms, it is the worst. The Gantt chart has 13 segments and 12 context switches. In a real system each switch takes a few microseconds; although it is taken as zero in this small example, the overhead grows as the slice shrinks.
When the same set is run with q = 5, the table changes. P1 runs 0–5 (3 left); P2, P3, and P4, arriving meanwhile, enter the queue first. P2 finishes at 5–9 before its slice expires. P3 runs 9–14 (4 left) and P4 finishes at 14–19. P1 finishes at 19–22 and P3 at 22–26 (Figure 5.25; Table 5.12).
| Process | Arrival | CPU | First run | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|---|
| P1 | 0 | 8 | 0 | 22 | 22 | 14 | 0 |
| P2 | 1 | 4 | 5 | 9 | 8 | 4 | 4 |
| P3 | 2 | 9 | 9 | 26 | 24 | 15 | 7 |
| P4 | 3 | 5 | 14 | 19 | 16 | 11 | 11 |
| Avg. | 17,5 | 11 | 5,5 |
With the larger slice the number of switches drops from 12 to 5; the average waiting time improves to 11 and the turnaround to 17.5. In return the average response rises from 2 to 5.5 ms. As the slice grows, RR approaches FCFS.
5.3.3Code trace: rr()
The core of RR is a loop of a few lines. The following function takes the array sorted by arrival time and prints each process's completion time. The helper function add_arrivals(p, n, &k, t) adds, in order, the processes that have arrived by time t but have not yet entered the queue. k is the index of the next process in the array to be added.
/* p[] sorted by arrival time */
void rr(Proc p[], int n, int q) {
int t = 0, k = 0; /* k: next arrival */
add_arrivals(p, n, &k, t);
while (!empty() || k < n) {
if (empty()) { /* CPU idle */
t = p[k].arrival; /* next arrival */
add_arrivals(p, n, &k, t);
}
Proc *s = dequeue(); /* head */
int slice = min(q, s->left);
t += slice; s->left -= slice;
add_arrivals(p, n, &k, t); /* first */
if (s->left > 0) enqueue(s); /* then */
else printf("%s %d\n", s->name, t);
}
}The loop continues as long as processes that have not yet arrived remain (k < n), even when the queue is empty. When the queue is empty the CPU is idle; the code advances the clock directly to the arrival time of the next process and adds that process to the queue. Without these lines the loop would end early and processes arriving later would never run. On the common set the CPU is never idle, so this branch does not run. Each round of the loop is one dispatch. The process at the head of the queue is removed and run for min(q, s->left): if the remaining time is shorter than the slice, the process finishes without using up the slice. The clock is advanced and the remaining time reduced. The order of the next two lines determines RR's tie-breaking rule. First the new processes that arrived during this slice are added, and then the process that is not finished goes to the end of the queue. If the two lines were swapped, the process whose slice expired would get ahead of the newcomers and the schedule would be different. A process that finishes does not return to the queue; its name and completion time are printed (Table 5.13).
| Round | Running | slice | t | Left | Queue (head → tail) | Output |
|---|---|---|---|---|---|---|
| initially | — | — | 0 | — | P1 | |
| 1 | P1 | 4 | 4 | 4 | P2, P3, P4, P1 | |
| 2 | P2 | 4 | 8 | 0 | P3, P4, P1 | P2 8 |
| 3 | P3 | 4 | 12 | 5 | P4, P1, P3 | |
| 4 | P4 | 4 | 16 | 1 | P1, P3, P4 | |
| 5 | P1 | 4 | 20 | 0 | P3, P4 | P1 20 |
| 6 | P3 | 4 | 24 | 1 | P4, P3 | |
| 7 | P4 | 1 | 25 | 0 | P3 | P4 25 |
| 8 | P3 | 1 | 26 | 0 | empty | P3 26 |
When the queue is empty and no process is left to arrive, the loop ends: 8 dispatches and 7 context switches. The waiting times are P1 20 − 8 = 12, P2 8 − 1 − 4 = 3, P3 26 − 2 − 9 = 15, P4 25 − 3 − 5 = 17; the average is 11.75 ms. The average turnaround is 18.25 and the average response is (0 + 3 + 6 + 9) / 4 = 4.5 ms (Figure 5.26).
rr() trace (q = 4): P1 0–4, P2 4–8, P3 8–12, P4 12–16, P1 16–20, P3 20–24, P4 24–25, P3 25–26.Each round runs in O(1) time: removing from and adding to the queue take constant time. The total number of rounds is the sum, over the processes, of each CPU time divided by q and rounded up. In this example it is 2 + 1 + 3 + 2 = 8. Consequently, as q shrinks the number of dispatches grows in inverse proportion.
Putting the process whose slice expired ahead of new processes arriving at the same moment. In these notes and in the slides, new arrivals enter first; in the code this is ensured by the add_arrivals line coming before the enqueue(s) line. Textbooks may use different rules on this point; in an RR question, the rule must be settled first.
5.3.4Choosing the time quantum
RR's only parameter is q, and its behavior depends largely on it. When the common set is run with different slices, Table 5.14 results (Figure 5.27).
| Time quantum | Waiting | Turnaround | Response | Switches |
|---|---|---|---|---|
| q = 2 | 12,75 | 19,25 | 2 | 12 |
| q = 3 | 13,5 | 20 | 3 | 9 |
| q = 4 | 11,75 | 18,25 | 4,5 | 7 |
| q = 5 | 11 | 17,5 | 5,5 | 5 |
| q = 6 | 12 | 18,5 | 6,5 | 5 |
| q ≥ 9 (FCFS) | 8,75 | 15,25 | 8,75 | 3 |
Three conclusions follow from the table. First, as q shrinks, response improves but the number of switches grows. Second, average waiting and turnaround do not vary monotonically with q: q = 3 is even worse than q = 2, and q = 5 is better than q = 6. Third, when q is equal to or larger than the longest burst (here P3's 9 ms), no process is preempted and RR becomes exactly FCFS.
That turnaround does not vary monotonically with q can be seen on another set as well. For P1 6, P2 3, P3 1, P4 7 ms (all at t = 0), the average turnaround for q = 1 to 7 is 11; 11.5; 10.75; 11.5; 12.25; 10.5; 10.5 (Figure 5.28, right). The general rule is this: if most processes can finish their work in a single slice, the average turnaround improves.
If each context switch in a real system takes time s, the fraction of CPU time wasted with processes that use their slices to the end is
overhead fraction = s / (q + s)
This formula assumes that every process uses its whole slice and that there is a switch after every slice; for processes that finish before their slice expires or block for I/O, the useful work is shorter than q and the fraction differs. Every round contains q of useful work and s of switching. If q = 4 ms and s = 1 ms, the overhead is 1 / 5 = 20%: one-fifth of CPU time goes only to switching processes. At q = 100 ms the overhead falls to ≈ 1%, but in a queue of ten processes each process waits nearly a second and the system responds sluggishly.
Computing the overhead fraction as s / q. The denominator is the whole round, that is, the sum of useful work and the switch: q + s. For q = 4, s = 1 this gives s / q = 25%; the correct value is 20%.
Today a context switch takes a few microseconds, and typical slices are between 1 and 100 ms. The direct switching overhead is therefore small; the real cost is the cooling of the cache. In Linux's EEVDF scheduler the base slice is computed with the formula 0.75 ms × (1 + log2 of the CPU count). The CPU count in the formula is capped at 8, so on 8 or more cores the slice is 3 ms. In Windows client versions the slice is about two clock ticks. Silberschatz's rule of thumb is this: about 80% of CPU bursts should be shorter than q. That way most processes go to I/O without using up their slice, and the slice limits only the long CPU jobs.
An example shows how a well-chosen slice breaks the convoy effect. In the set P1 24, P2 3, P3 3 ms, the FCFS average waiting time was 17 ms. With q = 4, P1 runs 0–4, P2 4–7, P3 7–10, and P1 10–30. The waiting times are 6, 4, and 7, an average of 17 / 3 ≈ 5.67 ms.
A, B, C, D arrive at t = 0 in that order; each needs 4 ms of CPU. What are the average turnaround and response times under FCFS and under RR with q = 1?
- FCFS. Completion times are 4, 8, 12, 16; the average turnaround is 40 / 4 = 10 ms. Response is (0 + 4 + 8 + 12) / 4 = 6 ms. Three switches.
- RR (q = 1). The processes swap places every millisecond. The last round is at 12–16; completion times are 13, 14, 15, 16 and the average turnaround is 58 / 4 = 14.5 ms. Response is (0 + 1 + 2 + 3) / 4 = 1.5 ms. Fifteen switches.
For jobs of equal length, RR is among the best options in response and the worst in turnaround: everyone is kept waiting until the end of the work.
5.4Multilevel queues
In a real system the processes are not homogeneous. A process playing audio, a text editor the user is typing in, and a script making a nightly backup should not compete fairly in the same queue. Multilevel queues divide processes into classes and give each class its own queue and its own rule.
5.4.1Multilevel queue (MLQ)
In multilevel queue (MLQ) scheduling the ready queue is divided into several separate queues. Each process is assigned permanently to one queue according to its type (for example foreground or background). Each queue has its own algorithm, and there is also a separate scheduling among the queues (Figure 5.29).
In a typical arrangement, interactive foreground processes are scheduled with short-slice RR and background batch processes with FCFS. There are two ways to choose among the queues. With fixed priority, a lower queue never runs until the upper queue is empty. A batch job waits as long as there are processes in the interactive queue and may starve. With time slicing, each queue is given a fixed fraction of the CPU; for example 80% to the foreground and 20% to the background.
MLQ has low overhead: a process is assigned to a queue once and never moved again. But it is not flexible. Even if a process changes its behavior over time, its queue does not change. A process whose class was misjudged either gets a priority it does not deserve or is deprived of the one it deserves. This fixed-assignment structure is MLQ; the structure in which processes change queues according to their behavior is called a feedback queue.
5.4.2Multilevel feedback queue (MLFQ) and its rules
MLFQ gives a practical answer to the question asked at the very beginning of the chapter: how do we put short jobs first without knowing burst lengths? The answer is to observe the processes. Every new job is first assumed to be short and is put in the top queue. If it is really short, it finishes there quickly. If it is long, it uses up its slice and drops to a lower queue. In this way the algorithm learns from the past and approaches SJF.
A multilevel feedback queue (MLFQ) is a multilevel queue in which processes are moved among queues according to their observed behavior. In OSTEP's formulation it has five rules:
- If Priority(A) > Priority(B), A runs.
- If priorities are equal, A and B run in RR.
- A new job enters the top queue.
- A job that uses up its allotment at a level moves down one level, no matter how many times it has given up the CPU.
- After some time period S, all jobs are moved to the top queue (priority boost; Figure 5.30).
Each of the rules solves a problem. The first two set up the basic schedule. The third is the advantage given to new jobs: a short command runs at once and finishes. The fourth pushes long jobs down; counting the allotment as total usage at the level prevents cheating. The fifth prevents starvation and gives a job whose behavior has changed a new chance.
The parameters that define an MLFQ are: the number of queues, the algorithm and slice of each queue, when a job moves to a lower or higher queue, and which queue a new job enters. Usually the slices are short in the upper queues and long in the lower ones: at the top, short jobs cycle quickly; at the bottom, long jobs run less often but for longer. This flexibility makes MLFQ the most general algorithm and at the same time the hardest to tune.
5.4.3MLFQ step by step
Three queues: Q0 (q = 8), Q1 (q = 16), Q2 (FCFS). Jobs (arrival, CPU): A (0, 30), B (2, 6), C (4, 20), D (25, 4). When a job arrives in a higher queue, the preempted job returns to the head of its own queue and completes its slice.
- t = 0. A arrives, enters Q0, and runs with an 8 ms slice. Meanwhile B (t = 2) and C (t = 4) are added to Q0.
- t = 8. A has used up its slice and drops to Q1 (22 left). Next in Q0, B runs.
- t = 14. B finishes in Q0 after 6 ms, before its slice is used up. C runs 8 ms in Q0.
- t = 22. C also drops to Q1 (12 left). Q0 is empty; A, at the head of Q1, starts running with a 16 ms slice.
- t = 25. D arrives and enters Q0. Because Q0 is above Q1, A is preempted and returns to the head of Q1; it has used 3 ms of its slice and 13 ms remain.
- t = 29. D finishes after 4 ms; it never waited. A uses the remaining 13 ms of its slice in Q1.
- t = 42. A has used up its Q1 slice too and drops to Q2 (6 left). C runs in Q1; its remaining 12 ms fit in the 16 ms slice and it finishes at 54.
- t = 54. Q0 and Q1 are empty. A runs its remaining 6 ms in Q2 under FCFS and finishes at 60 (Figure 5.31; Table 5.15).
| Job | Arrival | CPU | Completion | Turnaround | Waiting | Response |
|---|---|---|---|---|---|---|
| A | 0 | 30 | 60 | 60 | 30 | 0 |
| B | 2 | 6 | 14 | 12 | 6 | 6 |
| C | 4 | 20 | 54 | 50 | 30 | 10 |
| D | 25 | 4 | 29 | 4 | 0 | 0 |
| Avg. | 31,5 | 16,5 | 4 |
The short jobs B and D finish quickly in the top queue; their response times are 6 and 0. The long job A filters downward and finishes last. The average response is 4 ms. MLFQ has put short jobs first without knowing any process's length: all it does is count how much CPU each job uses.
With the same rules, take Q0 (q = 4), Q1 (q = 8), Q2 (FCFS) and A (0, 14), B (1, 3), C (3, 9), D (16, 2). When do the jobs finish?
- A uses up its slice at 0–4 and drops to Q1. B finishes at 4–7 before its slice is used up (response 3). C uses up its slice at 7–11 and drops to Q1.
- Q0 is empty; A, at the head of Q1, starts at 11 with an 8 ms slice. At t = 16 D arrives; A, having used 5 ms of its slice, is preempted and returns to the head of Q1.
- D finishes at 16–18. A uses the remaining 3 ms of its slice at 18–21; it has run 4 + 8 = 12 ms in total in Q0 and Q1, and drops to Q2.
- C finishes its remaining 5 ms in Q1 at 21–26. A runs its remaining 2 ms in Q2 at 26–28.
Completion times: B 7, D 18, C 26, A 28. The average response is (0 + 3 + 4 + 0) / 4 = 1.75 ms.
5.4.4MLFQ in practice
Why MLFQ's rules are the way they are becomes clear from the problems that arise when they are not.
Gaming. Had the first form of the rule been "a job that uses up its slice moves down; a job that gives up the CPU before the slice ends stays at the same level," a malicious program could exploit it. The program does a short I/O just before the slice ends, for example using 9.9 ms of a 10 ms slice. It never drops to a lower queue and monopolizes most of the CPU. The solution is to count the allotment as total usage at the level (rule 4). However many pieces the job uses the CPU in, it drops when the total reaches 10 ms (Figure 5.32).
Starvation and change of behavior. If there are many interactive jobs, the upper queues never empty and the long jobs in the lower queue starve. Also, if a long computation later becomes interactive, this goes unnoticed because it stays in the lower queue. Periodic priority boosting (rule 5) solves both problems together. Choosing S is hard. If it is too large, long jobs still starve; if it is too small, interactive jobs do not get enough CPU. OSTEP calls such values "voodoo constants."
History. The MLFQ idea was first implemented by Corbató and his team in 1962 in the CTSS system at MIT. In CTSS the priority classes ran for 1, 2, 4, and 8 slices; a job that finished its slices dropped to a lower class. When Enter was pressed at the terminal, the process was moved to the top class, because the system assumed it had become interactive. Users soon noticed this and pressed Enter now and then to speed up their long jobs. This is one of the first examples of the gaming problem.
Today. The MLFQ idea lives on in many real systems. Solaris's time-sharing (TS) class defines each priority level's slice and its move-down and move-up rule with a table. FreeBSD's ULE scheduler, Windows's dynamic priorities, and macOS use the same idea. Linux, since version 2.6.23, has relied on fair sharing instead of such priority heuristics: first with CFS, then with EEVDF.
Believing that a priority boost prevents fooling MLFQ. A priority boost prevents starvation; the rule that stops a job from always using 9.9 ms of its slice and staying on top is the counting of total usage at the level. Sending every job that does I/O straight to the bottom is not a solution either: jobs that are truly interactive get punished.
5.5Proportional share
The algorithms so far tried to improve turnaround or response time. Proportional-share schedulers set a different goal: each process or user should receive a predetermined share of the CPU. On a cloud server the customer wants the share they paid for; on a shared machine every user wants a fair share.
5.5.1Guaranteed and fair-share scheduling
In guaranteed scheduling, if there are n users (or processes), each is promised 1/n of the CPU. The scheduler computes for each the value ratio = CPU received / CPU entitled to and runs the one with the lowest ratio. In fair-share scheduling the share is given not to processes but to users or groups.
In guaranteed scheduling a process whose ratio is 0.5 has received only half its share and goes to the front. A process whose ratio is 2.0 has received twice its share and yields to those with lower ratios. For the computation it is enough for the scheduler to keep track of how long each process has existed and how much CPU it has used since. Guaranteed scheduling in Tanenbaum's sense is this share guarantee; it does not mean running to a predetermined time schedule.
Per-process fairness rewards a user who starts many processes. Let user 1 run four processes (A, B, C, D) and user 2 a single process (E). With per-process RR the five processes get equal shares, and user 1 gets 80% of the CPU. In fair share the share is first divided among users: 50% to each user. User 1's share is divided among their four processes, and user 2's goes to E. The order takes the form A, E, B, E, C, E, D, E. Shares can also be set by policy; if user 1 is given a 2/3 share, two of every three slices go to their processes (Figure 5.33).
Today fair share on Linux is done with control groups (cgroups). In cgroup v2 each group has a cpu.weight value, and the CPU is divided according to the group weights. systemd puts each user in a group called user-UID.slice; so a user starting a hundred processes does not reduce another user's share. Kubernetes likewise translates the CPU requests given to containers into these weights.
5.5.2Lottery scheduling
In lottery scheduling each process is given tickets. In every slice a ticket is drawn at random and the holder of the ticket runs. In the long run a process's CPU share is the ratio of its tickets to the total number of tickets (Figure 5.34).
The most attractive aspect of the method proposed by Waldspurger and Weihl in 1994 is its simplicity. All that is needed is a random number generator and a running total over the list of processes. Expressing priority is easy too: a more important process gets more tickets. A newly arrived process can win as soon as it receives tickets; in this sense the algorithm responds at once.
Tickets also solve the hard parts of fair share. In ticket transfer, a client waiting for a reply from a server temporarily hands its tickets to the server; the server thus speeds up the work of the client that waits most. Ticket currency lets a user divide their own tickets among their own processes in any unit they like; the system converts it into a global value. In an environment with mutually trusting processes, inflation can also be used: a process that needs more CPU temporarily increases its own number of tickets.
The weakness of lottery is that it is probabilistic. In the short run it can be unfair: two jobs with equal tickets may split 10 slices 7–3. The share approaches the ticket ratio only as the number of draws grows. The method that achieves the same ratio deterministically is stride scheduling.
A has 50 tickets, B has 30, and C has 20. If C is given 20 more tickets, what is the expected number of slices for C in 240 slices?
- The total number of tickets becomes 50 + 30 + 40 = 120.
- C's share is 40 / 120 = 1/3; the expected value in 240 slices is 240 / 3 = 80.
Computing with the old share (20%) gives 48; mistakenly taking the total to be 100 gives 40% and 96. 80 is an expected value; in a single run 75 or 86 may also be seen.
5.5.3Code trace: the drawing loop
OSTEP gives lottery's decision loop as follows. The processes are in a linked list together with their ticket counts; getrandom(0, totaltickets) returns a number between 0 and the total number of tickets. OSTEP gives this function that name; it is pseudocode and not the Linux system call of the same name.
/* one draw per time slice */
int counter = 0;
int winner = getrandom(0, totaltickets);
node_t *current = head;
while (current) {
counter = counter + current->tickets;
if (counter > winner)
break; /* found the winner */
current = current->next;
}
/* current: process that gets the CPU */
run(current);The loop scans the list from the head and keeps in the variable counter the total of the tickets seen so far. At each node the node's tickets are added to the total. The moment the total exceeds the drawn number, the drawn ticket lies in this node's range and the loop breaks. If it does not, the loop moves to the next node. For the trace, the drawn numbers are fixed as 47, 35, and 12 in turn; the ticket list is A 30, B 10, C 60 (total 100). A holds tickets 0–29, B 30–39, C 40–99 (Table 5.16).
| Draw | Node | counter | counter > winner? | Result |
|---|---|---|---|---|
| 47 | A | 30 | no | next node |
| 47 | B | 40 | no | next node |
| 47 | C | 100 | yes | C wins |
| 35 | A | 30 | no | next node |
| 35 | B | 40 | yes | B wins |
| 12 | A | 30 | yes | A wins |
At each new draw the counter starts from zero and the list is scanned from the head. In three slices A, B, and C each ran once. Yet the expected shares are 30%, 10%, and 60%; in the short run the share is not proportional to the tickets, and only in the long run does it approach 30 : 10 : 60.
The cost of a draw is O(n) in the worst case, because the winner may be at the end of the list. If the list is sorted by decreasing ticket count, the processes with the most tickets come first and the scan gets shorter on average. In systems with many processes the selection can be reduced to O(log n) by keeping the running totals in a tree.
5.5.4Stride scheduling
In stride scheduling each process has a stride: stride = a large constant / the number of tickets. Each process also keeps a pass counter, which starts at zero. In every slice the process with the smallest pass value runs and adds its own stride to its pass value.
A process with many tickets has a small stride; its pass value grows slowly and it is chosen often. A process with few tickets has a large stride; once it has run, it stays behind for a long time. Waldspurger proposed this method in 1995 as the deterministic counterpart of lottery (Table 5.17; Figure 5.35).
A has 100 tickets, B has 50, and C has 250; the constant is 10,000. The strides are A 10,000 / 100 = 100, B 200, C 40. In a tie the order A, B, C applies. What is the order of execution over the first 8 slices?
| Slice | pass A | pass B | pass C | Running | Update |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 0 | A | pass(A) = 100 |
| 2 | 100 | 0 | 0 | B | pass(B) = 200 |
| 3 | 100 | 200 | 0 | C | pass(C) = 40 |
| 4 | 100 | 200 | 40 | C | pass(C) = 80 |
| 5 | 100 | 200 | 80 | C | pass(C) = 120 |
| 6 | 100 | 200 | 120 | A | pass(A) = 200 |
| 7 | 200 | 200 | 120 | C | pass(C) = 160 |
| 8 | 200 | 200 | 160 | C | pass(C) = 200 |
In 8 slices A ran 2 times, B 1, and C 5. The ratio is exactly 2 : 1 : 5, which is the ticket ratio 100 : 50 : 250 itself. At the end of the eighth slice all three pass values are 200: one full cycle has been completed and the same pattern starts again. In lottery the same ratio holds only in the long run and only approximately.
One disadvantage of stride is global state. When a new process enters the system, what should its pass value be? If it is given zero, the other processes' pass values are in the hundreds, so the new process would monopolize the CPU for a long time. The new process is therefore started with the smallest pass value at that moment. Lottery has no such problem; a new process just brings its tickets and gets a fair chance at once. Linux CFS's virtual-runtime idea is very close to stride: vruntime is a pass counter, and the inverse of the weight is the stride.
A has 50, B has 100, C has 25 tickets; the strides are A 200, B 100, C 400. What is the order of the first 7 slices?
- Slice 1: pass (0, 0, 0) → A; A becomes 200. Slice 2: (200, 0, 0) → B; B becomes 100. Slice 3: (200, 100, 0) → C; C becomes 400.
- Slice 4: (200, 100, 400) → B; B becomes 200. Slice 5: (200, 200, 400) → tie, A; A becomes 400.
- Slice 6: (400, 200, 400) → B; B becomes 300. Slice 7: (400, 300, 400) → B; B becomes 400.
The order is A, B, C, B, A, B, B. A got 2 slices, B 4, C 1: the ratio 2 : 4 : 1 = 50 : 100 : 25. At the end all three pass values are 400.
5.6Multiprocessor scheduling
Today even a phone has eight cores. With several CPUs the scheduler must answer two questions: which job should run, and on which CPU should it run? The second question is harder than it looks, because of caches and the memory layout.
5.6.1Thread scheduling: PCS and SCS
The kernel schedules not processes but kernel threads. User threads are managed by a library or the language runtime. This two-level structure gives rise to two separate contention scopes.
In process-contention scope (PCS) the thread library makes the user threads of the same process compete on lightweight processes (LWPs) within the process. This scope appears in the N:1 and M:N models. In system-contention scope (SCS) the kernel chooses among all the threads in the system (Figure 5.36).
Pthreads lets a program query and set the scope through an attribute:
pthread_attr_t attr;
int scope;
pthread_attr_init(&attr);
pthread_attr_getscope(&attr, &scope);
if (scope == PTHREAD_SCOPE_PROCESS)
printf("PCS\n");
/* Linux, macOS: SYSTEM only */
pthread_attr_setscope(&attr,
PTHREAD_SCOPE_SYSTEM);
pthread_create(&tid, &attr, runner, NULL);The program creates an attribute object and reads the default scope. If the scope is PTHREAD_SCOPE_PROCESS, it prints PCS. It then sets the scope to system and creates the thread with this attribute. Linux, Windows, and macOS use the 1:1 model, so they support only SCS. On Linux the default scope is already PTHREAD_SCOPE_SYSTEM and the program prints nothing; asking for PCS fails with the ENOTSUP error.
Although the PCS idea was abandoned in operating systems, it has returned in language runtimes. Java 21's virtual threads and Go's goroutines are mapped by the runtime's own scheduler onto a small number of carrier threads. The kernel sees only the carriers; the runtime decides which virtual thread runs on which carrier.
5.6.2Common queue and per-core queues
Multiprocessor scheduling has two basic organizations. In asymmetric multiprocessing (AMP) a single master processor makes all the scheduling decisions and handles the I/O; the others run only user code. It is simple, because only one processor touches the kernel data structures, but the master becomes a bottleneck. In symmetric multiprocessing (SMP) each processor makes its own scheduling decisions. Most modern general-purpose systems are SMP; AMP-like organizations are still used in embedded and heterogeneous systems (for example on chips where a master processor hands out work to auxiliary cores) (Figure 5.37).
In SMP there are two ways to hold the ready processes. In a common queue all the cores take work from the same queue. The load balances itself, because each core that becomes free takes the next job in the queue. But every access to the queue needs a lock, and lock contention grows with the number of cores. Also, a job may run on a different core each time; the data in its cache is useless.
With per-core queues each core has its own ready queue. This is also called two-level scheduling: a job is first assigned to a core and then runs from that core's queue. A lock is almost never needed, and because the job stays on the same core its cache stays warm. Linux, Windows, and FreeBSD use this organization. Its price is that the queues may become unbalanced over time: one core may have five jobs waiting while another sits idle. Load balancing is therefore needed.
5.6.3Multicore and hardware threads
In modern processors a core may spend most of its time waiting for memory. On a cache miss, hundreds of cycles pass until the data arrives from main memory. Silberschatz notes that this memory stall can take up to 50% of core time (Figure 5.38).
Simultaneous multithreading (SMT; Hyper-Threading at Intel) fills this gap. A core has two hardware threads; each has its own set of registers, while the execution units are shared. While one waits for memory, the other executes instructions. The operating system sees each hardware thread as a separate logical CPU; a processor with four cores and SMT shows eight logical CPUs.
This gives rise to two-level scheduling. The operating system chooses which software thread runs on which logical CPU. The core's hardware chooses which hardware thread executes at a given moment. The operating system must know about this distinction. Sibling logical CPUs share execution units. So when an idle physical core exists, putting two busy jobs on the two logical CPUs of the same core is a bad decision; both slow down.
5.6.4Load balancing
Load balancing is the task of distributing jobs evenly among cores. In push migration a periodic checker compares the loads and pushes jobs from an overloaded core to less loaded ones. In pull migration an idle core pulls a job from the queue of a loaded core (Figure 5.39).
With per-core queues the imbalance does not fix itself; someone has to intervene. The two methods complement each other, and Linux uses both. A periodic balancer runs every few milliseconds and removes large differences. When a core's queue empties, pull migration is done without waiting: the idle core steals a job from the busiest queue (Figure 5.40).
Even when balance is achieved, it has a cost. The migrated job's cache is cold on the new core, and its first accesses start with misses. Linux therefore balances in layers. These layers are called scheduling domains. It balances first among the SMT siblings of the same physical core, then among cores that share the last-level cache. Balancing across NUMA nodes is done less often and with a larger imbalance threshold, because migration is most expensive there.
5.6.5Code trace: balance()
The essence of pull balancing is a short function. q[c].n is the queue length of core number c; migrate(src, dst) moves the job at the tail of the source queue to the destination queue.
void balance(int me) { /* idle CPU */
int max = me;
for (int c = 0; c < NCPU; c++)
if (q[c].n > q[max].n) /* busier */
max = c;
int t = (q[max].n - q[me].n) / 2;
for (int k = 0; k < t; k++)
migrate(&q[max], &q[me]); /* from tail */
}The function is called with the number of the core whose queue has emptied (me). The first loop finds the busiest queue: max starts as me and is updated whenever a longer queue is seen. Then the number of jobs to migrate is computed as half the difference. Had the whole difference been moved, the imbalance would merely have changed direction; moving half brings the two queues closer. The last loop takes that many jobs from the tail of the source (Table 5.18; Figure 5.41).
| Step | Event | max | Queue lengths |
|---|---|---|---|
| initially | max = me = 1 | 1 | 3, 0, 5, 2 |
| c = 0 | 3 > 0, busier | 0 | 3, 0, 5, 2 |
| c = 1 | 0 > 3 is false | 0 | 3, 0, 5, 2 |
| c = 2 | 5 > 3, busier | 2 | 3, 0, 5, 2 |
| c = 3 | 2 > 5 is false | 2 | 3, 0, 5, 2 |
t | (5 − 0) / 2 = 2 (integer division) | 2 | 3, 0, 5, 2 |
| k = 0 | H migrates from CPU2 to CPU1 | 2 | 3, 1, 4, 2 |
| k = 1 | G migrates from CPU2 to CPU1 | 2 | 3, 2, 3, 2 |
balance(1): H and G have migrated to CPU1; the lengths are 3, 2, 3, 2.There is a reason jobs are taken from the tail of the queue. The ones at the tail are not those that have waited longest but those that arrived last; they have loaded the least data into the cache, that is, their caches are the coldest. Moving them minimizes the loss of affinity. The function's time is O(NCPU + t). Real kernels look not only at queue length but also at the jobs' weights and their recent CPU usage.
5.6.6Affinity, NUMA, and heterogeneous cores
Processor affinity is the tendency to keep a thread on the CPU whose cache and TLB are warm. With soft affinity the scheduler tries to keep the job on the same CPU but does not guarantee it. With hard affinity the set of CPUs on which the thread may run is specified explicitly.
Linux offers hard affinity through the sched_setaffinity() system call; in the shell, the command taskset -c 0-3 ./prog restricts the program to CPUs 0–3. Databases and real-time applications use this often.
The affinity question grows larger in NUMA (non-uniform memory access) architectures. In multi-socket servers each processor has memory close to it. Access to local memory is fast; access to another node's memory over the interconnect is slow. A good scheduler runs a thread on the node where its memory is. Linux's automatic NUMA balancing samples page accesses and moves tasks closer to their data or pages closer to their tasks (Figure 5.42).
Load balancing and affinity conflict with each other. Migration achieves balance but breaks cache and memory locality. Affinity preserves locality, but some cores may sit idle while others are overloaded. Real schedulers strike a balance between the two with thresholds: if the imbalance is small, jobs stay where they are; if it is large, they are moved.
In recent years cores have stopped being uniform as well. Heterogeneous multiprocessor chips combine high-performance but power-hungry cores with slow but efficient ones. ARM's big.LITTLE and DynamIQ designs, Intel's P and E cores since the 12th generation, and the Apple M series are examples. Intel's Thread Director hardware gives the operating system hints about which kind of core suits which thread. Linux's Energy Aware Scheduling (EAS) puts each job on the core that meets the performance target and uses the least energy. Background jobs go to the efficient cores, and jobs the user is waiting for go to the powerful cores.
Believing that migration is free. Load balancing evens out the jobs, but a migrated job finds the cache and TLB cold on the new core; if it was moved between NUMA nodes, it also accesses its memory remotely. An idle core pulling a job (pull migration) also breaks affinity; under hard affinity, however, the job is never moved.
5.7Real-time scheduling
In a general-purpose system a job finishing late is annoying but not wrong. In a real-time system, a correct result that arrives late counts as wrong. An airbag controller noticing a collision 40 ms late is the same as never noticing it. In these systems the goal of scheduling is not to improve the average but to guarantee every job's deadline.
5.7.1Hard and soft real time, latency
In a hard real-time system, missing a deadline means the system has failed. In a soft real-time system, critical tasks have priority but there is no guarantee; missing a deadline only lowers the quality of service.
ABS braking systems, airbags, industrial robot control, and flight control are hard real time. Video streaming, voice over the internet (VoIP), games, and audio playback are soft real time: if a frame arrives late the picture stutters for a moment, but the system keeps working.
The quantity that measures a real-time system's responsiveness is event latency: the time from the occurrence of an event until the process that serves it starts running. This time is the sum of several components (Figure 5.43). Interrupt latency is the time from the arrival of the interrupt until the interrupt service routine (ISR) starts. The ISR then runs. Finally comes dispatch latency: the scheduler's stopping the running process and starting the real-time process.
In the conflict phase of dispatch latency two things are done. Any work running in the kernel is preempted, and a resource that a low-priority process holds and the real-time process needs is released. For this phase to be short, the kernel must be preemptive; if kernel code could not be preempted, a long system call would have to be waited out. This is why real-time systems require a preemptive, priority-based kernel. Even this alone is not enough for a hard guarantee. Before accepting a new task, the system must test whether all deadlines can still be met when the task is added. This test is called admission control.
Real-time algorithms can be static or dynamic. In static algorithms the priorities are computed once before the system runs; rate-monotonic scheduling is like this. In dynamic algorithms the decisions are made at run time; earliest deadline first is like this.
5.7.2Periodic tasks and rate-monotonic scheduling
Most real-time tasks are periodic. A sensor is read every 10 ms; a control loop computes a new output every 50 ms.
A periodic task requires t of CPU time once every p units of time (the period) and must finish each job by its deadline d; 0 ≤ t ≤ d ≤ p. The task's utilization is U = t / p. In these notes the deadline is the end of the period: d = p (Figure 5.44).
In rate-monotonic (RM) scheduling each periodic task is given a static priority inversely proportional to its period: the shorter the period, the higher the priority. It is preemptive; when a new job of a higher-priority task arrives, the running task is preempted.
The intuition behind RM is simple: a task that must run more often is more urgent. RM is optimal among static-priority algorithms. If a task set can be scheduled by any static priority assignment, it can be scheduled by RM as well. A set that RM cannot schedule cannot be scheduled by any other static priority assignment.
Let n independent periodic tasks have their deadlines at the end of their periods. If the total utilization satisfies
ΣU ≤ n (21/n − 1)
then RM meets all deadlines.
The bound decreases as n grows. Table 5.19 gives a few values; as n goes to infinity the bound approaches ln 2 ≈ 0.693. So whatever the number of tasks, if the total utilization does not exceed 69.3%, RM's success is guaranteed.
| n | 1 | 2 | 3 | 4 | 5 | 10 | ∞ |
|---|---|---|---|---|---|---|---|
| bound | 1 | 0,8284 | 0,7798 | 0,7568 | 0,7435 | 0,7177 | ln 2 ≈ 0.6931 |
The direction of the theorem matters: the condition is sufficient, not necessary. If the utilization is below the bound, RM certainly succeeds. If it is above the bound, RM may or may not succeed; the test gives no conclusion. To decide, the schedule must be drawn over one hyperperiod (the least common multiple of the periods). If the total utilization exceeds 1, no algorithm can schedule the set: more than one second of work per second is being demanded of the CPU.
P1 (p = 50, t = 20) and P2 (p = 100, t = 35). Can they be scheduled with RM?
- Test. U = 20/50 + 35/100 = 0.40 + 0.35 = 0.75. For n = 2 the bound is 0.828; since 0.75 ≤ 0.828, RM meets all deadlines.
- Schedule. P1 has the short period and the high priority. P1 runs 0–20, P2 20–50 (30 ms). At t = 50 a new job of P1 arrives and preempts P2: P1 50–70. P2 finishes its remaining 5 ms at 70–75; its deadline is 100. From 75 to 100 the CPU is idle.
- The second hyperperiod. From 100 to 200 the same pattern repeats. No deadline is missed (Figure 5.45).
5.7.3RM and EDF on the same set
In earliest-deadline-first (EDF) scheduling the priority is dynamic: among the ready jobs, the one with the nearest deadline runs. A job's priority is redetermined in every new period, according to its new deadline.
EDF's schedulability condition is much more generous: for preemptive, independent tasks whose deadlines are at the end of their periods, ΣU ≤ 1 is both sufficient and necessary. EDF can in theory use the CPU up to 100%. Let us see the difference between the two algorithms on a set that RM fails to pass the test on.
P1 (p = 50, t = 25) and P2 (p = 80, t = 35). U = 25/50 + 35/80 = 0.5 + 0.4375 = 0.9375 > 0.828: there is no guarantee for RM; but since U ≤ 1, EDF suffices.
- RM. P1 (short period) runs first at 0–25 and P2 at 25–50; P2 has completed 25 ms and has 10 ms left. At t = 50 a new job of P1 arrives and, having the higher static priority, preempts P2; P1 runs 50–75. P2 runs 5 ms more at 75–80, but its time runs out at t = 80: P2 misses its deadline with 5 ms short.
- EDF, t = 50. The new job of P1 has deadline 100 and that of P2 has deadline 80. P2, with the nearer deadline, continues and finishes at 60. P1 runs 60–85.
- EDF, t = 80. A new job of P2 arrives; its deadline is 160. Since P1's is 100, P1 continues until 85. P2 runs 85–100. At t = 100 the deadline of P1's new job is 150 < 160 and P1 goes ahead: P1 100–125, P2 finishes at 125–145. From 145 to 150 the CPU is idle.
- Result. Over the 400 ms hyperperiod (the least common multiple of 50 and 80), EDF misses no deadline (Figure 5.46).
EDF's superiority has a price. Because priorities are dynamic, deadlines have to be compared at every decision. More importantly, there is its behavior under overload. If total utilization temporarily exceeds 1, in RM only the low-priority tasks miss, and which ones miss is predictable. In EDF the misses can spread like a chain, and it is hard to say in advance which task will be affected.
An idea close to EDF is proportional-share real-time scheduling. A total of T shares is distributed among the applications; an application receiving N shares gets N/T of the CPU. Admission control rejects a request that would exceed the total. Linux's SCHED_DEADLINE policy (since version 3.14) combines EDF with constant-bandwidth-server (CBS) protection. Each task declares a runtime, a deadline, and a period. If a task tries to run longer than it declared, it is stopped until the next period; so a misbehaving task cannot break the guarantees of the others.
T1 (runtime 2, period 5) and T2 (runtime 4, period 7). What is the total utilization? Are the first deadlines met under RM and under EDF?
- U = 2/5 + 4/7 = 34/35 ≈ 0.97. The RM bound of 0.828 is exceeded; for EDF, U ≤ 1 suffices.
- RM. T1 runs 0–2, T2 2–5 (3 units). At t = 5 the new job of T1 preempts T2 by its static priority: T1 5–7. T2's deadline is 7 and it is 1 unit short; the deadline is missed.
- EDF. At t = 5 the new deadline of T1 is 10 and that of T2 is 7; T2 continues and finishes at 6. Over the 35-unit hyperperiod EDF misses no deadline.
5.7.4Code trace: the Liu–Layland test
RM's sufficiency test is a short function. The function returns three values: 1 (RM certainly suffices), 0 (the test cannot decide), and −1 (since utilization exceeds 1, no algorithm can schedule the set).
int rm_test(Task g[], int n) {
double U = 0;
for (int i = 0; i < n; i++)
U += (double) g[i].t / g[i].p;
double bound = n * (pow(2, 1.0/n) - 1);
if (U <= bound) return 1; /* enough */
if (U <= 1.0) return 0; /* unknown */
return -1; /* impossible */
}The loop adds up each task's utilization; the (double) cast prevents integer division. Then the bound is computed. The 1.0 in pow(2, 1.0/n) is important: had 1/n been written, integer division would give 0 for n ≥ 2 and the bound would come out as 0. The last two comparisons separate the three outcomes (Table 5.20).
| Set | Step | Added | U | bound | Turnaround |
|---|---|---|---|---|---|
| T1 (20, 5), T2 (50, 10), T3 (100, 30) | i = 0 | 5 / 20 = 0,25 | 0,25 | ||
| i = 1 | 10 / 50 = 0,2 | 0,45 | |||
| i = 2 | 30 / 100 = 0,3 | 0,75 | |||
| bound | 0,75 | 3(21/3 − 1) = 0,7798 | 1 | ||
| P1 (50, 25), P2 (80, 35) | i = 0 | 25 / 50 = 0,5 | 0,5 | ||
| i = 1 | 35 / 80 = 0,4375 | 0,9375 | |||
| bound | 0,9375 | 0,8284 | 0 |
In the first set, 0.75 ≤ 0.7798, so the function returns 1 and RM meets all deadlines. The second set is the one in Example 5.17. The utilization exceeds the bound but is below 1; the function returns 0. In this set RM really does miss a deadline, while EDF meets them. A result of 0 does not mean "RM fails": the set P1 (p = 50, t = 25) and P2 (p = 100, t = 50) has a utilization of 0.5 + 0.5 = 1 > 0.828 and the test gives 0, but because the periods are multiples of one another, RM meets all the deadlines (P1 0–25, P2 25–50, P1 50–75, P2 75–100). Another set that slightly exceeds the bound may also be schedulable with RM; only the schedule itself shows this. The function's time is O(n).
5.7.5Code trace: the EDF scheduler
EDF's decision rule can be applied at every time step. The following program schedules three periodic tasks for 12 ms, making a decision every millisecond.
/* A(P=3,C=1) B(P=4,C=1) C(P=6,C=2) */
for (int t = 0; t < 12; t++) {
for (int i = 0; i < n; i++)
if (t % P[i] == 0) { /* new job */
left[i] = C[i];
due[i] = t + P[i];
}
int s = -1;
for (int i = 0; i < n; i++)
if (left[i] > 0 &&
(s < 0 || due[i] < due[s]))
s = i;
if (s >= 0) left[s]--; /* 1 ms */
}P[i] is the period, C[i] the run time, left[i] the remaining time of the current job, and due[i] the deadline of the current job. At the start of every millisecond the jobs of tasks whose period begins are renewed: the remaining time is set to C[i] and the deadline to t + P[i]. The second loop picks, among the tasks that still have work, the one with the smallest deadline. Because the comparison is strictly less than (<), in a tie the first task in the array wins. The chosen task's remaining time drops by 1. If there is no work at all, s stays −1 and the CPU is idle for that millisecond.
The tasks are A (P = 3, C = 1), B (P = 4, C = 1), and C (P = 6, C = 2). The total utilization is 1/3 + 1/4 + 2/6 = 11/12 ≈ 0.917 ≤ 1. Since the least common multiple of the periods is 12, a 12 ms window shows the whole pattern (Table 5.21; Figure 5.47).
t | New job | Ready (deadline) | Running |
|---|---|---|---|
| 0 | A, B, C | A 3, B 4, C 6 | A |
| 1 | — | B 4, C 6 | B |
| 2 | — | C 6 | C |
| 3 | A | A 6, C 6 | A (first in a tie) |
| 4 | B | B 8, C 6 | C |
| 5 | — | B 8 | B |
| 6 | A, C | A 9, C 12 | A |
| 7 | — | C 12 | C |
| 8 | B | B 12, C 12 | B (first in a tie) |
| 9 | A | A 12, C 12 | A (first in a tie) |
| 10 | — | C 12 | C |
| 11 | — | none | empty |
In 12 ms, 11 ms of work is done and 1 ms of slack remains; that is 1 − 11/12. No job misses its deadline. The moment t = 4 separates EDF from RM: B's period is shorter than C's, and under RM B would run. EDF instead looks at the deadlines: C's job must finish by 6 and B's by 8; C is chosen. This set is also scheduled without misses under RM, but because its utilization (0.917) exceeds the three-task Liu–Layland bound (0.780), only the schedule itself can show RM's success.
The program's time is O(n) per step. Real EDF implementations do not decide every millisecond; they decide only when a job arrives or finishes, and keep the ready jobs in a priority queue ordered by deadline. Each decision then takes O(log n).
5.7.6POSIX real-time scheduling
POSIX's real-time extension (POSIX.1b) makes it possible to assign scheduling policies to threads. Table 5.22 summarizes the policies available on Linux.
| Policy | Behavior |
|---|---|
SCHED_FIFO | Fixed priority (1–99), no time slice; the thread runs until it blocks or yields the CPU. |
SCHED_RR | Same as SCHED_FIFO, but a time slice is applied among equal priorities. |
SCHED_OTHER | The default time-sharing policy (EEVDF on Linux); also SCHED_BATCH and SCHED_IDLE. |
SCHED_DEADLINE | Linux only: EDF with runtime, deadline, and period. |
pthread_attr_t attr;
struct sched_param sp;
int policy;
pthread_attr_init(&attr);
pthread_attr_getschedpolicy(&attr, &policy);
/* policy is ignored unless inheritance is off */
pthread_attr_setinheritsched(&attr,
PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
sp.sched_priority = 50; /* 1..99 */
pthread_attr_setschedparam(&attr, &sp);
pthread_create(&tid, &attr, runner, NULL);The program first prepares the attribute object and reads the default policy. Then comes an important line: inheritance is turned off with pthread_attr_setinheritsched. By default a new thread inherits its policy from the thread that creates it; if inheritance is not turned off, the policy set in the attribute is silently ignored. Then the policy is set to SCHED_FIFO, the priority to 50, and the thread is created.
Real-time policies require privilege: on Linux the CAP_SYS_NICE capability is needed; in an unprivileged process pthread_create returns EPERM. In the shell the same thing is done with the command chrt -f 50 ./prog. A real-time thread that enters an infinite loop can lock up the system. As a safeguard Linux by default gives real-time jobs at most 0.95 seconds of every second; the remaining 0.05 seconds is left to normal processes. This limit can be changed with the sched_rt_runtime_us setting. One detail in the function names is also often misspelled: the names are pthread_attr_getschedpolicy and pthread_attr_setschedpolicy; there is no underscore between "sched" and "policy."
5.8Operating-system examples
Real schedulers are combinations of the ideas in this chapter. Linux uses priority queues for real-time jobs and proportional share for normal jobs. Windows works with dynamic priorities that resemble an MLFQ.
5.8.1Linux scheduling classes
The Linux scheduler is modular: each task belongs to a scheduling class, and the classes are consulted in a fixed priority order. The scheduler first asks the top class "do you have a task to run?"; if not, it moves to the one below. While the upper class has a ready task, those below never run (Table 5.23).
| Class | Policies | Selection |
|---|---|---|
stop | — (internal to the kernel) | CPU stop, task migration; preempts everything |
deadline | SCHED_DEADLINE | EDF + CBS |
rt | SCHED_FIFO, SCHED_RR | array of 100 priority levels and a bitmap, O(1) selection |
fair | SCHED_NORMAL, SCHED_BATCH, SCHED_IDLE | CFS (2.6.23–6.5), EEVDF (6.6 and later) |
ext | SCHED_EXT | Scheduler written in BPF (sched_ext, 6.12 and later) |
idle | — | idle loop when there is no work |
This order directly determines which of three ready tasks on the same CPU runs first. A SCHED_DEADLINE task comes before a SCHED_FIFO task at priority 50. That in turn comes before a normal task with nice value −20. The nice value affects only the share within the fair class; it cannot put a normal task ahead of a real-time task (Figure 5.48).
Inside the kernel a single priority scale is used, and a small number means high priority. The range 0–99 belongs to real-time tasks; the rt_priority (1–99) given by the user is converted to the kernel priority as 99 − rt_priority. The range 100–139 belongs to normal tasks: nice −20 → 100, nice 0 → 120, nice 19 → 139. The default slice of the SCHED_RR policy is 100 ms.
5.8.2CFS: virtual runtime
From Linux 2.6.23 to 6.5, normal tasks were scheduled by the Completely Fair Scheduler (CFS). CFS's goal is to imitate an ideal multitasking processor. On the ideal processor, with n tasks, each would run at the same time at 1/n of the CPU's speed. Because a real CPU can run only one task at a time, CFS tracks how far each task has fallen behind this ideal and runs the one that has fallen furthest behind.
The virtual runtime (vruntime) is the CPU time a task has received, scaled by its weight. When a task runs for Δ,
vruntime += Δ × 1024 / weight
CFS always runs the task with the smallest vruntime.
The weight comes from the nice value. The weight of nice 0 is 1024; each nice step changes the weight by about a factor of 1.25. The weight of nice 5 is 335 and that of nice −5 is 3121. A factor of about 1.25 corresponds to a difference of roughly 10% in CPU share between two CPU-bound tasks. For a nice 0 task, vruntime grows at the same rate as real time. A task with a smaller weight (larger nice) has its vruntime grow faster; so it is chosen less often.
Consider two CPU-bound tasks: A with nice 0 (weight 1024), B with nice 5 (weight 335). In the long run both vruntimes must advance at the same rate; this requires their shares to be proportional to their weights. A gets 1024 / (1024 + 335) = 1024 / 1359 ≈ 75% and B ≈ 25%; the ratio is about 3 : 1. When B runs 10 ms its vruntime grows by 10 × 1024 / 335 ≈ 30.6 ms.
I/O-bound tasks are rewarded automatically in this scheme. A sleeping task uses no CPU, so its vruntime does not grow; when it wakes up it has fallen behind the CPU-bound tasks and immediately moves to the front. It is also undesirable for a task that has slept for a long time to monopolize the CPU when it returns. CFS therefore pulls the woken task's vruntime to slightly behind the minimum vruntime; the advantage given to a task that has fallen behind is limited (Figure 5.49).
Ready tasks are kept in a red-black tree keyed by vruntime. Insertion and deletion take O(log n). The leftmost node, that is, the task with the smallest vruntime, is also cached in a pointer; so selection is O(1).
5.8.3Code trace: vruntime
The following code shows CFS's selection rule as a simplified tick handler. At each tick the leftmost task is run for 3 ms (3000 µs), its vruntime is updated, and it is reinserted into the tree.
#define DELTA 3000 /* 3 ms, in µs */
/* nice 0 → 1024, nice 5 → 335 */
void tick(void) {
Task *g = leftmost(); /* leftmost */
run(g, DELTA);
g->vruntime += DELTA * 1024 / g->weight;
tree_insert(g); /* re-sort */
}leftmost() returns the task with the smallest vruntime; in a tie the task inserted into the tree first is on the left. run runs the task for 3 ms. The update line uses integer arithmetic: for A, 3000 × 1024 / 1024 = 3000; for B, 3,072,000 / 335 = 9170 (the remainder is discarded). The last line puts the task back into its place in the tree according to its new vruntime. Initially both tasks' vruntime is 0 (Table 5.24).
| Tick | A.vruntime | B.vruntime | Chosen | Added |
|---|---|---|---|---|
| 1 | 0 | 0 | A (first inserted in a tie) | 3000 |
| 2 | 3.000 | 0 | B | 9170 |
| 3 | 3.000 | 9.170 | A | 3000 |
| 4 | 6.000 | 9.170 | A | 3000 |
| 5 | 9.000 | 9.170 | A | 3000 |
| 6 | 12.000 | 9.170 | B | 9170 |
| 7 | 12.000 | 18.340 | A | 3000 |
| 8 | 15.000 | 18.340 | A | 3000 |
| 9 | 18.000 | 18.340 | A | 3000 |
| end | 21.000 | 18.340 |
In 9 ticks A ran 7 times and B 2 times. In the short run the ratio is 7 : 2; in the long run it approaches the weight ratio 1024 : 335, that is, ≈ 75% – 25%. When the same rule is run for 10,000 ticks, A gets 7535 and B 2465 ticks. CFS has no fixed time slice; the share comes directly from the weight. Real CFS measures time in nanoseconds and, instead of fixed ticks, divides a "scheduling latency" window among the tasks according to their weights; but the selection rule is the same. This rule is the same idea as the pass counter of stride scheduling: vruntime is the pass, and 1024 / weight is the stride.
5.8.4EEVDF
CFS provided fair share well, but it needed many heuristic tunings for latency-sensitive tasks. In Linux 6.6 the scheduler for normal tasks was replaced by EEVDF. EEVDF (Earliest Eligible Virtual Deadline First) is an algorithm proposed by Stoica and Abdel-Wahab in 1995. It replaces the heuristics in CFS with two clear criteria: eligibility and virtual deadline.
In EEVDF, V is the (weighted) average of the tasks' virtual runtimes. A task's lag shows how far behind its share it is. A task is eligible if it is behind its share or exactly at it: lag ≥ 0, that is, v ≤ V. A task's virtual deadline is vd = v + slice / weight. Among the eligible tasks, the one with the earliest vd runs.
The eligibility condition governs fairness, and the deadline governs latency. A task that has received more than its share (v > V) is not eligible and waits; so no one can exceed its share. Among eligible tasks, a task that asks for a short slice has a nearer deadline and runs first. A task asking for a short slice runs more often but for shorter periods; its share does not change in the long run.
Three tasks of equal weight: A (v = 12, slice 3), B (v = 12, slice 1), C (v = 15, slice 3). Since the weights are equal, vd = v + slice is used. Let us trace five selections.
- V = (12 + 12 + 15) / 3 = 13. C is ahead (v = 15 > V): not eligible. A and B are eligible; vd is 15 for A and 13 for B → B is chosen.
- B ran 1 ms: v = 13, new vd = 14. V = 13.33; A and B are eligible; the earliest vd is B's (14) → B.
- B advanced to 14; V = 13.67. B and C are ahead of the average; only A is eligible → A runs its 3 ms slice.
- A: v = 15, new vd = 18. V = 14.67; only B (v = 14) is eligible → B.
- B: v = 15, vd = 16. V = 15; all three are eligible. vd is A 18, B 16, C 18 → B (Figure 5.50).
In the example B, which asks for a short slice, got four of the five selections, but each time it ran only 1 ms. A ran once, for 3 ms. The eligibility condition limits B's running ahead: when B moved ahead of the average (the third step) it lost its eligibility and gave way to A. Since Linux 6.12 a latency-sensitive task can ask for a short slice for itself with the sched_setattr() call. The weights are computed from nice in the same way as in CFS.
5.8.5Windows priorities
Windows uses a preemptive, priority-based scheduler. Of the ready threads, the one with the highest priority runs. It stays on the CPU until it blocks, its slice ends, or a higher-priority thread becomes ready. There are 32 priority levels, and a large number means high priority. Levels 1–15 are the variable class and 16–31 the real-time class. Level 0 is reserved for the system thread that zeroes free memory pages (the zero-page thread). Each level has its own queue; if there is no ready thread, the idle thread runs.
A thread's numeric priority comes from two pieces of information: its process's priority class and the thread's relative priority within that class (Table 5.25).
| Relative priority | REALTIME | HIGH | ABOVE_NORMAL | NORMAL | BELOW_NORMAL | IDLE |
|---|---|---|---|---|---|---|
| time-critical | 31 | 15 | 15 | 15 | 15 | 15 |
| highest | 26 | 15 | 12 | 10 | 8 | 6 |
| above normal | 25 | 14 | 11 | 9 | 7 | 5 |
| normal | 24 | 13 | 10 | 8 | 6 | 4 |
| below normal | 23 | 12 | 9 | 7 | 5 | 3 |
| lowest | 22 | 11 | 8 | 6 | 4 | 2 |
| idle | 16 | 1 | 1 | 1 | 1 | 1 |
The priority of threads in the variable class changes over time; this is Windows's counterpart of MLFQ. When an I/O completes, the thread's priority is temporarily boosted. The boost is larger for interactive devices such as the keyboard and mouse than for disk I/O. Threads of the foreground window and threads woken by GUI events also get a boost. A boosted priority decreases by 1 each slice and returns to the base, and never exceeds 15. There is a safeguard against starvation as well: a thread that has been ready for about 4 seconds without running has its priority raised to 15 for one slice. The slice is about 2 clock ticks on client versions and 12 on server versions; on a server the long slice reduces context switches and increases throughput (Figure 5.51).
Believing that a task with nice −20 on Linux will get ahead of a SCHED_FIFO task. nice changes only the weight within the fair class; while a ready task exists in the real-time class, no task in the fair class runs. On Windows, too, dynamic boosts are limited to the variable class: a thread cannot be boosted past 15 into the real-time class.
5.9Evaluating algorithms
Among so many algorithms, which should be chosen for a particular system? First the criterion is set: for example, "the longest response time must not exceed 300 ms, and subject to that, throughput should be maximized." Then the algorithms are evaluated against this criterion. There are four ways of evaluating.
5.9.1Four methods and Little's law
Deterministic modeling. For a particular workload given in advance, each algorithm's result is computed. All the Gantt charts in this chapter are deterministic modeling. The method is exact and simple, and the results are comparable numbers. Its weakness is that the result is valid only for that input: on another set the ranking may change.
Queueing models. In a real system the workload changes every day, but the distributions of the processes' arrival and service times can be measured. Queueing theory computes quantities such as average queue length, average waiting time, and utilization from these distributions. The most basic tool is Little's law.
In a system in steady state, the average number of processes n is the product of the average arrival rate λ and the average time W a process spends in the system:
n = λ × W
In steady state the number of processes entering the system equals the number leaving. If λ processes arrive per second and each stays W seconds, there are on average λ × W processes inside at any moment. If 7 processes arrive per second and each stays 2 seconds on average, there are 14 processes in the system on average. The law is independent of the arrival and service distributions; that is why it is used in so wide an area. If any two of the quantities are known, the third can be found. If 6 requests per second arrive at a server and the system holds 18 requests on average, each request stays W = 18 / 6 = 3 seconds on average (Figure 5.52).
The limit of queueing models is the assumptions made so that they can be solved mathematically. Assumptions such as arrivals following a Poisson distribution do not hold exactly for real workloads; and the model of a complex algorithm often cannot be solved.
Simulation. A programmed model of the system is built: the clock, the queues, the scheduler. The model is run with randomly generated data or with trace data recorded from a real system. Because trace data preserves the order of real events, the results are close to reality. The price is time: a detailed simulation can take hours, and the recordings take up a lot of space.
Implementation. The most exact way is to put the algorithm into a real kernel and try it. This used to be expensive: the kernel had to be modified, compiled, and rebooted. Today Linux's sched_ext infrastructure allows loading schedulers written in BPF without recompiling the kernel; large companies compare different schedulers in production with A/B tests. Implementation has a subtle problem as well: users and programmers adapt to the algorithm. Users pressing Enter in CTSS were the first example of this; the measured behavior can change because of the algorithm.
5.9.2Comparison on the common set
The results of all the algorithms examined on the common set are brought together in Table 5.26 (Figure 5.53).
| Algorithm | Waiting | Turnaround | Response | Switches |
|---|---|---|---|---|
| FCFS | 8,75 | 15,25 | 8,75 | 3 |
| SJF | 7,75 | 14,25 | 7,75 | 3 |
| SRTF | 6,5 | 13 | 4,25 | 4 |
| Priority (P) | 10,75 | 17,25 | 8,5 | 4 |
| RR q = 2 | 12,75 | 19,25 | 2 | 12 |
| RR q = 5 | 11 | 17,5 | 5,5 | 5 |
SRTF is best in average waiting (6.5), but it requires the lengths to be known. RR with q = 2 is best in response (2), but it makes the most switches and is worst in waiting. Preemptive priority optimizes importance, not waiting time; its average is worse than FCFS, but the most important process, P3, never waits. There is no single "best" algorithm. The choice depends on the goal: response, throughput, fairness, or deadlines. This is why real systems use hybrid structures such as MLFQ or EEVDF: while putting short jobs first, they try not to starve anyone and to keep response bounded.
5.9.3Three exercises on turnaround, response, and fairness
A, B, and C all arrive at t = 0 and each needs 5 ms of CPU. What are the average turnaround and average response times under SJF and under RR (q = 1)?
- SJF. Since the lengths are equal, SJF is the same as FCFS here. Completion times are 5, 10, 15; the average turnaround is 10 ms. Response is (0 + 5 + 10) / 3 = 5 ms.
- RR (q = 1). A, B, and C swap places every millisecond; the last round is at 12–15 and the completion times are 13, 14, 15. The average turnaround is 14 ms and the response is (0 + 1 + 2) / 3 = 1 ms.
A (arrival 0, length 100), B (10, 10), C (10, 10). What are the average turnaround and response times under nonpreemptive SJF and under STCF (SRTF)?
- SJF. At t = 0 only A is present and it cannot be preempted: A 0–100, B 100–110, C 110–120. Turnaround times are 100, 100, 110; the average is 310 / 3 ≈ 103.3 ms. Response times are 0, 90, 100; the average is ≈ 63.3 ms.
- STCF. At t = 10 B arrives; its length is 10 and A's remainder is 90, so A is preempted. B 10–20, C 20–30, A 30–120. Turnaround times are 120, 10, 20; the average is 150 / 3 = 50 ms. Response times are 0, 0, 10; the average is ≈ 3.3 ms.
Preemption removed the short jobs' waiting behind the long job, that is, the convoy effect.
Let the unfairness measure U be the ratio of the completion time of the job that finishes first to that of the job that finishes second. Two jobs with equal tickets each want L slices. What is U under RR? How does U change as L grows under lottery scheduling?
- RR (and stride). The jobs run alternately; one finishes at 2L − 1 and the other at 2L. U = (2L − 1) / 2L; for L = 10 it is 19 / 20 = 0.95. As the job gets longer U approaches 1.
- Lottery. In each slice the two jobs win with equal probability; when one reaches L wins it finishes, and the other runs its remaining slices alone and finishes at 2L. If the expected value of the first job's completion time is computed, the expected U comes out as ≈ 0.82 for L = 10 and ≈ 0.94 for L = 100.
Lottery creates a marked unfairness for short jobs; as the job gets longer, the effect of chance diminishes and U approaches 1. Deterministic stride does not have this problem.
5.10Summary
- The short-term scheduler selects a process from the ready queue when the CPU becomes free; the dispatcher switches context, switches to user mode, and jumps into the program. The time in between is the dispatch latency.
- Processes alternate between CPU and I/O bursts. Most bursts are short; not keeping I/O-bound processes waiting keeps the devices busy. Treating each burst as a separate job overlaps I/O with computation.
- A decision is made in four situations: running → waiting, running → ready, waiting → ready, and termination. A nonpreemptive scheduler decides only in situations 1 and 4; a preemptive one decides in all four.
- Criteria: CPU utilization and throughput should be large; turnaround (C − A), waiting (turnaround − CPU), and response (F − A) times should be small. The scheduler affects only the waiting time.
- FCFS is simple and starvation-free, but it is sensitive to arrival order and causes the convoy effect. SJF minimizes the average waiting time when all jobs are ready at the same time; the next burst is predicted with the exponential average: τn+1 = α tn + (1 − α) τn. SRTF is the preemptive version and gives the lowest waiting time (6.5 ms) on the common set.
- In priority scheduling, starvation is solved with aging and priority inversion with priority inheritance.
- RR gives each process at most q of time; when n ready processes is constant and the switching cost is neglected, no process waits longer than (n − 1) · q. As q shrinks, response improves and switches increase; if slices are fully used, the overhead fraction is s / (q + s). When q exceeds the longest burst, RR becomes FCFS.
- MLQ divides processes into permanent classes. MLFQ moves them according to behavior: a new job starts at the top, a job that uses up its allotment at a level moves down, and at regular intervals everyone goes back to the top.
- Proportional share: guaranteed and fair-share scheduling (Linux cgroup
cpu.weight), probabilistic lottery, and deterministic stride (stride = constant / tickets, the smallest pass runs). - On multiprocessors most modern general-purpose systems use SMP and per-core queues; imbalance is corrected by push and pull migration, and migration in turn breaks affinity. SMT cores, NUMA, and heterogeneous cores complicate the decision.
- In real time, RM has static priorities; ΣU ≤ n(21/n − 1) is a sufficient condition. EDF is dynamic; ΣU ≤ 1 is both sufficient and necessary. Linux
SCHED_DEADLINEcombines EDF with CBS. - The Linux classes are consulted in order: stop, deadline, rt, fair, ext, idle. CFS chooses the smallest
vruntime(vruntime += Δ × 1024 / weight); EEVDF chooses the earliest virtual deadline among the eligible tasks. Windows uses 32 priority levels and dynamic boosts. - Evaluation methods: deterministic modeling, queueing models (Little's law n = λ × W), simulation, and implementation.
5.11Key terms
- scheduler
- ready queue
- CPU burst
- preemptive / nonpreemptive scheduling
- dispatcher
- context switch
- throughput
- turnaround time
- response time
- convoy effect
- shortest-job-first
- exponential average
- starvation
- aging
- priority inversion
- time slice (quantum)
- multilevel feedback queue
- lottery scheduling
- load balancing
- processor affinity
- rate-monotonic scheduling
- earliest deadline first
5.12Test Yourself
P1 (arrival 0, CPU 7), P2 (1, 3), P3 (3, 2), P4 (6, 1). What are the average waiting times under nonpreemptive SJF and under SRTF?
Answer
SJF: P1 runs 0–7 uninterrupted; at t = 7 the ready processes are P2 (3), P3 (2), P4 (1); the order is P4 7–8, P3 8–10, P2 10–13. Waiting times are 0, 9, 5, 1; the average is 15 / 4 = 3.75 ms. SRTF: at t = 1, P2 (3) < P1's remainder of 6, so P1 is preempted; P2 1–4, P3 4–6, P4 6–7, P1 7–13. Waiting times are 6, 0, 1, 0; the average is 7 / 4 = 1.75 ms.
A (arrival 0, CPU 5), B (1, 4), C (2, 3); RR, q = 2. A newly arrived process enters the queue before the process whose slice has ended. What are the Gantt chart and the average waiting time?
Answer
A 0–2, B 2–4, C 4–6, A 6–8, B 8–10 (finishes), C 10–11 (finishes), A 11–12 (finishes). Completion times are A 12, B 10, C 11. Waiting times are A 12 − 0 − 5 = 7, B 10 − 1 − 4 = 5, C 11 − 2 − 3 = 6; the average is 6 ms. The average response is (0 + 1 + 2) / 3 = 1 ms.
α = 0.25 and τ0 = 10 ms. The measured bursts are 4, 4, and 16 ms. What is τ3? What is the effect of choosing α = 0.25 on this sequence?
Answer
τ1 = 0.25 · 4 + 0.75 · 10 = 8.5; τ2 = 0.25 · 4 + 0.75 · 8.5 = 7.375; τ3 = 0.25 · 16 + 0.75 · 7.375 ≈ 9.53 ms. A small α gives a lot of weight to the past: after two short bursts the prediction is still above 7, and it catches up slowly with the burst that jumps to 16.
MLFQ: Q0 (q = 3), Q1 (q = 6), Q2 (FCFS). A (arrival 0, CPU 12), B (2, 2), C (5, 6). When do the jobs finish?
Answer
A uses up its slice at 0–3 and drops to Q1. B finishes in Q0 at 3–5. C, arriving at t = 5, uses up its Q0 slice at 5–8 and drops to Q1. A runs in Q1 at 8–14, uses up its slice, and drops to Q2 (3 left). C finishes in Q1 at 14–17. A finishes in Q2 at 17–20. Completion times are B 5, C 17, A 20.
A system uses a nonpreemptive scheduler. The running process starts a file read, and at that moment a disk read that was started earlier completes. In which of these two events is the scheduler invoked?
Answer
Only in the first. When the running process requests I/O it moves to the waiting state and the CPU becomes free (running → waiting); a choice is mandatory. The completion of the disk read moves a process from waiting to ready; the nonpreemptive scheduler does not stop the running process, and the woken process joins the ready queue.
In stride scheduling A has 40, B has 20, and C has 80 tickets; stride = 10,000 / tickets. In a tie the order is A, B, C. What is the order of execution in the first 7 slices?
Answer
The strides are A 250, B 500, C 125. The order is A, B, C, C, A, C, C. A gets 2, B 1, and C 4 slices; the ratio is 2 : 1 : 4 = 40 : 20 : 80. At the end of the seventh slice all three pass values are 500.
Three periodic tasks: T1 (p = 4, t = 1), T2 (p = 5, t = 2), T3 (p = 10, t = 3). What does the Liu–Layland test say? Does RM really miss a deadline?
Answer
U = 0.25 + 0.4 + 0.3 = 0.95. For three tasks the bound is ≈ 0.780; the test cannot decide (the result is 0). If the RM schedule is drawn over the 20 ms hyperperiod (T1 0–1, T2 1–3, T3 3–4, T1 4–5, T2 5–7, T3 7–8, T1 8–9, T3 9–10, …), no deadline is missed. The test is a sufficient condition, not a necessary one.
On Linux CFS there are two CPU-bound tasks: A with nice −5 (weight 3121) and B with nice 0 (weight 1024). What are their approximate shares? Whose vruntime grows faster?
Answer
A gets 3121 / 4145 ≈ 75% and B ≈ 25%. Since vruntime += Δ × 1024 / weight, B's vruntime grows about 3 times faster for the same running time; B is chosen less often.
Why is a single common queue not used in a system with per-core queues? What is the price of per-core queues?
Answer
In a common queue every access needs a lock; lock contention grows with the number of cores, and because a job may run on a different core each time, its cache stays cold. With per-core queues no lock is needed and affinity is preserved; but the queues may become unbalanced and load balancing (push and pull migration) is needed. A migrated job finds its cache cold on the new core.
In RR, q = 9 ms and each context switch takes 1 ms. The processes use their slices to the end. What percentage of CPU time goes to switching? What changes compared with q = 4?
Answer
1 / (9 + 1) = 10%. At q = 4 the overhead was 1 / 5 = 20%. As the slice grows the overhead falls, but each process in the queue waits longer for its next slice and response time gets worse.
5.13Further reading
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters "Scheduling: Introduction," "The Multi-Level Feedback Queue," "Lottery Scheduling," and "Multiprocessor Scheduling": builds the MLFQ rules starting from the problems, and presents lottery and stride scheduling with short C code; free at ostep.org.
- C. L. Liu and J. W. Layland, "Scheduling Algorithms for Multiprogramming in a Hard-Real-Time Environment," Journal of the ACM, 20(1), 1973: the foundational paper that proves the optimality and the utilization bound of RM and the ΣU ≤ 1 condition of EDF.
- Linux kernel documentation,
Documentation/scheduler/sched-eevdf.rstandsched-deadline.rst: describe EEVDF's eligibility and virtual-deadline rules and the admission control ofSCHED_DEADLINEin the kernel's own documentation. - P. Yosifovich et al., Windows Internals, 7th ed., Part 1, Chapter 4: gives a detailed account of Windows's priority levels, slice computation, dynamic boosts, and multiprocessor thread selection.
5.14References
- A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Chapter 5: CPU Scheduling.
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Section 2.4: Scheduling.
- R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — Chapters 7–10: Scheduling, MLFQ, Lottery, Multiprocessor.
- P. Yosifovich, A. Ionescu, M. Russinovich, D. Solomon, Windows Internals, 7th ed., Part 1, 2017 — Chapter 4: Thread scheduling.
- Linux kernel documentation:
sched-eevdf.rst,sched-design-CFS.rst,sched-deadline.rst,sched-ext.rst; thesched(7)manual page. - I. Stoica, H. Abdel-Wahab, “Earliest Eligible Virtual Deadline First”, 1995.
- C. L. Liu, J. W. Layland, "Scheduling Algorithms for Multiprogramming in a Hard-Real-Time Environment," Journal of the ACM, 20(1), 1973, pp. 46–61.
- C. A. Waldspurger, W. E. Weihl, “Lottery Scheduling: Flexible Proportional-Share Resource Management”, OSDI, 1994.