一次 context switch(上下文切换)是 kernel 保存当前运行线程的 CPU 状态(寄存器、program counter、stack pointer)并恢复另一个线程的状态,从而让单个 core 能多路复用许多线程。它在每次 scheduler 抢占、阻塞 syscall 或 interrupt 时发生——而且它并不免费。
成本藏在哪里
text
DIRECT cost (visible, ~1–5 µs):
save/restore registers · run scheduler logic · switch kernel stacks
if PROCESS switch: also swap page tables (CR3) → FLUSHES the TLB
INDIRECT cost (often much larger):
cold CPU CACHES → the new thread's data isn't in L1/L2/L3 → cache misses to RAM
cold TLB → address translations must be re-walked
lost pipeline / branch-predictor state
成本是几微秒。成本——切换后冷掉的 cache 和 TLB——常常是更大的那一击:新进来的线程会慢跑一阵,因为它要从主存重新预热自己的 cache(每次 miss 几十到几百个 cycle)。
