Skip to content

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

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