Part 5 of 6 · 2 min read
Switch kinds
Two kinds of context switch
In plain words: The kernel counts how often a process lost the processor. Linux keeps two numbers in /proc/PID/status. A voluntary switch happens when the process gives up the processor by waiting, for example for I/O or a sleep. A non-voluntary switch happens when the kernel takes the processor away, because the time slice is over or a more important process is ready.
This program prints both counters, sleeps five times for one millisecond each, and prints them again:
voluntary_ctxt_switches: 0
nonvoluntary_ctxt_switches: 0
voluntary_ctxt_switches: 5
nonvoluntary_ctxt_switches: 0
Five sleeps made five voluntary switches. Each sleep moved the process from running to waiting, which also means the processor was handed to somebody else. A process that computes without ever waiting, like the loop in the last section, collects non-voluntary switches instead, since the timer interrupt ends its slices.
The ratio is a useful health sign. Many voluntary switches mean a process spends its life waiting, as an input-heavy program does. Many non-voluntary switches mean it is hungry for the processor, as a number-crunching program is.
Interview angle
Answer in your head first, then open it.
What are the process states?
New, ready, running, waiting and terminated, with the arrows between them.
Which events move a process between them?
Dispatch, timer interrupt, wait for I/O, I/O completion and exit.
What is in a PCB?
State, PID, program counter, registers, scheduling, memory, accounting and I/O information, and family links.
What is the difference between waiting and ready?
A waiting process needs an event and cannot use a processor. A ready one only needs the scheduler.
Check yourself:
1. A process calls sleep(1). Which kind of switch is that?
2. A loop that never waits is cut off by a timer. Which kind is that?
3. What does a high count of voluntary switches suggest about a process?
Words you will meet
| Word | Meaning |
|---|---|
| Ready, running, waiting | The main process states |
| Dispatch | Giving a ready process the processor |
| Blocked | Another word for waiting |
| PCB | The kernel's record of a process |
task_struct |
The Linux PCB |
| Voluntary and non-voluntary switch | Giving up the processor, and losing it by force |
Quick notes
- A process state is the value, kept in the process control block, that says what a process is currently doing with respect to the processor: new, ready (waiting for a.
- A process control block (PCB) is a record kept by the kernel for each process.