Context switch¶
Category: Units of execution · Status: stub
One line: Saving one thread's or process's CPU state and loading another's so that it can run; switching between threads is cheaper than between processes, and between async tasks cheaper still.
Also called: task switch.
How it connects¶
flowchart LR
n_context_switch["Context switch"]
n_multitasking["Multitasking"]
n_scheduler["Scheduler"]
n_multitasking -->|uses| n_context_switch
n_scheduler -->|uses| n_context_switch
classDef center stroke-width:3px
class n_context_switch center
classDef outside stroke-dasharray: 4 3
class n_multitasking,n_scheduler outside
- Is used by: Multitasking, Scheduler
- See also: Oversubscription, Preemptive scheduling, Process, Scheduler
In each language¶
| Rust | std::thread::yield_now ↗ gives up the rest of a time slice |
| Go | runtime.Gosched ↗ yields the processor to other goroutines |
| C++ | std::this_thread::yield ↗ |
| Java | Thread.yield ↗, which its documentation says is rarely appropriate to use |
| The operating system | sched_yield(2) ↗; /proc/pid/status ↗ counts a process's voluntary and involuntary switches |
Where to read more¶
- In the books: Java Concurrency in Practice, Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea — ch. 11, 'Performance and Scalability' → 'Reducing Context Switch Overhead'
- Notes: Difference between Thread Context Switch and Process Context Switch ↗
- Notes: context switching - general ↗
- Notes: thread suspension ↗
- Reference: Wikipedia: Context switch ↗