11.3 OS Scheduling and Context Switches
The operating system decides which thread runs on which CPU core and when to switch threads. This decision affects latency, throughput, and cache performance. The OS scheduler makes thousands of decisions per second. Understanding the costs of context switches and the heuristics of scheduling explains why oversubscription hurts performance.
11.3.1 Mental model
A CPU core, or one hardware thread of a core that runs two at once, can run one software thread at a time. A modern machine has multiple cores. A running program can have far more threads than cores. The scheduler decides which thread runs on which core and for how long. The scheduler switches threads frequently, every few milliseconds. Each switch is a context switch.
A context switch does three things. The OS saves the registers of the running thread, restores the registers of the new one, then jumps to its program counter. The new thread continues from where it last paused.
To the thread, this switching is invisible. The thread has no idea when it is paused and resumed. The system appears to be running multiple threads in parallel.
The scheduler has different modes depending on system demand. If there are fewer runnable threads than cores, threads run continuously on their cores. If there are more runnable threads than cores, threads share cores and context switches happen constantly.
11.3.2 Mechanism
Runnable threads and the ready queue
The kernel maintains a queue of runnable threads, the ready queue. A thread is runnable if it is not blocked waiting for I/O or a lock. Threads enter the ready queue when they are created or wake from a wait, and leave it when they are picked to run or when they block.
The scheduler picks the next runnable thread according to its policy. Many schedulers, including the textbook multilevel feedback queue, use priorities that change over time: a thread that blocks often, such as an interactive one, keeps a higher priority than a thread that uses up its whole time slice. Linux uses a fair-share design instead, described below. Either way, the aim is for latency-sensitive work to run soon after it becomes runnable.
Time slicing and preemption
Each thread gets a time slice of a few milliseconds. On Linux 6.15 and later the default base slice is 0.7 ms (0.75 ms from 6.6 to 6.14), multiplied by one plus the base-2 logarithm of the CPU count, with the count capped at 8, which gives about 2.8 ms on a machine with 8 or more CPUs (3 ms before 6.15) (kernel/sched/fair.c). When the time slice ends, a timer interrupt fires. The scheduler’s interrupt handler saves the current thread’s registers and picks the next thread from the ready queue. The new thread resumes.
Interrupts are asynchronous. The scheduler can preempt a thread between any two of its instructions. From the thread’s perspective, it was running and then suddenly control jumped to the next instruction after a gap of unknown duration. Synchronization primitives like mutexes account for these gaps.
Context switch overhead
A context switch has direct and hidden costs. The direct cost is the kernel’s own work: enter the kernel, save one thread’s registers, load the other’s, and, if the new thread belongs to a different process, switch to that process’s page tables. Li, Ding and Shen measured an average direct cost of 3.8 microseconds on a 2007 Linux machine. Hardware has changed since, so read that figure as an order of magnitude (microseconds), not as a current number.
The hidden costs are cache effects. When a thread runs, its working set populates the L1, L2, and L3 caches. The thread reads and writes memory using this cached data. When the thread is preempted and another runs, the new thread’s working set is not in the caches, so its first accesses miss. The caches refill as it touches its data again, and in doing so evict the data of the thread that ran before.
The refill is often the larger cost. In the same study, the indirect cost of a switch ranged from several microseconds to more than a thousand, depending on how much data the workload touched. For memory-bound code, this effect is severe. For computation-bound code, the effect is smaller.
CPU affinity
Schedulers try to run a thread on the core it last ran on, since some of its data may still be in that core’s caches. A program can also pin a thread to chosen cores, on Linux with sched_setaffinity or the taskset command, and the scheduler then never moves it elsewhere.
Pinning is not always beneficial. It helps when each pinned thread has a core to itself. Under oversubscription it backfires: a pinned thread cannot move to an idle core, so threads pinned to the same core take turns on it while other cores sit idle.
The switch itself is short. The larger cost comes after it, while thread B’s working set refills the caches.
11.3.3 Oversubscription and the sleep cost
When there are more runnable threads than cores, the scheduler must time-slice. Each thread gets a few milliseconds. The scheduler picks the next thread. Context switches happen constantly.
Oversubscription hurts performance. Every thread does less work before being preempted. Latency-sensitive work suffers. Cache effects become severe. Threads spend time being preempted and waiting for the scheduler to pick them again.
A sleep, blocking on a mutex or I/O, removes the thread from the ready queue. It stops consuming time slices. When the wait completes, the thread reenters the ready queue. If the scheduler is oversubscribed, the thread waits behind many others. Latency increases.
This is one reason that a thread pool is better than creating a thread per task. A thread pool has a fixed small number of threads. The pool adds tasks to a queue, and idle threads block on the queue until a task arrives. No thread is created per task, the thread count stays fixed, and the scheduler is not oversubscribed, so there are fewer context switches.
11.3.4 Idle cores and spinning
If all cores are idle and one thread is runnable, the scheduler runs that thread on an idle core immediately, and nothing competes with it for that core.
But if a thread is in a busy loop, spinning on a lock, it does not sleep. It keeps consuming CPU cycles. The scheduler keeps it running. If the system is otherwise idle, the spinning thread can run uninterrupted, and cache effects are minimal.
Spinning is a tradeoff. It wastes CPU time but avoids context switch latency. For short waits, spinning is faster. For long waits, sleeping is more efficient.
11.3.5 Other systems
Linux used the Completely Fair Scheduler (CFS) from 2.6.23 until 6.6, when it began moving to EEVDF. CFS tracks each thread’s virtual runtime, the CPU time it has used weighted by its priority, and always runs the thread with the smallest. A thread that sleeps falls behind in that count, so it runs soon after it wakes. EEVDF keeps the weighted fair share and adds a virtual deadline per thread, so a thread that asks for shorter slices gets an earlier deadline and runs sooner.
macOS uses an array of priority queues. Windows similarly has priority-based scheduling. Both systems allow real-time threads with higher priority than normal threads. Real-time threads preempt normal threads.
Go’s runtime runs many goroutines on a small number of OS threads. The OS scheduler runs those threads, and the Go scheduler decides which goroutine each of them executes, so switching from one goroutine to another needs no OS context switch.
Rust has no runtime scheduler. Rust programs use the OS scheduler directly. Some libraries add schedulers. tokio is a Rust async runtime that uses work-stealing scheduling. The tokio scheduler makes scheduling decisions without OS context switches, reducing overhead.
11.3.6 R’s approach
GNU R evaluates R code on one thread. R starts a helper thread only in narrow cases, such as the timer thread behind elapsed-time profiling with Rprof() (src/main/eval.c). R’s main thread is preempted by the OS scheduler like any other thread. R has no scheduler of its own, and it gives up the core only by blocking, for example in Sys.sleep() or on input. What R controls is when it does its own housekeeping: the garbage collector runs during allocation, and the evaluator checks for a user interrupt about every thousand evaluation steps.
Packages add native threads. Multithreaded BLAS uses threads to parallelize matrix operations. OpenMP code uses threads. These threads run below the R API and do not interact with the R interpreter directly. They do their work while R’s main thread waits inside the call, and wait between calls, spinning for a short time before they sleep.
sunlight uses fork, which creates new processes. Each worker is a process, not a thread. The kernel scheduler schedules processes. Oversubscription hurts similarly. Starting 32 worker processes on a 4-core machine means the scheduler switches between workers constantly. Performance degrades. The practical approach is to match worker count to core count.
11.3.7 Tradeoffs
Context switches have real costs. Direct costs are small (microseconds). Indirect cache costs are larger: around a hundred nanoseconds for each miss that goes to main memory, multiplied by many misses. Affinity helps. Avoiding oversubscription helps. Fewer, longer-running threads are faster than many short-running threads.
Too few threads has its own cost. With fewer runnable threads than cores, some cores sit idle, and a thread that blocks on I/O leaves its core with nothing to run. Each thread then runs undisturbed, but total throughput drops.
Further reading
- Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces <https://pages.cs.wisc.edu/~remzi/OSTEP/>. Free online. See the chapters “Scheduling: Introduction”, “The Multi-Level Feedback Queue” and “Multiprocessor Scheduling (Advanced)”.
- Linux kernel documentation, Scheduler <https://docs.kernel.org/scheduler/index.html>, including the CFS <https://docs.kernel.org/scheduler/sched-design-CFS.html> and EEVDF <https://docs.kernel.org/scheduler/sched-eevdf.html> design notes.
- Li, C., Ding, C. and Shen, K. (2007). Quantifying the cost of context switch <https://www.cs.rochester.edu/u/kshen/papers/expcs2007.pdf>. Workshop on Experimental Computer Science (ExpCS ’07). The source of the direct and indirect costs above.
- Gregg, B. (2020). Systems Performance: Enterprise and the Cloud, 2nd edition <https://www.brendangregg.com/systems-performance-2nd-edition-book.html>. Addison-Wesley. Chapter 6, “CPUs”, covers CPU scheduling with practical tools.
- Bakhvalov, D. (2024). Performance Analysis and Tuning on Modern CPUs <https://github.com/dendibakh/perf-book>, 2nd edition, free online. Covers measuring cache misses and other CPU effects.