Skip to content
LeetQuant
QD05 Operating Systems and Computer Architecture

QD05 · Operating Systems and Computer Architecture · Lesson 5 of 6

Scheduling

How Linux shares CPUs fairly with weights and virtual runtime, real-time policies, CPU affinity and core isolation, and why trading systems pin busy-polling threads to dedicated cores.

16 min

The scheduler's job

Each CPU has a run queue of runnable tasks. A task is running, runnable (ready, waiting for a CPU), sleeping (blocked on I/O, a futex or a timer; shown as S, or D for uninterruptible sleep, usually disk I/O) or stopped. The scheduler decides which runnable task gets each CPU and for how long. It runs when a task blocks or wakes, on the periodic timer tick, and when tasks are created or migrated. Periodically it also load-balances, moving tasks between CPUs' queues.

Two goals pull against each other: throughput and fairness (everyone progresses, little time wasted switching) and latency (a task that wakes runs soon). General-purpose schedulers are tuned for the first; trading systems need the second, and get it mostly by keeping the scheduler out of the way.

CFS: fair shares by virtual runtime

The Completely Fair Scheduler (CFS), Linux's default for normal tasks from 2.6.23, models an ideal CPU that runs all runnable tasks simultaneously, each at a speed proportional to its weight.

  • Each task has a virtual runtime, which advances as the task runs, scaled by its weight:
Δvruntime=Δtreal×1024w\Delta \text{vruntime} = \Delta t_{\text{real}} \times \frac{1024}{w}

where 1024 is the weight at nice 0. A heavy task's vruntime grows slowly.

  • The scheduler always runs the runnable task with the smallest vruntime (kept in a red-black tree ordered by vruntime), so tasks that have had less than their share catch up.
  • A newly woken task's vruntime is set near the queue's minimum, so a long sleeper cannot hoard credit, but it still tends to run soon after waking.

Nice values run from −20-20 (highest priority) to +19+19. Weights come from a kernel table in which each nice step changes the weight by about 1.25 times, so one nice level is roughly a 10% change in CPU share relative to a competitor: nice 0 is 1024, nice 1 is 820, nice 5 is 335, nice 10 is 110, nice 19 is 15, and nice −20-20 is 88,761. When nn tasks compete for one CPU, task ii receives

sharei=wi∑jwj.\text{share}_i = \frac{w_i}{\sum_j w_j}.

Since Linux 6.6 the selection rule is EEVDF (earliest eligible virtual deadline first), which adds per-task deadlines and lag for better latency, but the weights and long-run shares are the same.

Worked example

CPU shares from nice values

(a) Two CPU-bound tasks share one core, one at nice 0 and one at nice 5. What share does each get? (b) Three CPU-bound tasks share a core at nice 0, nice 0 and nice 10. What share does each get?

Show solution

(a) Weights 1024 and 335, total 1,359. Shares: 1024/1359≈75.3%1024/1359 \approx 75.3\% and 335/1359≈24.7%335/1359 \approx 24.7\%. Five nice levels give roughly a 3 to 1 split (1.255≈3.051.25^{5} \approx 3.05).

(b) Weights 1024, 1024 and 110, total 2,158. Each nice-0 task gets 1024/2158≈47.5%1024/2158 \approx 47.5\% and the nice-10 task 110/2158≈5.1%110/2158 \approx 5.1\%.

The interview point: nice changes share, not latency. A nice −20-20 task still waits behind a running task until the scheduler next preempts it, which can be up to a few milliseconds. For bounded latency you need either a real-time policy or a CPU with nothing else on it.

Real-time policies

PolicyBehaviour
SCHED_OTHER (normal)Fair sharing as above
SCHED_BATCH, SCHED_IDLEThroughput-oriented or only-when-idle background work
SCHED_FIFOStatic priority 1–99; runs until it blocks, yields or a higher priority preempts it
SCHED_RRLike FIFO, but round-robin with a time slice among equal priorities
SCHED_DEADLINERuntime, period and deadline reservations

