CPU series, post 2 of 5
One core runs one thread at a time. Everything else you have been told about multitasking is bookkeeping.
Set simultaneous multithreading aside for now. Post 3 puts it back.
Bookkeeping sounds easy until you read the bug reports. In 2016, Lozi and colleagues published The Linux Scheduler: a Decade of Wasted Cores at EuroSys. They found four bugs that made Linux leave cores idle, sometimes for seconds, while ready threads sat in run queues. Typical workloads slowed by 13% to 24%. Some corner cases slowed by 138 times. The scheduler had one invariant to maintain, and it broke it for years without anyone noticing.
If the multi-core version is that hard, start with the single-core one. It is the version where nothing hides the trade-offs. The samples below run on the same 2-vCPU cloud VM as Post 1, and where it matters I pin the work to one CPU. Models are labeled as models.
Concurrency is structure. Parallelism is execution.
Rob Pike drew the cleanest line in a 2012 Heroku Waza talk, Concurrency is not Parallelism. Concurrency is a way to structure a program as independent pieces. Parallelism is running pieces at the same instant. One core can run a concurrent program. It can never run a parallel one.
Why does the split matter? Because the two fail differently. Concurrency failures are correctness failures: the program is built from pieces that interleave, and some interleavings are wrong. Parallelism adds a second class, where the program is correct and slow because shared hardware is contended. Post 3 covers the second class. This post covers the first.
Here is the smallest wrong interleaving. counter++ looks like one operation. The CPU runs it as three: load the value, add one, store it back. Put two threads on one core. Thread A loads 41. The timer fires. Thread B loads 41, adds one, stores 42. A resumes, adds one to its stale 41, and stores 42. Two increments ran. The counter moved once.

That is a story. Here is the same bug at scale. The program below starts two threads that each run counter++ five million times. It runs them three ways: both threads pinned to one CPU, one thread per CPU, and with an atomic increment. It prints how many of the 10 million increments vanished, in six runs each. The plain counter is volatile so the compiler keeps the load, the add and the store.
// lost_update.c: two threads run counter++ five million times each. How many increments vanish?
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdio.h>
#define N 5000000L
static volatile long plain; // volatile: every ++ is a real load, add, store
static atomic_long safe;
struct job { int cpu, use_atomic; };
static void *worker(void *arg) {
struct job *j = arg;
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(j->cpu, &set);
sched_setaffinity(0, sizeof set, &set);
if (j->use_atomic)
for (long i = 0; i < N; i++) atomic_fetch_add(&safe, 1);
else
for (long i = 0; i < N; i++) plain++;
return 0;
}
static long trial(int cpu_a, int cpu_b, int use_atomic) {
plain = 0;
safe = 0;
struct job a = {cpu_a, use_atomic}, b = {cpu_b, use_atomic};
pthread_t ta, tb;
pthread_create(&ta, 0, worker, &a);
pthread_create(&tb, 0, worker, &b);
pthread_join(ta, 0);
pthread_join(tb, 0);
return use_atomic ? safe : plain;
}
int main(void) {
struct { const char *name; int a, b, at; } cfg[] = {
{"plain, both threads on CPU 0", 0, 0, 0},
{"plain, one thread per CPU ", 0, 1, 0},
{"atomic, one thread per CPU ", 0, 1, 1},
};
printf("expected total per run: %ld\nlost increments in six runs:\n", 2 * N);
for (int c = 0; c < 3; c++) {
printf(" %s:", cfg[c].name);
for (int r = 0; r < 6; r++) printf(" %8ld", 2 * N - trial(cfg[c].a, cfg[c].b, cfg[c].at));
printf("\n");
}
return 0;
}
$ ./lost_update
expected total per run: 10000000
lost increments in six runs:
plain, both threads on CPU 0: 5000000 3597705 5000000 3800375 1832694 5000000
plain, one thread per CPU : 4823275 4822688 4560636 4474099 4505360 4656242
atomic, one thread per CPU : 0 0 0 0 0 0
Check the loop first. This is what the compiler emitted for the plain increment:
$ objdump -d lost_update # the plain++ loop inside worker()
14c0: mov 0x2b59(%rip),%rax # 4020 <plain>
14c7: add $0x1,%rax
14cb: mov %rax,0x2b4e(%rip) # 4020 <plain>
Load, add, store. Three instructions, so an interrupt can land between any two of them.
Now the numbers. On one core, with no parallelism at all, between 1.8 million and 5.0 million of the 10 million increments disappeared. Three of six runs lost exactly 5,000,000, which is one thread’s entire contribution. How? A thread loaded a stale value and got preempted, and the other thread ran to completion. The first thread resumed, stored its stale value plus one, and carried on from there. One badly timed interrupt erased the other thread’s whole slice. On two cores the loss was 4.5 to 4.8 million in every run. The atomic version lost nothing, six times out of six.
So concurrency without parallelism is already enough. And the loss does not scale with how often the bad interleaving happens. It scales with how much work sat between the load and the stale store.
A toy, yes. The class of bug is not. Between June 1985 and January 1987, six known accidents involved massive overdoses from the Therac-25 radiation therapy machine, with deaths and serious injuries. Leveson and Turner’s investigation, published in IEEE Computer in July 1993, found race conditions in how the software handled operator input among the causes. They also refused the single-cause story. Poor software design, overconfidence in the software and slow responses to complaints all contributed. Concurrency bugs rarely arrive alone.
What a switch costs
To run B after A, the kernel saves A’s registers, program counter and stack pointer, restores B’s, and, if B belongs to a different process, switches the page-table base so B sees its own address space. That is the direct cost.
Tsuna measured it by bouncing a futex between two threads. On Intel parts from the 2010 to 2012 era, a switch pinned to one core took roughly 1,300 to 1,900 nanoseconds between processes and 1,100 to 1,700 between threads. Unpinned, it rose to 3,000 to 4,500. At 3 GHz, 1.3 microseconds is 3,900 cycles, and 4.5 microseconds is 13,500.
My version of that experiment bounces one byte between two threads through a pair of pipes. Each round trip is two hand-offs. I ran it pinned to one CPU and across two.
// ctxswitch.c: two threads bounce one byte through two pipes. One round trip is two hand-offs.
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define ROUNDS 200000
static int ab[2], ba[2], cpu_a, cpu_b;
static void pin(int cpu) {
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
sched_setaffinity(0, sizeof set, &set);
}
static void *peer(void *unused) {
char c;
pin(cpu_b);
for (int i = 0; i < ROUNDS; i++) {
read(ab[0], &c, 1);
write(ba[1], &c, 1);
}
return 0;
}
static double bench(int a, int b) {
cpu_a = a; cpu_b = b;
pipe(ab); pipe(ba);
pthread_t t;
pthread_create(&t, 0, peer, 0);
pin(cpu_a);
char c = 'x';
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int i = 0; i < ROUNDS; i++) {
write(ab[1], &c, 1);
read(ba[0], &c, 1);
}
clock_gettime(CLOCK_MONOTONIC, &t1);
pthread_join(t, 0);
close(ab[0]); close(ab[1]); close(ba[0]); close(ba[1]);
double ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
return ns / (2.0 * ROUNDS);
}
int main(void) {
for (int r = 0; r < 3; r++)
printf("run %d: same CPU %5.0f ns per hand-off | two CPUs %5.0f ns per hand-off\n",
r + 1, bench(0, 0), bench(0, 1));
return 0;
}
$ ./ctxswitch
run 1: same CPU 1008 ns per hand-off | two CPUs 12785 ns per hand-off
run 2: same CPU 993 ns per hand-off | two CPUs 12514 ns per hand-off
run 3: same CPU 1097 ns per hand-off | two CPUs 13612 ns per hand-off
Pinned to one CPU, a hand-off cost 993 to 1,097 nanoseconds. That includes a read and a write system call, so it overstates the switch itself, but it lands in the same range as Tsuna’s pinned figures. Across two CPUs it jumped to 12.5 to 13.6 microseconds, about twelve times worse. Tsuna saw the unpinned case cost roughly 2.3 times the pinned one on bare metal. I did not isolate why my VM pays more. A wakeup on another CPU needs an inter-processor interrupt, and virtualization generally makes interrupts costlier, which is a Post 4 problem. The lesson survives either way: where a thread runs changes what a switch costs.
Two warnings. Tsuna’s numbers come from old hardware, and mitigations for speculative-execution flaws have since moved direct costs around, so read them as microseconds, not nanoseconds and not milliseconds. And the thread-versus-process gap is roughly 10% to 15%. “Threads are cheap, processes are heavy” is a statement about sharing memory, not about switch speed.
The bigger bill is indirect. After a switch, B’s data is not in the cache and its address translations are not in the TLB. Changing the page-table base flushes the TLB on CPUs that do not tag entries, and tagging, called PCID on x86, only softens the blow. Tsuna cites Li and colleagues at Rochester, who found the cost rising by up to two orders of magnitude once a working set passed about half the L2 cache. His own rough estimate, which he presents as an estimate, puts the full overhead near 30 microseconds. Direct cost < indirect cost.
Why does that number control scheduler design? Because of the slice. The next section runs the arithmetic.
Who runs next?
OSTEP builds scheduling policy in layers across chapters 7 to 10, and the order is worth knowing because each policy answers the failure of the one before it.
First-in-first-out is simple, and one long job at the front makes everything behind it wait. Shortest-job-first fixes the average wait but needs a prediction of the future that the OS does not have. Round robin cuts response time by slicing, and it stretches turnaround. The multi-level feedback queue guesses the future by watching behavior: jobs that give up the CPU early stay at high priority, and jobs that burn whole slices sink. Proportional-share schedulers drop the guess and ask who is owed what.
Put numbers on the first trade-off. The script below runs four CPU-bound tasks of 100 milliseconds each through FIFO and round robin on one core. It charges 30 microseconds per switch, the rough full estimate from Tsuna, on top of each slice. It is a model of the policies, not of Linux.
# rr_overhead.py: what do time slices cost? Four CPU-bound tasks of 100 ms on one core. A model of the policies.
SWITCH_US = 30 # cost of one switch, direct plus indirect (Tsuna's rough estimate)
def fifo(n=4, work=100_000, c=SWITCH_US):
t, first, done = 0, [], []
for _ in range(n):
t += c; first.append(t); t += work; done.append(t)
return first, done, n * c / t
def round_robin(q, n=4, work=100_000, c=SWITCH_US):
rem, t, first, done, switches = [work] * n, 0, [None] * n, [None] * n, 0
while any(rem):
for i in range(n):
if rem[i]:
t += c; switches += 1 # pay the switch, then run one slice
first[i] = first[i] if first[i] is not None else t
run = min(q, rem[i]); t += run; rem[i] -= run
if not rem[i]: done[i] = t
return first, done, switches * c / t
print("four CPU-bound tasks of 100 ms each, one core, switch cost 30 us")
print(f"{'policy':14} {'avg response':>13} {'avg turnaround':>15} {'time lost to switches':>22}")
rows = [("FIFO", fifo())] + [(f"RR q={q / 1000:g} ms", round_robin(q)) for q in (100, 1_000, 3_000, 10_000)]
for name, (first, done, lost) in rows:
print(f"{name:14} {sum(first) / len(first) / 1000:10.1f} ms {sum(done) / len(done) / 1000:12.1f} ms {100 * lost:20.1f} %")
four CPU-bound tasks of 100 ms each, one core, switch cost 30 us
policy avg response avg turnaround time lost to switches
FIFO 150.1 ms 250.1 ms 0.0 %
RR q=0.1 ms 0.2 ms 519.8 ms 23.1 %
RR q=1 ms 1.6 ms 410.5 ms 2.9 %
RR q=3 ms 4.6 ms 402.5 ms 1.0 %
RR q=10 ms 15.1 ms 386.2 ms 0.3 %
FIFO wins turnaround and loses response. The average task waits 150 milliseconds before it first runs and finishes after 250. Round robin with a 100 microsecond slice answers in 0.2 milliseconds and pays 23.1% of the core to switching, and its average turnaround is more than double FIFO’s, 519.8 against 250.1. At a 3 millisecond slice the loss falls to 1.0% and the first answer arrives after 4.6 milliseconds. Short slices buy responsiveness and pay for it in throughput. Every scheduler is a position on that curve.

