Operating Systems Module 3: CPU scheduling Lesson 3.5 12 min

How Linux schedules

Fair sharing by virtual runtime (CFS, and EEVDF which replaced it), nice values as weights, one run queue per core, and how an idle core steals work.

Open a system monitor on a laptop with several cores while a few programs run. Every core shows some activity, and when one program gets busy, its load does not stay stuck on one core while the others sit idle. Something is sharing out the work between cores, and within each core, sharing out the time between tasks.

This lesson shows the ideas Linux uses, in plain words. You already have every piece: time slices from round robin, priorities, and the wish to treat interactive tasks well.

Fair sharing by virtual runtime

For many years Linux used the Completely Fair Scheduler (CFS). Its goal is simple to state: if n tasks want the CPU, each should get a 1/n share, as if the CPU could run them all at once at 1/n speed. A real CPU runs one task at a time, so CFS keeps score.

Each task has a virtual runtime: how much CPU time it has had so far. The scheduler always runs the task with the smallest virtual runtime, the one that has had the least. While a task runs, its virtual runtime grows, until another task has less and takes over. A task that sleeps a lot (an editor waiting for keys) builds up very little virtual runtime, so when it wakes it is at the front and runs almost at once. Interactive tasks get good response without any special rules, which is what MLFQ (Lesson 3.4) needed several rules to achieve.

Since Linux 6.6 the default is a newer scheduler called EEVDF (earliest eligible virtual deadline first). It keeps the same fairness idea, but each task also gets a virtual deadline, and tasks that want short, frequent turns can get earlier deadlines. That improves latency for tasks such as audio, without letting them take more than their fair share.

Nice values are weights

Not every task should get an equal share. Each task has a nice value: 0 by default, higher to be “nicer” to others and take less, lower to take more. The name comes from the idea that a high-nice task is being nice to everyone else.

The scheduler turns the nice value into a weight. A task’s virtual runtime grows more slowly the bigger its weight, so an important task can run longer before it stops being the one with the least. Two busy tasks with equal nice values split the CPU evenly; give one of them a higher nice value and it gets a smaller share, but it still gets some. This is different from strict priorities (Lesson 3.4), where a lower priority could starve completely.

Any program can make itself nicer. Going the other way, to a lower nice value, needs administrator rights, or every program would ask for it.

nice.c
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <sched.h>
#include <unistd.h>
#include <sys/resource.h>

int main(void) {
    int before = getpriority(PRIO_PROCESS, 0);          /* this process's nice value */
    errno = 0;
    if (nice(5) == -1 && errno != 0) { perror("nice"); return 1; }   /* be 5 steps nicer */
    int after = getpriority(PRIO_PROCESS, 0);
    printf("nice value went up by %d\n", after - before);

    cpu_set_t cpus;
    sched_getaffinity(0, sizeof cpus, &cpus);          /* which cores may run this process? */
    printf("cores this process may run on: %d\n", CPU_COUNT(&cpus));
    printf("running on core %d right now\n", sched_getcpu());
    return 0;
}

Output (one run)

nice value went up by 5
cores this process may run on: 16
running on core 10 right now

getpriority reads the nice value and nice(5) raises it by 5. The second half asks which cores the process is allowed to use (its CPU affinity) and which core it is on at this moment. Both numbers depend on the machine, and the second can change from one run to the next: the scheduler may move the process between cores.

One run queue per core

With one CPU, there is one ready queue. With many cores, a single shared queue would be a problem: every core would have to lock it to pick a task, and on a big machine the cores would spend their time queuing for the lock. Tasks would also hop between cores at random, and each hop leaves behind the task’s data in the old core’s cache.

So Linux gives each core its own run queue. A core picks only from its own queue, with no fighting over a lock, and a task tends to stay on the core whose cache already holds its data. The cost is that queues can become uneven: one core has a pile of work while another has none. Linux fixes this with load balancing: from time to time it moves tasks from busy queues to quiet ones. And when a core runs out of work completely, it does not wait for the next balancing round; it looks at the other queues and pulls a task over. Taking work from another core’s queue is called work stealing.

Here are two cores and five tasks. Tasks A, B and C (6, 6 and 4 ms) are on core 1; D and E (2 ms each) are on core 2. Each core runs its own queue round robin with a 2 ms slice. The bottom pane is the same machine with stealing turned off.

