CSOS & ConcurrencyDiagramIntermediate
Context Switching
KO: 컨텍스트 스위칭 (문맥 교환)·EN: Context Switching·JA: コンテキストスイッチ
The kernel operation of saving a running task's CPU registers and state into its PCB/TCB and restoring another task to resume execution
Table of Contents
Structure Diagram
CPU Context Switching Execution & Overhead Timeline
CPU Core 0 Timeline5 steps
STEP 1Process A(35ms)
Quick Answer
What is Context Switching?
The kernel operation of saving a running task's CPU registers and state into its PCB/TCB and restoring another task to resume execution. It is a core concept in OS & Concurrency within CS.
Core Principles
Context Switching enables multitasking by pausing a running process or thread, saving its registers and execution state into its PCB/TCB, and loading another task's state onto the CPU.
- Triggers: Preemptive timer ticks, blocking I/O waits, lock contention, or system calls.
- Hidden Indirect Cost: Saving registers takes only microseconds, but switching processes pollutes CPU L1/L2 caches and flushes the TLB, causing expensive cache-miss cascades afterward.
Practical Takeaways
- More threads can hurt throughput: Spawning thousands of OS threads on an 8-core box wastes cycles on switching and cache thrashing. Size CPU-bound pools near core count.
- Prefer user-space concurrency for I/O: Event loops (
epoll/kqueue) and green threads (Go goroutines, Rust async) switch tasks in user space without kernel transitions. - Monitor involuntary switches: High
nvcswch/sinpidstat -wsignals CPU oversubscription or heavy lock contention.
Notable Examples
- Preemptive OS Multitasking: Linux, macOS, and Windows multiplexing hundreds of processes across a few cores.
- C10K+ Network Servers: Nginx, Go, and Node.js avoiding thread-per-connection switching overhead.