TransWikia.com

Context Switch in C in 32-Bit MCU

Electrical Engineering Asked on November 26, 2021

I am trying to understand the concept of ‘Context switch’ in reference to C-language and 32-bit MCUs.

For example if I am programming STM32F407 MCU in C-language using STM32CubeIDE and I want to demonstrate full context switch of the MCU then how could I do that?

Do I need to service an Interrupt request for example an interrupt from a periodic timer? So when I will go into the Timer ISR it would imply that the MCU has experienced a full-context switch while jumping to the ISR (Interrupt Handler).

Or Do I need to make a function call? So that when the MCU jumps into a new function that will mean that the MCU has experienced a full-context switch?

Can anyone explain how can I demonstrate a Context-Switch in C-language?

2 Answers

An interrupt in a Cortex-M CPU would probably count as a context switch by itself. When handling an interrupt, the CPU:

  • Pushes its registers to the stack
  • Saves the address of the next instruction it would have executed.
  • Branches to the address of the ISR.

If "context" means register contents, stack frame, and PC, then an interrupt is a context switch. And when returning from an interrupt, the original "context" is restored.

Answered by Adam Haun on November 26, 2021

Under an RTOS, a context switch means the RTOS changes which task (process) is currently running on MCU. The switch to another task may happen due to user code (e.g. OS call to sleep for some amount of time) or via timer interrupt if a task is running and time slice it was given is used so it is time to run other tasks. Or a task says to OS it is done and next task can run if user calls yield().

The context switch is done by OS code, you don't need to worry about it. Just like coding under Windows or Linux, the CPU cores are switched between tasks automatically by the kernel, and your plain old single threas C program does not need to be aware of it.

Answered by Justme on November 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP