← All lessons
How context switching works
Three tasks, one core
Editor
Kernel
Compiler
Editorvol 0 · invol 0
Compilervol 0 · invol 0
Musicvol 0 · invol 0
tasks.c
// the editorn = read(fd, buf, 4096); // sleeps here until the disk answers // the compiler never waits for anythingfor (;;) parse(next_token());kernel/sched/core.c
void schedule(void) { struct task *prev = current; if (prev->state != TASK_RUNNING) prev->nvcsw++; // the task is waiting: voluntary else prev->nivcsw++; // still runnable, so it was preempted struct task *next = pick_next_task(rq); // furthest behind on its fair share if (next->mm != prev->mm) switch_mm(prev->mm, next->mm); // load CR3 switch_to(prev, next); // save prev's registers, load next's} // every timer tickif (curr->ran >= curr->slice) resched_curr(rq); // later, in the disk interruptwake_up_process(editor); // back in the run queuePick a time slice short feels smooth, long wastes less
One round on the core one switch
lost
worst wait
per task
switches/s
Linux uses slices of a few ms and stretches them on machines with more cores
round.js
// n tasks each take one slice, with a switch between eachconst round = n * (slice + cost); // share of the CPU lost to switchingconst lost = cost / (slice + cost); // how long a task waits for its next turnconst wait = (n - 1) * slice + n * cost;Thread or process decides how much a switch throws away
What the switch does
kernel/sched/core.c
void context_switch(struct task *prev, struct task *next) { if (next->mm != prev->mm) { // with PCID, CR3 can keep old TLB entries switch_mm(prev->mm, next->mm); } // threads share mm, so this is skipped switch_to(prev, next);}Topics
Next: How hash tables work
Open lesson