Linux’s answer for ordinary tasks descends from that last idea. The Completely Fair Scheduler arrived in Linux 2.6.23 in October 2007. Each task has a weight derived from its nice value. The scheduler tracks virtual runtime, the weighted CPU time a task has consumed. Run whoever has had the least.
How big is a nice step? Measure it. The script below starts two busy loops on one CPU, one at nice 0 and one at nice 5, and reads how much CPU time the scheduler gave each.
# nice_weights.py: each nice level is a weight. Two busy loops on one CPU, nice 0 against nice 5.
import subprocess, time
def spin(nice):
return subprocess.Popen(["taskset", "-c", "0", "nice", "-n", str(nice), "python3", "-c", "while True: pass"])
def run_ns(p): # CPU time the scheduler has given this process
return int(open(f"/proc/{p.pid}/schedstat").read().split()[0])
a, b = spin(0), spin(5)
time.sleep(0.5) # let both start
before = [run_ns(a), run_ns(b)]
time.sleep(3)
ta, tb = (run_ns(a) - before[0]) / 1e9, (run_ns(b) - before[1]) / 1e9
a.kill(); b.kill()
print(f"nice 0 got {ta:.2f} s ({100 * ta / (ta + tb):.0f}%), nice 5 got {tb:.2f} s ({100 * tb / (ta + tb):.0f}%)")
print(f"measured ratio {ta / tb:.2f}; five steps of 1.25 would give {1.25 ** 5:.2f}")
nice 0 got 2.26 s (75%), nice 5 got 0.74 s (25%)
measured ratio 3.05; five steps of 1.25 would give 3.05
75% to 25%, a ratio of 3.05. Five nice levels at a factor of 1.25 each also give 3.05. So “each nice level shifts the weight by about 25%” is not folklore. You just measured it.
Ordinary tasks are only one tier. Real-time and deadline classes sit above the fair class and win whenever they have work. The fair class is where your editor and your web server live, and this series cares about it.
In October 2023, Linux 6.6 changed how the choice gets made. EEVDF, Earliest Eligible Virtual Deadline First, kept weights, accounting, group scheduling and load balancing, and replaced the pick-the-smallest rule. Each task carries a lag: how much CPU it is owed against its fair share. A task with lag at or above zero is eligible. Among eligible tasks, the scheduler runs the one with the earliest virtual deadline, roughly its start time plus its requested slice scaled by weight. A task that asks for a shorter slice gets an earlier deadline and runs sooner, without receiving more CPU overall. Four equal tasks still get 25% each (LWN).
Here is that rule as a toy. The script keeps a weighted virtual runtime per task, computes the fair virtual time as the weighted average, treats a task as eligible when it sits at or behind that average, and runs the eligible task with the earliest virtual deadline. Four tasks, one second of CPU. In the second run, task S asks for a 0.5 millisecond slice while the others ask for 3. This is a toy: equal weights, tasks that never sleep, and none of the wakeup logic the real scheduler has.
# eevdf_toy.py: run the eligible task with the earliest virtual deadline. A toy: equal weights, tasks always runnable.
class Task:
def __init__(self, name, slice_us, weight=1):
self.name, self.slice, self.w = name, slice_us, weight
self.v, self.cpu, self.starts = 0.0, 0, [] # v: virtual runtime, weighted CPU time consumed
self.vd = self.v + slice_us / weight # virtual deadline = eligible time + slice / weight
def eevdf(tasks, horizon_us):
t = 0
while t < horizon_us:
V = sum(k.v * k.w for k in tasks) / sum(k.w for k in tasks) # the fair virtual time
ready = [k for k in tasks if k.v <= V + 1e-9] # eligible: lag >= 0
k = min(ready, key=lambda x: x.vd) # earliest virtual deadline wins
k.starts.append(t); k.cpu += k.slice; t += k.slice
k.v += k.slice / k.w
k.vd = k.v + k.slice / k.w # a new request begins
return t
def report(title, tasks):
horizon = eevdf(tasks, 1_000_000)
print(f"\n{title}")
print(f" {'task':5} {'share':>7} {'slices':>7} {'longest wait':>13}")
for k in tasks:
waits = [b - (a + k.slice) for a, b in zip(k.starts, k.starts[1:])]
print(f" {k.name:5} {100 * k.cpu / horizon:6.1f}% {len(k.starts):7d} {max(waits) / 1000:10.1f} ms")
report("all four tasks request 3 ms slices", [Task(n, 3000) for n in "SABC"])
report("S requests 0.5 ms, the others 3 ms", [Task("S", 500)] + [Task(n, 3000) for n in "ABC"])
all four tasks request 3 ms slices
task share slices longest wait
S 25.1% 84 9.0 ms
A 25.1% 84 9.0 ms
B 24.9% 83 9.0 ms
C 24.9% 83 9.0 ms
S requests 0.5 ms, the others 3 ms
task share slices longest wait
S 25.0% 500 3.0 ms
A 25.2% 84 9.0 ms
B 24.9% 83 9.0 ms
C 24.9% 83 9.0 ms
Every task ends with about 25% of the CPU in both runs. Asking for a short slice did not buy S more. It bought S a different schedule: 500 short slices instead of 84 long ones, and a longest wait of 3.0 milliseconds instead of 9.0. That is the point of the change. A latency-sensitive task can say so, and the kernel can honor it without bending fairness.

