Lesson 10 · Processes, threads, and CPU scheduling

Multilevel Feedback Queue Scheduling

Run several round-robin queues at different priorities and let each process's behaviour decide where it lives: use a whole quantum and you sink, give up the CPU early and you stay on top.

Multilevel Feedback Queue Scheduling concept diagramThree stacked ready queues. New processes enter the top queue; a process that uses its whole quantum moves down one level; the CPU serves the highest non-empty queue; a periodic priority boost returns every process to the top.Q0 · round robin, q = 8 mshighest priorityQ1 · round robin, q = 16 msQ2 · FCFSlowest prioritynew processused whole quantum → downused whole quantum → downCPUtop non-emptyqueue firstboostevery Sa process that blocks before its quantum ends keeps its level — interactive jobs stay on top
1

Queues That Learn From Behaviour

  1. Queues – several ready queues, Q0 (highest priority) down to Qn (lowest).
  2. Quanta – each queue has its own time quantum, usually growing towards the bottom; the last is often FCFS.
  3. Feedback – a process moves between queues based on how it used the CPU.
  4. Selection – the CPU always serves the highest non-empty queue.
  5. Goal – fast response for interactive jobs and good turnaround for short ones, with no advance knowledge of burst lengths.

Multilevel feedback queue (MLFQ) scheduling is the CPU scheduling algorithm behind most general-purpose operating systems, from the original CTSS to the schedulers in BSD, Solaris and Windows. It keeps several queues at different priorities and moves processes between them according to their observed behaviour — that movement is the feedback.

The problem it solves is that the best algorithm for average turnaround, SJF, needs to know how long each burst will be, which the OS cannot know. MLFQ scheduling learns it instead. A process that keeps using its full quantum is probably long and CPU-bound, so it drops to a lower queue; a process that blocks for I/O quickly is probably interactive, so it stays high.

  • Also written MFQ; the queues are sometimes called priority levels
  • What it learns is recent behaviour, so a job that changes phase gets re-judged after the next boost
2

The MLFQ Rules

  1. Rule 1 – if priority(A) > priority(B), A runs.
  2. Rule 2 – if priority(A) = priority(B), they share the CPU round robin with that queue's quantum.
  3. Rule 3 – a new process enters the highest-priority queue.
  4. Rule 4 – once a process has used its whole time allotment at a level, it moves down one level, however many times it gave up the CPU along the way.
  5. Rule 5 – every S time units, move every process back to the top queue (the priority boost).

Rules 1–3 give the basic behaviour: new work is assumed to be short, and it proves otherwise by using up its quantum. A process that arrives in a higher queue preempts a process running from a lower one, as D does to A in the tracer.

Rule 4 closes a loophole. If demotion only happened when a process used a full quantum in one go, a program could give up the CPU just before its quantum ended — by doing a tiny I/O — and stay in the top queue forever while using almost all of the CPU. Counting total time used at a level, across preemptions and blocks, defeats that.

Rule 5 answers two other problems at once: long jobs starving at the bottom while short jobs keep arriving, and a job whose behaviour changes, such as a batch program that becomes interactive, being stuck at a low level.

  • These five rules follow Arpaci-Dusseau's OSTEP; Silberschatz's textbook version demotes after one full quantum, which is how exam problems are solved
  • No formula gives the boost interval S; it is tuned by hand for the workload
3

Parameters That Define an MLFQ Scheduler

  1. Number of queues – 3 in textbook problems; 60 or more in real systems.
  2. Algorithm inside each queue – round robin, often FCFS at the bottom.
  3. When to demote – after a full quantum, or after the level's total allotment.
  4. When to promote – a periodic boost, or aging by waiting time.
  5. Entry queue – usually the top one, so new work is assumed short until it proves otherwise.

MLFQ is a family of schedulers rather than one algorithm, and an exam question on it will usually give you these parameters. Silberschatz uses this list as the definition of a multilevel feedback queue scheduler.

Quanta normally grow towards the bottom: the top queues hold interactive jobs that need a quick turn, while the bottom ones hold long jobs that gain more from fewer switches than from fast response.

  • The promotion rule is what separates a fair MLFQ from one that starves long jobs
  • Change one parameter and the others usually need retuning
