Context Switch
Introduction

A context switch is when the CPU stops executing one process and starts executing another
Before stop executing, CPU will save the current executing context into the process. This way, CPU can continue the process in the next time slice for this process
When to switch?
Voluntarily Context Switch
- Call yield() to yield CPU
- Call sleep()
- Request I/O, request to lock/semaphore, makes a system call that blocks, etc.
Involuntarily Context Switch
- Process/thread scheduler tries to share CPU fairly by time-slicing.
- Suspend/resume at periodic intervals
- Involuntary context switches can happen “any time”
Cost of Context Switch
Direct Cost
Load and store current process status to PCB, then load next process status to CPU
Indirect Cost (HOT/COLD Cache)
CPU will load frequently used data and instruction into cache. Thus no need to fetch them from main memory. This is called “HOT Cache”
However, when we do context switch. The original cache has nearly no usage for the new process, and CPU need to fetch data/instructions from main memory. We call this “COLD Cache”