Any runnable real-time task preempts every normal task on its CPU. Set one with chrt -f 50 ./app or sched_setscheduler. The danger: a SCHED_FIFO thread that busy-polls never blocks, so kernel threads and per-CPU work on that core can starve. Real-time throttling (by default kernel.sched_rt_runtime_us = 950000 out of each 1000000) stops real-time tasks once they have used 950 ms of a 1 s period, so a spinning FIFO thread can be stopped for up to 50 ms every second. In practice, a busy-polling thread on an isolated core does not need a real-time policy, because there is nothing to compete with.

CPU affinity and isolation

Affinity restricts which CPUs a thread may run on:

taskset -c 3 ./strategy          # start pinned to CPU 3 (Linux)
taskset -cp 3 12345              # re-pin running pid 12345
numactl --cpunodebind=0 --membind=0 ./strategy   # CPUs and memory on NUMA node 0

From code, pin each thread individually:

#include <cstdio>
#include <thread>
#ifdef __linux__
#include <pthread.h>
#include <sched.h>
#endif

// Pin the calling thread to one CPU. Linux only; macOS has no hard affinity API.
bool pin_to_cpu(int cpu) {
#ifdef __linux__
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    return pthread_setaffinity_np(pthread_self(), sizeof(set), &set) == 0;
#else
    (void)cpu;
    return false;
#endif
}

int main() {
    std::thread hot([] {
        bool ok = pin_to_cpu(3);
        std::printf("pinned to CPU 3: %s\n", ok ? "yes" : "no (not Linux)");
        // ... busy-poll the market-data queue here ...
    });
    hot.join();
}

Affinity alone stops your thread from moving but does not stop other tasks from landing on its core. Isolation does, via kernel boot parameters on Linux:

  • isolcpus=2-7: removes CPUs 2–7 from the general scheduler and load balancing; nothing runs there unless explicitly pinned. Threads pinned to an isolated CPU are not balanced among themselves either, so give each hot thread its own CPU. (Newer setups achieve the same with cpusets/cgroups.)
  • nohz_full=2-7: stops the periodic timer tick on a CPU running a single task.
  • rcu_nocbs=2-7: moves RCU callback processing off those CPUs.
  • Interrupt affinity: steer device interrupts away through /proc/irq/<n>/smp_affinity (and disable or configure irqbalance), except the NIC queue you want local.

Further habits: keep the hyperthread sibling of a hot core idle (or disable SMT), keep threads, memory and the NIC on the same NUMA node, fix the CPU frequency, and disable deep C-states, since waking a core from deep sleep can take tens to hundreds of microseconds.

Busy-polling versus blocking

A thread waiting for work can block (sleep on a futex, epoll_wait, a condition variable) and let the kernel wake it, or busy-poll (spin reading a flag, a queue index or a NIC ring). A two-thread ping-pong shows the gap:

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <thread>

constexpr int ROUNDS = 100'000;

double spin_round_trip_ns() {
    std::atomic<int> turn{0};   // 0: main's turn to ping, 1: worker's turn to pong
    std::thread worker([&] {
        for (int i = 0; i < ROUNDS; ++i) {
            while (turn.load(std::memory_order_acquire) != 1) { }   // busy-poll
            turn.store(0, std::memory_order_release);
        }
    });
    auto t0 = std::chrono::steady_clock::now();
    for (int i = 0; i < ROUNDS; ++i) {
        turn.store(1, std::memory_order_release);
        while (turn.load(std::memory_order_acquire) != 0) { }
    }
    auto t1 = std::chrono::steady_clock::now();
    worker.join();
    return std::chrono::duration<double, std::nano>(t1 - t0).count() / ROUNDS;
}

