Context Switch
Context Switch When
CPU switches to another process, the system must save the state of the old process and load the saved state for the new process. This is called context switch. Context of process represented in the PCB. Context switch triggered by interrupt, preemptive multitasking, or as part of user/kernel mode switching.
The term “context”, which means the environment that a program runs inside. The address space that the program has, plus the current state of the program’s registers.
•
•
The O.S. does not run like a program! The CPU should be running in user-mode as much as possible: the purpose of a computer is to run programs. The OS kernel is only invoked by an interrupt, exception or system call. It has to handle this as quickly as possible, and get back to user mode and continue to run a program.
Why do we want Context Switch
Because all contemporary system allow for multiprogramming: having multiple programs in memory which take turns to run on the CPU. For example : a file system browser, a web browser, a chat program, a word processor, an email reader etc. The act of context switching can only be performed in kernel mode. Because only in kernel mode can page map be changed.
Step in Context Switching 1)
2) 3) 4) 5)
Save context of processor including program counter and other registers. Update the PCB of the running process with its new state and other associate information. Move PCB to appropriate queue – ready, blocked Update PCB of the selected process. Restore CPU context from that of the selected process.
Context switch between processes 1
Context switch between processes 2
Example of Context Switch
Cost of Context Switching
Context switches are usually computationally intensive, and much of the design of OS is to optimize the use of context switches.
Switches from one process to another requires a certain amount of time for doing the administration – saving and loading register and memory maps, updating various tables and lists, etc.
What is actually involved in a context switch varies between these senses and between processors and Operating systems.
Three potential triggers of Context Switching Multitasking
•When the CPU needs to switch processes in and out of memory, so that more than one process can be running.
Interrupt handling
User and kernel mode switching
•When the CPU is interrupted to return data from a disk read.
•When switching between user mode to kernel mode, it may be used.
Context switch in Round Robin