Was it free? No. Ingo Molnar’s merge note warned that the switch would shift behavior sharply for some workloads, and that adversarial loads that had gotten lucky under the old code, some hackbench variants among them, would regress (Phoronix).
When does the scheduler get to choose?
Post 1 said the tick is a guarantee, not the only trigger. Here are the real triggers. A task blocks on I/O. A task yields. A wakeup makes a better candidate eligible. The tick shows that the current task has used its slice. An inter-processor interrupt arrives from another core. Linux marks the running task with a need-reschedule flag, TIF_NEED_RESCHED, and the switch happens at the next safe point.
Not every switch is forced. A thread that waits for a disk read or a lock hands over the core voluntarily, and the timer only has to deal with programs that never stop. /proc/<pid>/status keeps both counters, voluntary_ctxt_switches and nonvoluntary_ctxt_switches. A process that mostly waits piles up the first. A busy loop piles up the second.
So a time slice is not a fixed number the scheduler hands out and then waits on. It is a request with a deadline attached. If you take one correction from this post, take that one: “CFS gives every task a fixed time slice” was never accurate.
Run it yourself, with better tools than mine
The samples above are small on purpose. Read the kernel’s sched-stats document for what /proc/schedstat reports, use runqlat from Brendan Gregg’s eBPF page to see how long tasks wait for a CPU, and build Tsuna’s contextswitch benchmark to compare with my pipe version.
What to carry forward
One core runs one thread at a time. The scheduler’s whole job is making that fact invisible, and the price of the illusion is measured in microseconds, cache lines and deadlines. The Wasted Cores bugs live one level up, in how threads get spread across cores. Post 3 puts more cores on the table, and the new problems that come with them.
Takeaways
- Concurrency structures a program; parallelism runs it on several execution units at once, and one core gives you only the first.
counter++is three instructions, and one preemption between the load and the store can erase a whole slice of the other thread’s work.- A switch costs microseconds directly and often more in cold caches and TLBs, and where the thread runs changes the price.
- Slice length trades response against throughput: 23.1% lost at 100 microseconds, 1.0% at 3 milliseconds, in the model.
- CFS ran the task with the least virtual runtime; EEVDF runs the eligible task with the earliest virtual deadline.
- Pin a loop to one CPU and measure, because the machine will correct what you assumed.
Published November 22, 2026