double blocking_round_trip_ns() {
    std::mutex m;
    std::condition_variable cv;
    int turn = 0;
    std::thread worker([&] {
        for (int i = 0; i < ROUNDS; ++i) {
            std::unique_lock lk(m);
            cv.wait(lk, [&] { return turn == 1; });   // sleeps in the kernel
            turn = 0;
            cv.notify_one();
        }
    });
    auto t0 = std::chrono::steady_clock::now();
    for (int i = 0; i < ROUNDS; ++i) {
        std::unique_lock lk(m);
        turn = 1;
        cv.notify_one();
        cv.wait(lk, [&] { return turn == 0; });
    }
    auto t1 = std::chrono::steady_clock::now();
    worker.join();
    return std::chrono::duration<double, std::nano>(t1 - t0).count() / ROUNDS;
}

int main() {
    std::printf("busy-poll round trip: %8.0f ns\n", spin_round_trip_ns());
    std::printf("blocking  round trip: %8.0f ns\n", blocking_round_trip_ns());
}

On an Apple-silicon laptop, repeated runs gave about 100–400 ns for the spinning round trip and 11–14 µs for the blocking one: a factor of roughly 30 to 100. The spinning version costs only a cache line moving between two cores; the blocking version pays system calls, two wake-ups and two context switches per round trip. On a tuned Linux server both numbers are smaller, but the gap remains one to two orders of magnitude.

The price of spinning is a core at 100% forever, plus power and heat, and it only works if the spinner has the core to itself; two spinners sharing a core are disastrous. Spin loops should include a pause hint (_mm_pause() on x86) to save power and be kind to a hyperthread sibling. A common compromise for less critical threads is spin, then block: spin for a few microseconds, then sleep.

Worked example

a millisecond tail on a microsecond system

An interviewer says: "Our order path has a median of 2 µs, but p99.9 is about 3 ms, and the slow events have no relation to market activity. The hot thread busy-polls but is not pinned, and the box also runs a logging thread and a monitoring agent. What is going on and how do you fix it?"

Show solution

Reason from the size of the outlier. 3 ms is about 1,500 times the median: far too big for cache misses (nanoseconds) or a page fault (about a microsecond), and about the size of a scheduler time slice. A busy-polling thread never blocks, so whenever the logger or the agent becomes runnable on the same CPU, the fair scheduler eventually preempts the hot thread to give the other task its share, and the hot thread waits up to a slice. Unpinned, it can also be migrated to another CPU and arrive with cold caches.

How to confirm, on Linux: nonvoluntary_ctxt_switches in /proc/<pid>/task/<tid>/status climbing for the hot thread; perf sched showing other tasks on its CPU; correlation of slow events with the other processes' activity.

Fix, in order: isolate CPUs (isolcpus, nohz_full, rcu_nocbs) and steer interrupts off them; pin the hot thread alone on an isolated core; pin the logger and agent to housekeeping cores; then re-measure the tail. Mention the remaining sources of rare stalls (THP compaction, SMT siblings, power states, timer ticks) as the next things to rule out.

Knowledge check

Two CPU-bound tasks share one core under CFS, at nice 0 (weight 1024) and nice 5 (weight 335). About what share does the nice-0 task get?

Knowledge check

A machine boots with isolcpus=4-7. A team starts its strategy without taskset or affinity calls and finds that CPUs 4–7 sit idle. Why?

Knowledge check

Why does a busy-polling consumer react to a new message much faster than one blocked on a condition variable?

Knowledge check

What is the main risk of running a busy-polling thread as SCHED_FIFO on a core shared with other work?

Key takeaways

  • CFS (and EEVDF from Linux 6.6) shares a CPU in proportion to weights set by nice values; each nice step is about 1.25 times in weight.
  • Nice changes share, not wake-up latency. Real-time policies preempt normal tasks but a spinning RT thread can starve its core.
  • Affinity pins a thread; isolation (isolcpus, nohz_full, rcu_nocbs, IRQ steering) keeps everything else off the core.
  • Busy-polling turns a microseconds-scale wake-up into a ~100 ns cache-line transfer, at the cost of a dedicated core.
  • Trading systems pin one busy-polling thread per isolated core to remove preemption, migration and wake-up latency from the tail.

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).