Process Scheduling — The CFS
You might have 200 processes but only 8 CPU cores. The scheduler decides which process runs on which core at any given moment. Linux's scheduler, the CFS (Completely Fair Scheduler), uses a clever algorithm to share CPU time fairly.
The Scheduler's Job
How CFS Works — vruntime
CFS tracks a number called vruntime (virtual runtime) for each process — how long it has run, weighted by priority. The core idea is simple:
CFS uses a red-black tree (a self-balancing binary search tree) to store runnable processes, sorted by vruntime. The leftmost node (lowest vruntime) is always the next to run. Picking the next process is O(log n).
Priority and Weight
Not all processes are equal — nice values change how fast vruntime grows. A higher-priority process accumulates vruntime more slowly, so it gets scheduled more often.
Scheduling Policies
| Policy | Who uses it | Behavior |
|---|---|---|
| SCHED_NORMAL | Regular processes | CFS — fair sharing, default |
| SCHED_BATCH | Background batch jobs | CFS with lower wakeup priority |
| SCHED_IDLE | Very low priority tasks | Only runs when nothing else wants CPU |
| SCHED_FIFO | Real-time tasks | Run until done or voluntarily yields. No preemption. |
| SCHED_RR | Real-time tasks | Like FIFO but with time slices — round-robin among equal priority |
| SCHED_DEADLINE | Time-critical tasks | Earliest Deadline First — guaranteed to complete before deadline |
Real-time policies (FIFO, RR) always preempt NORMAL processes. Within RT, higher priority numbers run first.