Key reference

Terms, operations, and practical uses

Terms to know

  • DemotionMoving a process to a lower-priority queue after it uses its allotment.
  • Priority boostPeriodically moving every process back to the top queue.
  • AllotmentTotal CPU time a process may use at one level before it is demoted.
  • CPU-bound vs I/O-boundLong bursts versus short bursts between I/O waits — what MLFQ infers.
Implementation

Code in Python, C++ and Java

from collections import deque

QUANTA = [2, 4, None]  # None = FCFS, run to completion


def mlfq(processes):
    # processes: (name, arrival, burst), sorted by arrival.
    queues = [deque() for _ in QUANTA]
    remaining = {name: burst for name, _, burst in processes}
    used = {name: 0 for name, _, _ in processes}  # time used at the current level
    level = {name: 0 for name, _, _ in processes}
    gantt, finish = [], {}
    clock, nxt, current = 0, 0, None

    while len(finish) < len(processes):
        while nxt < len(processes) and processes[nxt][1] <= clock:
            queues[0].append(processes[nxt][0])  # every new process starts on top
            nxt += 1
        top = next((q for q in range(len(queues)) if queues[q]), None)
        # A process waiting in a higher queue preempts the running one.
        if current is not None and top is not None and top < level[current]:
            queues[level[current]].append(current)
            current = None
        if current is None:
            if top is None:
                clock += 1
                continue
            current = queues[top].popleft()

        name = current
        last = gantt[-1] if gantt else None
        if last and last[0] == name and last[2] == clock and last[3] == level[name]:
            gantt[-1][2] += 1
        else:
            gantt.append([name, clock, clock + 1, level[name]])
        clock += 1
        remaining[name] -= 1
        used[name] += 1

        quantum = QUANTA[level[name]]
        if remaining[name] == 0:
            finish[name] = clock
            current = None
        elif quantum is not None and used[name] == quantum:
            # Used its whole allotment at this level: demote it.
            level[name] += 1
            used[name] = 0
            queues[level[name]].append(name)
            current = None
    return gantt, finish


procs = [("A", 0, 9), ("B", 1, 2), ("C", 3, 5), ("D", 8, 1)]
gantt, finish = mlfq(procs)
print("Gantt:", " ".join(f"{n}[{s}-{e}]Q{q}" for n, s, e, q in gantt))
for name, arrival, burst in procs:
    tat = finish[name] - arrival
    print(f"{name}: completion {finish[name]:>2}  turnaround {tat:>2}  waiting {tat - burst:>2}")
#include <cstdio>
#include <deque>
#include <string>
#include <vector>
using namespace std;

struct Process {
    string name;
    int arrival, burst;
    int remaining = 0, used = 0, level = 0, finish = 0;
};

struct Slice {
    int proc, start, end, level;
};

int main() {
    const vector<int> quanta = {2, 4, 0};  // 0 = FCFS, run to completion
    vector<Process> procs = {{"A", 0, 9}, {"B", 1, 2}, {"C", 3, 5}, {"D", 8, 1}};
    for (Process& p : procs) p.remaining = p.burst;

    vector<deque<int>> queues(quanta.size());
    vector<Slice> gantt;
    size_t next = 0;
    int clock = 0, done = 0, current = -1;

    while (done < (int)procs.size()) {
        while (next < procs.size() && procs[next].arrival <= clock) {
            queues[0].push_back(next++);  // every new process starts on top
        }
        int top = -1;
        for (int q = 0; q < (int)queues.size() && top < 0; q++) {
            if (!queues[q].empty()) top = q;
        }
        // A process waiting in a higher queue preempts the running one.
        if (current >= 0 && top >= 0 && top < procs[current].level) {
            queues[procs[current].level].push_back(current);
            current = -1;
        }
        if (current < 0) {
            if (top < 0) {
                clock++;
                continue;
            }
            current = queues[top].front();
            queues[top].pop_front();
        }

        Process& p = procs[current];
        if (!gantt.empty() && gantt.back().proc == current && gantt.back().end == clock &&
            gantt.back().level == p.level) {
            gantt.back().end++;
        } else {
            gantt.push_back({current, clock, clock + 1, p.level});
        }
        clock++;
        p.remaining--;
        p.used++;

        int quantum = quanta[p.level];
        if (p.remaining == 0) {
            p.finish = clock;
            done++;
            current = -1;
        } else if (quantum > 0 && p.used == quantum) {
            // Used its whole allotment at this level: demote it.
            p.level++;
            p.used = 0;
            queues[p.level].push_back(current);
            current = -1;
        }
    }

    printf("Gantt:");
    for (const Slice& s : gantt) printf(" %s[%d-%d]Q%d", procs[s.proc].name.c_str(), s.start, s.end, s.level);
    printf("\n");
    for (const Process& p : procs) {
        int tat = p.finish - p.arrival;
        printf("%s: completion %2d  turnaround %2d  waiting %2d\n", p.name.c_str(), p.finish, tat, tat - p.burst);
    }
    return 0;
}
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class Main {
    static final int[] QUANTA = {2, 4, 0}; // 0 = FCFS, run to completion

    static class Process {
        final String name;
        final int arrival, burst;
        int remaining, used, level, finish;

        Process(String name, int arrival, int burst) {
            this.name = name;
            this.arrival = arrival;
            this.burst = burst;
            this.remaining = burst;
        }
    }

    record Slice(Process proc, int start, int end, int level) {}

    public static void main(String[] args) {
        Process[] procs = {
            new Process("A", 0, 9), new Process("B", 1, 2),
            new Process("C", 3, 5), new Process("D", 8, 1)
        };
        List<ArrayDeque<Process>> queues = new ArrayList<>();
        for (int q = 0; q < QUANTA.length; q++) queues.add(new ArrayDeque<>());
        List<Slice> gantt = new ArrayList<>();
        int next = 0, clock = 0, done = 0;
        Process current = null;

        while (done < procs.length) {
            while (next < procs.length && procs[next].arrival <= clock) {
                queues.get(0).add(procs[next++]); // every new process starts on top
            }
            int top = -1;
            for (int q = 0; q < QUANTA.length && top < 0; q++) {
                if (!queues.get(q).isEmpty()) top = q;
            }
            // A process waiting in a higher queue preempts the running one.
            if (current != null && top >= 0 && top < current.level) {
                queues.get(current.level).add(current);
                current = null;
            }
            if (current == null) {
                if (top < 0) {
                    clock++;
                    continue;
                }
                current = queues.get(top).poll();
            }

            Process p = current;
            Slice last = gantt.isEmpty() ? null : gantt.get(gantt.size() - 1);
            if (last != null && last.proc() == p && last.end() == clock && last.level() == p.level) {
                gantt.set(gantt.size() - 1, new Slice(p, last.start(), clock + 1, p.level));
            } else {
                gantt.add(new Slice(p, clock, clock + 1, p.level));
            }
            clock++;
            p.remaining--;
            p.used++;

            int quantum = QUANTA[p.level];
            if (p.remaining == 0) {
                p.finish = clock;
                done++;
                current = null;
            } else if (quantum > 0 && p.used == quantum) {
                // Used its whole allotment at this level: demote it.
                p.level++;
                p.used = 0;
                queues.get(p.level).add(p);
                current = null;
            }
        }

        StringBuilder line = new StringBuilder("Gantt:");
        for (Slice s : gantt) line.append(String.format(" %s[%d-%d]Q%d", s.proc().name, s.start(), s.end(), s.level()));
        System.out.println(line);
        for (Process p : procs) {
            int tat = p.finish - p.arrival;
            System.out.printf("%s: completion %2d  turnaround %2d  waiting %2d%n", p.name, p.finish, tat, tat - p.burst);
        }
    }
}
Watch it run

Step through it

Running on (arrival, burst): A (0,9) B (1,2) C (3,5) D (8,1)

Q0 · RR q = 2 · highestQ1 · RR q = 4Q2 · FCFS · lowestt = 0CPU idleGantt chart (level under each slice)0new → Q0; full quantum used → move down
Step 1

