Lesson 12 · Processes, threads, and CPU scheduling

Completely Fair Scheduler (CFS)

CFS replaced priority queues and fixed time slices with one number per task: how much weighted CPU time it has had. The task with the least always runs next.

Completely Fair Scheduler (CFS) concept diagramA red-black tree of seven tasks keyed by vruntime, from T3 at 12 ms on the far left to T6 at 31 ms. An arrow from the leftmost node T3 runs to the CPU; a return arrow from the CPU goes back to the tree's root, labelled with the vruntime update, vruntime plus delta times 1024 over weight.run queue: red-black tree keyed by vruntime (ms)T1·20T5·15T2·27T3·12T7·18T4·23T6·31pick the cached leftmost node: O(1)CPU runs T3for its weighted slicereinsert from the root: O(log n)vruntime += Δ × 1024 / weightheavier tasks grow slowerredblack
1

A Fair Share of an Ideal CPU

  1. Track each task's weighted CPU time as its vruntime.
  2. Order runnable tasks in a red-black tree keyed by vruntime.
  3. Pick the leftmost node: the smallest vruntime.
  4. Run it for a slice proportional to its weight.
  5. Charge the elapsed time to its vruntime and reinsert it.

The Completely Fair Scheduler (CFS) is the Linux kernel's scheduler for normal (SCHED_OTHER) tasks, usually called the CFS scheduler. Written by Ingo Molnár, it was merged in Linux 2.6.23 (2007), replacing the O(1) scheduler, and remained the default until Linux 6.6 (2023), when the EEVDF (Earliest Eligible Virtual Deadline First) scheduler replaced its pick logic. EEVDF keeps CFS's core ideas, vruntime and weights, so CFS is still the model for understanding Linux scheduling.

CFS starts from an ideal, perfectly multitasking CPU: with n runnable tasks of equal weight, each would run simultaneously at 1/n of the CPU's speed. Real hardware runs one task at a time, so CFS tracks how far each task has fallen behind that ideal and always runs the one that is furthest behind. There are no priority queues, no fixed time quantum and no heuristics for guessing which tasks are interactive, only a running total per task.

Unlike round robin or a multilevel feedback queue, CFS is a proportional-share scheduler: fairness means each task gets CPU time in proportion to its weight, set by its nice value.

  • Real-time tasks (SCHED_FIFO, SCHED_RR) are scheduled by a separate class and always run before CFS tasks
  • Each CPU has its own CFS run queue; load balancing moves tasks between them
2

Virtual Runtime (vruntime) and Nice Weights

Each task has a nice value from −20 (highest priority) to +19 (lowest). The kernel converts it to a weight using a fixed table, sched_prio_to_weight: nice 0 is 1024, and each nice level multiplies or divides the weight by about 1.25. The factor is chosen so that one nice step changes a task's CPU share by roughly 10% relative to a competitor.

Virtual runtime (vruntime) is the task's actual CPU time scaled by its weight: vruntime += delta_exec × 1024 / weight. For a nice-0 task vruntime advances at wall-clock speed. A heavier task's vruntime advances more slowly, so it stays towards the left of the tree and gets picked more often; a lighter task's vruntime races ahead. When every task's vruntime is equal, every task has had exactly its weighted fair share.

Nice values and weights from the kernel table
NiceWeightvruntime per 1 ms of CPUShare against one nice-0 task
−20887610.012 ms98.9%
−531210.328 ms75.3%
−112770.802 ms55.5%
010241.000 ms50.0%
18201.249 ms44.5%
53353.057 ms24.7%
191568.267 ms1.4%
  • Only the ratio of weights matters: two nice 5 tasks share a CPU 50/50, exactly like two nice 0 tasks
  • Lowering a task's nice value below 0 needs root privileges (CAP_SYS_NICE); any user can raise it
3

The Red-Black Run Queue

  1. Update the current task: vruntime += delta_exec × 1024 / weight.
  2. Reinsert it in the tree if it is still runnable (O(log n)).
  3. Advance min_vruntime to the smallest vruntime, never backwards.
  4. Pick the cached leftmost node (O(1)) and remove it from the tree.
  5. Run it until its slice ends, it blocks, or a wake-up preempts it.

