You are on page 1of 12

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, pre-
emptive 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 e-
mail 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) Save context of processor including program
counter and other registers.
2) Update the PCB of the running process with
its new state and other associate information.
3) Move PCB to appropriate queue – ready,
blocked
4) Update PCB of the selected process.
5) 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
Interrupt User and kernel
Multitasking
handling mode switching
•When the CPU •When the CPU •When
needs to switch is interrupted to switching
processes in return data between user
and out of from a disk mode to kernel
memory, so read. mode, it may
that more than be used.
one process
can be
running.
Context
switch in
Round
Robin

You might also like