Skip to content

Instantly share code, notes, and snippets.

@chris-short
Created December 18, 2022 15:16
Show Gist options
  • Save chris-short/c4275cac5d194312d4bf3a896544b69d to your computer and use it in GitHub Desktop.
Save chris-short/c4275cac5d194312d4bf3a896544b69d to your computer and use it in GitHub Desktop.

A context switch is the process of storing and restoring the state of a CPU or a device so that multiple tasks can share the same hardware resources. In a computer operating system, a context switch occurs when the operating system kernel switches the execution of a task from one process to another.

When a context switch occurs between the kernel and user space, it can be more expensive in terms of performance because it requires the kernel to perform additional tasks. These tasks include:

Saving and restoring the state of the CPU registers, including the program counter, stack pointer, and any other relevant registers.

Saving and restoring the kernel stack, which is used to store temporary data and function calls made by the kernel.

Updating the process control block (PCB) for the current process to reflect the new state of the task.

Updating the memory management unit (MMU) to reflect the new memory mapping for the process.

The cost of a context switch depends on the hardware and software architecture of the system. In general, context switches are faster on systems with a fast cache, a large number of registers, and a small kernel.

There are several techniques that can be used to reduce the performance cost of context switches, including using fast system calls, minimizing the number of kernel entry and exit points, and using real-time scheduling algorithms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment