Electronic – the difference between context switching and interrupt handling

interruptslinuxmicrocontrollerosrtos

I'm an embedded developer. I haven't worked with RTOS/linux. I was going through RTOS concepts when I stumbled upon 'context switching'. I understand that when context switch occurs, all the registers along with PC(Program Counter) gets saved in stack before another thread is loaded to the processor. Isn't a similar thing happening when an interrupt occurs(in a controller which doesn't use any kind of OS)?

How different are those two terms?

Best Answer

There isn't a fundamental difference, it's more a question of degree — the amount of context that needs to be saved.

When an RTOS thread context switch occurs, all of the CPU state that any thread might use must be saved. This usually includes all of the CPU registers, including flag or status registers, so that when they're restored, the thread resumes as though nothing ever happened.

When an interrupt occurs, there's still a context switch, but only the context that the interrupt handler actually needs to use needs to be saved and then subsequently restored. If you write your interrupt handler in a high-level language, this will pretty much be equivalent to a full thread context switch, because there are no constraints on what resources such an interrupt handler might touch. However, if you write your interrupt handler in assembly language, you can keep track of exactly which registers it touches and save only those. This allows the execution of the interrupt handler to be extremely fast, reducing its impact on the rest of the system, and/or allowing it to handle interrupts at a higher rate.