Runnable tasks are kept in a red-black tree ordered by vruntime. A red-black tree is a self-balancing binary search tree, so inserting and removing a task costs O(log n). The kernel caches a pointer to the leftmost node, the task with the smallest vruntime, so choosing the next task is O(1).

The running task is taken out of the tree. While it runs, its vruntime grows. When its slice expires, when it blocks, or when a newly woken task has a sufficiently smaller vruntime, the scheduler updates its vruntime, puts it back in the tree if it is still runnable, and takes the new leftmost. The kernel also keeps min_vruntime, a monotonically increasing lower bound on the tree's vruntimes, used to place tasks that join the queue.

  • A task that blocks leaves the tree entirely; only runnable tasks are kept in it
  • Ties in vruntime go to the right, so among equal keys the task inserted first runs first
Key reference

Terms, operations, and practical uses

Core vocabulary

  • vruntimeWeighted CPU time a task has used; the smallest runs next.
  • Nice value−20 to +19; lower means more CPU.
  • WeightFrom the nice value: 1024 at nice 0, about ×1.25 per level.
  • min_vruntimeMonotonic lower bound on the run queue's vruntimes; where new tasks start.
  • Targeted latencyThe period in which every runnable task should run once.

Formulas

  • vruntime updatevruntime += delta_exec × 1024 / weight
  • Time slicemax(latency × weight / Σ weights, minimum granularity)
  • Periodlatency if n ≤ 8, else n × minimum granularity
  • CPU shareweight / Σ weights of runnable tasks
  • Waking taskvruntime = max(vruntime, min_vruntime − latency / 2)
Implementation

CFS: picking the smallest vruntime

import bisect

# Kernel defaults on a machine with 8 or more CPUs, in microseconds.
SCHED_LATENCY = 24000
MIN_GRANULARITY = 3000
NICE_0_WEIGHT = 1024
# From the kernel's sched_prio_to_weight table.
WEIGHT = {-5: 3121, 0: 1024, 5: 335}

# (name, nice, arrival time in microseconds)
TASKS = [("A", 0, 0), ("B", 5, 0), ("C", -5, 0), ("D", 0, 40000)]
PICKS = 14


def ms(us):
    return f"{us // 1000}.{us % 1000:03d}"


