A context switch (sometimes, process switch or a task switch) is the switching of the CPU from one process or thread to another.It is sometimes described as the kernel suspending execution of one process on the CPU and resuming execution of some other process that had previously been suspended.
Context switching can be described in slightly more detail as the kernel (i.e., the core of the operating system) performing the following activities with regard to processes (including threads) on the CPU:
- suspending the execution of one process and storing the CPU’s state (i.e., the context) for that process somewhere in memory, so that, when the scheduler gets back to the execution of the first process, it can restore this state and continue.
- retrieving the context of the next process from memory and restoring it in the CPU’s registers and
- returning to the location indicated by the program counter (i.e., returning to the line of code at which the process was interrupted) in order to resume the process.
Context switches can occur only in kernel mode. Kernel mode is a privileged mode of the CPU in which only the kernel runs and which provides access to all memory locations and all other system resources. Other programs, including applications, initially operate in user mode, but they can run portions of the kernel code via system calls.
A context switch can also occur as a result of a hardware interrupt, which is a signal from a hardware device (such as a keyboard, mouse, modem or system clock) to the kernel that an event (e.g., a key press, mouse movement or arrival of data from a network connection) has occurred.
Context switching can be performed primarily by software or hardware.
Difference between context switch performed by Software and Hardware
|Software Context Switching||Hardware Context Switching|
|Software context switching can be selective and store only those registers that need storing||Hardware context switching stores nearly all registers whether they’re required or not|
|Software context switching allows for the possibility of improving the switching code, thereby further enhancing efficiency, and that it permits better control over the validity of the data that is being loaded. Since only those registers which are valid are loaded in case of Software Context Switch||Not possible with Hardware Context Switching since all the registers are loaded whether they are valid or not.|