4
votes

In my Operatingsystems class, one of the questions to know for the exam is "Why is context switching expensive?" What do they mean by expensive, and expensive in terms of what? In terms of time it takes to execute the task?

2
Get the reference manual for a processor -- say something from the 80x family. Study it to find all the registers that are a part of the processor "state", including any that are used to control address translation, etc. Figure out the instruction sequence needed to save/restore these registers, keeping in mind that any scheme used must be "atomic" -- it cannot allow other operations going on at the same time to change it's results.Hot Licks

2 Answers

4
votes

"Why is context switching expensive?" What do they mean by expensive, and expensive in terms of what? In terms of time it takes to execute the task?

There are several reasons for the overhead of context switching.

First,the steps for saving the context itself takes a lot of effort. All the process registers have to be saved. That includes the general registers, process state registers, and on some systems specialized registers (e.g., floating point).

Second, restoring the context for the new process is equally time consuming.

Third, memory caches have to be flushed and reloaded for the new process.

Fourth, there is overhead in determining what process to execute next.

(And probably some others that I have not listed).

All of this takes time.

2
votes

Expensive in terms of time.

A context switch is the process of storing and restoring the state (context) of a process.

So the OS does actually take "a photograph" of the process, stores it and is able to restore it later, but this is costly.

That procedure will take up some space as well, but the most expensive aspect of it is the time.