def simulate():
    nice = {name: n for name, n, _ in TASKS}
    vruntime, ran = {}, {}
    tree = []  # sorted (vruntime, seq, name): the red-black tree's in-order view
    seq, now, min_vruntime = 0, 0, 0
    for _ in range(PICKS):
        for name, _, arrival in TASKS:
            if name not in vruntime and arrival <= now:
                # A new task starts at min_vruntime, not 0, so it cannot hog the CPU.
                vruntime[name], ran[name] = min_vruntime, 0
                bisect.insort(tree, (min_vruntime, seq, name))
                seq += 1
                print(
                    f"t={ms(now):>7}  {name} enqueued (arrived {ms(arrival)}), "
                    f"vruntime = min_vruntime {ms(min_vruntime)}"
                )
        order = ", ".join(f"{name} {ms(v)}" for v, _, name in tree)
        _, _, cur = tree.pop(0)  # leftmost node: smallest vruntime
        weight = WEIGHT[nice[cur]]
        total = weight + sum(WEIGHT[nice[name]] for _, _, name in tree)
        slice_us = max(SCHED_LATENCY * weight // total, MIN_GRANULARITY)
        before = vruntime[cur]
        vruntime[cur] += slice_us * NICE_0_WEIGHT // weight
        ran[cur] += slice_us
        print(
            f"t={ms(now):>7}  run {cur}  slice {ms(slice_us)}  "
            f"vruntime {ms(before)} -> {ms(vruntime[cur])}  tree: {order}"
        )
        now += slice_us
        bisect.insort(tree, (vruntime[cur], seq, cur))
        seq += 1
        min_vruntime = max(min_vruntime, tree[0][0])
    print(f"elapsed {ms(now)} ms, min_vruntime {ms(min_vruntime)}")
    for name, n, _ in TASKS:
        share = ran[name] * 1000 // now
        print(
            f"{name}  nice {n:>2}  weight {WEIGHT[n]:>4}  "
            f"cpu {ms(ran[name]):>6} ms  share {share // 10}.{share % 10}%"
        )


simulate()
#include <algorithm>
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <vector>

// Kernel defaults on a machine with 8 or more CPUs, in microseconds.
const long SCHED_LATENCY = 24000;
const long MIN_GRANULARITY = 3000;
const long NICE_0_WEIGHT = 1024;
// From the kernel's sched_prio_to_weight table.
const std::map<int, long> WEIGHT{{-5, 3121}, {0, 1024}, {5, 335}};

struct Task {
    char name;
    int nice;
    long arrival;
};
const std::vector<Task> TASKS{{'A', 0, 0}, {'B', 5, 0}, {'C', -5, 0}, {'D', 0, 40000}};
const int PICKS = 14;

std::string ms(long us) {
    char buf[32];
    std::snprintf(buf, sizeof buf, "%ld.%03ld", us / 1000, us % 1000);
    return buf;
}

int main() {
    std::map<char, int> nice;
    for (const Task& t : TASKS) nice[t.name] = t.nice;
    std::map<char, long> vruntime, ran;
    // std::set is a red-black tree: ordered by (vruntime, insertion order).
    std::set<std::tuple<long, int, char>> tree;
    int seq = 0;
    long now = 0, minVruntime = 0;

    for (int pick = 0; pick < PICKS; pick++) {
        for (const Task& t : TASKS) {
            if (!vruntime.count(t.name) && t.arrival <= now) {
                // A new task starts at min_vruntime, not 0, so it cannot hog the CPU.
                vruntime[t.name] = minVruntime;
                ran[t.name] = 0;
                tree.insert({minVruntime, seq++, t.name});
                std::printf("t=%7s  %c enqueued (arrived %s), vruntime = min_vruntime %s\n",
                            ms(now).c_str(), t.name, ms(t.arrival).c_str(), ms(minVruntime).c_str());
            }
        }
        std::string order;
        for (auto [v, s, name] : tree) {
            if (!order.empty()) order += ", ";
            order += std::string(1, name) + " " + ms(v);
        }
        char cur = std::get<2>(*tree.begin()); // leftmost node: smallest vruntime
        tree.erase(tree.begin());
        long weight = WEIGHT.at(nice[cur]);
        long total = weight;
        for (auto [v, s, name] : tree) total += WEIGHT.at(nice[name]);
        long slice = std::max(SCHED_LATENCY * weight / total, MIN_GRANULARITY);
        long before = vruntime[cur];
        vruntime[cur] += slice * NICE_0_WEIGHT / weight;
        ran[cur] += slice;
        std::printf("t=%7s  run %c  slice %s  vruntime %s -> %s  tree: %s\n", ms(now).c_str(), cur,
                    ms(slice).c_str(), ms(before).c_str(), ms(vruntime[cur]).c_str(), order.c_str());
        now += slice;
        tree.insert({vruntime[cur], seq++, cur});
        minVruntime = std::max(minVruntime, std::get<0>(*tree.begin()));
    }
    std::printf("elapsed %s ms, min_vruntime %s\n", ms(now).c_str(), ms(minVruntime).c_str());
    for (const Task& t : TASKS) {
        long share = ran[t.name] * 1000 / now;
        std::printf("%c  nice %2d  weight %4ld  cpu %6s ms  share %ld.%ld%%\n", t.name, t.nice,
                    WEIGHT.at(t.nice), ms(ran[t.name]).c_str(), share / 10, share % 10);
    }
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

public class Main {
    // Kernel defaults on a machine with 8 or more CPUs, in microseconds.
    static final long SCHED_LATENCY = 24000;
    static final long MIN_GRANULARITY = 3000;
    static final long NICE_0_WEIGHT = 1024;
    // From the kernel's sched_prio_to_weight table.
    static final Map<Integer, Long> WEIGHT = Map.of(-5, 3121L, 0, 1024L, 5, 335L);

    record Task(char name, int nice, long arrival) {}

    // One node of the run queue, ordered by (vruntime, insertion order).
    record Entity(long vruntime, int seq, char name) implements Comparable<Entity> {
        public int compareTo(Entity o) {
            return vruntime != o.vruntime ? Long.compare(vruntime, o.vruntime) : Integer.compare(seq, o.seq);
        }
    }

    static final List<Task> TASKS = List.of(
            new Task('A', 0, 0), new Task('B', 5, 0), new Task('C', -5, 0), new Task('D', 0, 40000));
    static final int PICKS = 14;

    static String ms(long us) {
        return String.format("%d.%03d", us / 1000, us % 1000);
    }

    public static void main(String[] args) {
        Map<Character, Integer> nice = new HashMap<>();
        for (Task t : TASKS) nice.put(t.name(), t.nice());
        Map<Character, Long> vruntime = new HashMap<>();
        Map<Character, Long> ran = new HashMap<>();
        TreeSet<Entity> tree = new TreeSet<>(); // TreeSet is a red-black tree
        int seq = 0;
        long now = 0;
        long minVruntime = 0;

        for (int pick = 0; pick < PICKS; pick++) {
            for (Task t : TASKS) {
                if (!vruntime.containsKey(t.name()) && t.arrival() <= now) {
                    // A new task starts at min_vruntime, not 0, so it cannot hog the CPU.
                    vruntime.put(t.name(), minVruntime);
                    ran.put(t.name(), 0L);
                    tree.add(new Entity(minVruntime, seq++, t.name()));
                    System.out.printf("t=%7s  %c enqueued (arrived %s), vruntime = min_vruntime %s%n",
                            ms(now), t.name(), ms(t.arrival()), ms(minVruntime));
                }
            }
            List<String> order = new ArrayList<>();
            for (Entity e : tree) order.add(e.name() + " " + ms(e.vruntime()));
            char cur = tree.pollFirst().name(); // leftmost node: smallest vruntime
            long weight = WEIGHT.get(nice.get(cur));
            long total = weight;
            for (Entity e : tree) total += WEIGHT.get(nice.get(e.name()));
            long slice = Math.max(SCHED_LATENCY * weight / total, MIN_GRANULARITY);
            long before = vruntime.get(cur);
            vruntime.put(cur, before + slice * NICE_0_WEIGHT / weight);
            ran.merge(cur, slice, Long::sum);
            System.out.printf("t=%7s  run %c  slice %s  vruntime %s -> %s  tree: %s%n", ms(now), cur,
                    ms(slice), ms(before), ms(vruntime.get(cur)), String.join(", ", order));
            now += slice;
            tree.add(new Entity(vruntime.get(cur), seq++, cur));
            minVruntime = Math.max(minVruntime, tree.first().vruntime());
        }
        System.out.printf("elapsed %s ms, min_vruntime %s%n", ms(now), ms(minVruntime));
        for (Task t : TASKS) {
            long share = ran.get(t.name()) * 1000 / now;
            System.out.printf("%c  nice %2d  weight %4d  cpu %6s ms  share %d.%d%%%n", t.name(), t.nice(),
                    WEIGHT.get(t.nice()), ms(ran.get(t.name())), share / 10, share % 10);
        }
    }
}
Watch it run

Step through it

Running on A nice 0, B nice 5, C nice −5; D nice 0 arrives at 40 ms; latency 24 ms, min granularity 3 ms

t = 0: three runnable tasksCPU020406080100msvruntime (ms)min_vruntime 0.000A nice 0 w 10240.000B nice 5 w 3350.000C nice -5 w 31210.000D nice 0 w 1024not yet runnablerun queue (red-black tree)blackredA0.0B0.0C0.0weights: A 1024 + B 335 + C 3121 = 4480fair share = weight / 4480 of every 24 ms periodevery task starts with vruntime 0
Step 1

Three tasks, three weights, all at vruntime 0

A has nice 0 (weight 1024), B nice 5 (weight 335), C nice −5 (weight 3121); the weights come from the kernel's table, about 1.25× per nice level. Total weight is 4480, so C deserves 70% of the CPU, A 23% and B 7%. The targeted latency is 24 ms and the minimum granularity 3 ms, the kernel defaults on an 8-CPU machine.

Output
1 / 18
4

Targeted Latency, Minimum Granularity and Time Slice

CFS has no fixed quantum. Instead it aims to run every runnable task once within a targeted latency (sched_latency), and gives each task a slice proportional to its weight: timeslice = targeted latency × weight / total weight of runnable tasks. The kernel default is 6 ms scaled by 1 + log2(CPUs), capped at 8 CPUs: 24 ms on a machine with 8 or more CPUs.

With many tasks the slices would become tiny and the CPU would spend its time context switching. So every slice is at least the minimum granularity (0.75 ms, scaled the same way to 3 ms). When there are more tasks than latency / granularity (8 by default), the period itself grows to nr_running × min_granularity. A third tunable, the wake-up granularity (1 ms, 4 ms scaled), sets how much smaller a waking task's vruntime must be before it preempts the running task. The tracer's example: A (nice 0), B (nice 5) and C (nice −5) have total weight 4480, so in a 24 ms period C gets 16.719 ms, A 5.485 ms and B 1.794 ms, raised to 3 ms.

slice = 24 ms × weight / total weight (4480), at least 3 mspure weightC 16.719A 5.485B24.0with 3 ms floorC 16.719A 5.485B 325.2B's 1.794 ms share is below the minimum granularity, so it runs 3 ms and the round stretches
  • With a single runnable task there is nothing to share, so it keeps running past its slice until another task wakes
  • Pitfall: the slice is not a fixed quantum; adding one task shrinks every other task's slice
5

New Tasks, Sleeping Tasks and Fairness

A task joining the tree cannot start at vruntime 0: next to tasks that have run for minutes it would be leftmost for a long time and monopolise the CPU. A process that forks repeatedly could starve everyone else. So a new task starts at min_vruntime; with the kernel's START_DEBIT feature it is placed one slice beyond it, so a fork cannot jump the queue.

A task that wakes from sleep is treated similarly: its vruntime is set to at least min_vruntime − sched_latency / 2. It keeps a small credit, so interactive tasks that sleep often (editors, shells) are picked soon after they wake and feel responsive, but a long sleep cannot bank unlimited CPU time. This is sleeper fairness, and it is how CFS favours interactive work without any explicit interactivity heuristics.

CFS also supports group scheduling through cgroups: fairness is applied first between groups (users, containers, services) and then between tasks inside each group, so one user with 50 threads cannot crowd out a user with one.

  • Edge case: a task that sleeps briefly keeps its own vruntime if it is already above the floor, so a short nap earns no credit
  • Edge case: a task moved to another CPU has its vruntime rebased to that CPU's min_vruntime, since each CPU's queue has its own clock
6

CFS vs Round Robin vs MLFQ

All three share the CPU in turns, but they decide the order and the length of each turn differently. Round robin gives every task the same quantum in FIFO order; MLFQ moves tasks between priority queues based on how they used their last quantum; CFS orders by accumulated weighted runtime and sizes the slice by weight. See CPU scheduling algorithms for the full family.

Three time-sharing schedulers compared
AspectRound RobinMLFQCFS
OrderingFIFO ready queuehighest non-empty priority queuesmallest vruntime (red-black tree)
Time slicefixed quantumfixed per level, longer lower downlatency × weight / total weight
Prioritiesnonelevels, changed by behaviournice → weight
Interactive tasksno special treatmentstay high by giving up the CPUsleeper credit via min_vruntime
Starvationnonepossible without priority boostnone: every vruntime rises
Pick costO(1)O(1) (fixed number of levels)O(1) pick, O(log n) insert
Used intextbooks, simple RTOSWindows, BSD, early LinuxLinux 2.6.23–6.5
  • With equal weights and no sleeping, CFS behaves much like round robin with a slice of latency / n
  • The difference shows with unequal weights or tasks that sleep: round robin ignores both, CFS accounts for both
7

Strengths and Limits

CFS's strength is that one simple rule handles everything: fairness, priorities, interactivity and starvation all fall out of vruntime. Its weakness is latency control: a task can only say how much CPU it wants (its weight), not how soon it needs it. That limitation is what EEVDF addresses, by giving each task a virtual deadline as well as a vruntime.

  • Strengths: proportional fairness by weight, no starvation, no interactivity heuristics to tune, group scheduling through cgroups
  • Limits: no way to ask for low latency apart from CPU share, O(log n) tree work on every enqueue, the minimum granularity bends the shares of low-weight tasks, and several tunables to get right