Three queues, three rules of thumb

Every new process starts in Q0, the highest priority. A process that uses up its whole quantum is treated as CPU-bound and demoted one level. Higher queues always run first, so short and interactive jobs stay on top.

Output
1 / 12
4

A Solved Example: Three Jobs, Three Levels

  1. Setup – Q0: round robin, q = 8 ms; Q1: round robin, q = 16 ms; Q2: FCFS.
  2. Jobs – P1 = 30 ms, P2 = 6 ms, P3 = 20 ms, all arriving at t = 0 into Q0.
  3. Q0 – P1 0–8 (22 left → Q1); P2 8–14 (done); P3 14–22 (12 left → Q1).
  4. Q1 – P1 22–38 (6 left → Q2); P3 38–50 (done, 12 < 16).
  5. Q2 – P1 50–56 (done).

Work level by level. Every job gets one Q0 quantum first. P2 needs only 6 ms, less than 8, so it completes without being demoted. P1 and P3 use their full 8 ms and move to Q1. Q1 is served only once Q0 is empty, at t = 22, and there P3 fits within the 16 ms quantum while P1 does not.

Completion times are P1 = 56, P2 = 14, P3 = 50, so turnaround times are the same (all arrived at 0), averaging 40 ms. Waiting time = turnaround − burst: P1 = 26, P2 = 8, P3 = 30, averaging 21.33 ms. The shortest job finished first even though the scheduler was never told any burst length.

MLFQ result (all times in ms)
ProcessBurstLevels usedCompletionTurnaroundWaiting
P130Q0 → Q1 → Q2565626
P26Q014148
P320Q0 → Q1505030
Average4021.33
Q0 q = 8, Q1 q = 16, Q2 FCFS; P1 = 30, P2 = 6, P3 = 20, all at t = 0P1Q0P2Q0P3Q0P1Q1P3Q1P1Q2081422385056P2 fits in one Q0 quantum; P3 finishes in Q1; only P1 reaches Q2waiting: P1 26, P2 8, P3 30 → average 21.33 ms
  • Write the level of every slice under the Gantt chart; examiners look for it
  • If a new job arrived at t = 30, it would enter Q0 and preempt P1 in Q1 at once
5

Multilevel Queue vs Multilevel Feedback Queue

The two names are often confused. In multilevel queue scheduling, processes are permanently assigned to a queue when they are created — for example system, interactive and batch — and never move. In multilevel feedback queue scheduling, processes move between queues according to their behaviour. The feedback is the difference.

Multilevel queue compared with multilevel feedback queue
Multilevel queueMultilevel feedback queue
Queue assignmentFixed at creation, by process typeChanges with observed CPU use
Movement between queuesNoneDemotion and promotion
Needs process classificationYes, in advanceNo, learned at run time
StarvationLikely for low queuesPrevented by priority boost or aging
Overhead and complexityLowHigher: many parameters to tune
  • Multilevel queue suits systems where job classes are known in advance: system, interactive, batch
  • Between fixed queues the split can be strict priority or a time share, such as 80% foreground and 20% background
6

Strengths, Weaknesses and Real Schedulers

MLFQ's strength is that it gets most of SJF's benefit — short jobs finish quickly — and round robin's responsiveness without needing information the OS does not have. Its weakness is tuning: the number of queues, the quanta, the allotments and the boost interval all interact, and a bad setting either starves long jobs or lets CPU-bound jobs crowd out interactive ones.

Real schedulers show both sides. Solaris used a table of 60 priority levels with configurable quanta; Windows boosts the priority of a thread that has just finished I/O; Linux replaced its earlier multi-queue design with the Completely Fair Scheduler, and in 2023 with EEVDF, partly to avoid MLFQ-style tuning.

  • Advantage: favours short and interactive jobs automatically
  • Advantage: no need to know burst lengths in advance
  • Disadvantage: many parameters, hard to tune well
  • Disadvantage: without boosting, long jobs can starve
  • Linux replaced queue levels with weighted fairness: Completely Fair Scheduler