Two cores, two queues, and an idle core that steals work

  1. Tasks arrive A on core 1, B on core 1, C on core 1, D on core 2 and E on core 2 arrive and join their cores' queues. Core 1 runs A. Core 2 runs D.
    Time
    0 ms
    Core 1
    runs A · queue B → C
    Core 2
    runs D · queue E
    Steals so far
    0
    Finished
    none yet
  2. D finishes on core 2 Core 1: A's slice is over, so it goes to the back of that core's queue. Core 1 runs B. D finishes on core 2 at 2 ms. Core 2 runs E.
    Time
    2 ms
    Core 1
    runs B · queue C → A
    Core 2
    runs E · queue empty
    Steals so far
    0
    Finished
    D at 2
  3. Core 2 steals B Core 1: B's slice is over, so it goes to the back of that core's queue. Core 1 runs C. E finishes on core 2 at 4 ms. Core 2 has nothing to do, so it steals B from the back of core 1's queue. Core 2 runs B.
    Time
    4 ms
    Core 1
    runs C · queue A
    Core 2
    runs B · queue empty
    Steals so far
    1
    Finished
    D at 2, E at 4
  4. Slice over on core 1 Core 1: C's slice is over, so it goes to the back of that core's queue. Core 1 runs A.
    Time
    6 ms
    Core 1
    runs A · queue C
    Core 2
    runs B · queue empty
    Steals so far
    1
    Finished
    D at 2, E at 4
  5. Core 2 steals A Core 1: A's slice is over, so it goes to the back of that core's queue. Core 1 runs C. B finishes on core 2 at 8 ms. Core 2 has nothing to do, so it steals A from the back of core 1's queue. Core 2 runs A.
    Time
    8 ms
    Core 1
    runs C · queue empty
    Core 2
    runs A · queue empty
    Steals so far
    2
    Finished
    B at 8, D at 2, E at 4
  6. C finishes on core 1 C finishes on core 1 at 10 ms. Core 1 has nothing left to run and goes idle. A finishes on core 2 at 10 ms. Core 2 has nothing left to run and goes idle. Every task is done at 10 ms.
    Time
    10 ms
    Core 1
    idle · queue empty
    Core 2
    idle · queue empty
    Steals so far
    2
    Finished
    A at 10, B at 8, C at 10, D at 2, E at 4

With stealing, core 2 never sat idle: when it ran out of work it took B, and later A. Everything was done at 10 ms. Without stealing, core 2 was idle for 12 ms while core 1 worked through its pile alone, and the last task finished at 16 ms. Two cores are only twice as fast if both have something to do.

Press Try it to change the number of cores, put every task on core 1, or turn stealing off.

In the real world

Three commands change how Linux schedules a program:

Terminal
$ nice -n 10 make -j8          # start a build with a higher nice value
$ renice -n 5 -p 4182          # make a running process nicer
$ taskset -c 0,1 ./server      # only let it run on cores 0 and 1
$ chrt -f 50 ./audio_engine    # real-time FIFO policy (needs root)

nice and renice set the nice value, which turns into the weight you saw above. taskset sets the CPU affinity, so the process can only be placed on (or stolen by) the listed cores. chrt moves a program out of the fair scheduler altogether, into a real-time policy (SCHED_FIFO or SCHED_RR) that always runs before ordinary tasks. Real-time is for things like audio, where a late answer is a wrong answer; a real-time program stuck in a loop can freeze a core, so it is used with care. :::

Recap

  • Linux’s fair scheduler runs the task with the smallest virtual runtime, the one that has had the least CPU. Sleepy, interactive tasks therefore run quickly when they wake.
  • EEVDF replaced CFS as the default in Linux 6.6; it keeps fairness and adds virtual deadlines for better latency.
  • A nice value becomes a weight: a higher nice value means a smaller share, but never zero.
  • Each core has its own run queue: no shared lock and warm caches, but queues can become uneven.
  • Load balancing and work stealing move tasks to idle cores so all cores stay busy.

Quick check

Quick check

  1. You start a long job with nice -n 10. What changes?
  2. Why does Linux give each core its own run queue instead of one shared queue?
  3. What problem does work stealing fix?
  4. A text editor spends most of its time asleep, waiting for keys. Why does the fair scheduler run it quickly when a key arrives?

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion