Details on Context Switching

gauravpatni wrote on Sunday, November 15, 2015:

Dear All ,

I have just started exploring FreeRTOS …

I have few queries regarding implementation of “Context Switching” methodology.

  1. Whether all the local variables & array’s are saved in current context switching methodology?
    Eg. In vPortYieldISR: I haven’t found any logic of saving large buffers /arrays .

  2. What will happen if a task has 5K of local array ? how will such a large data is saved in stack ?

Plz reply ….

rtel wrote on Sunday, November 15, 2015:

Every task has its own stack. If the array is on the stack (declared as a non-static function scope variable) then there is no need to save it in the context switch. When the task stops running the stack pointer is updated to point to the stack of the task that has been selected to run. When the original task starts to run again, the stack pointer is restored to its original value, so the task finds the stack (and the array that is on the stack) exactly as it was.


gauravpatni wrote on Tuesday, November 17, 2015:

that means every task keeps its local variable / array ( what ever size it may be ) forever .
And tasks variables /arrays never returns to system ( unlike ordinary functions )
Is it correct?

gauravpatni wrote on Thursday, November 19, 2015:

plz reply

davedoors wrote on Thursday, November 19, 2015:

What more is there to say? Each task is completely separate and has its own stack. If you write an app without freertos, have a variable on the stack, call a function, then when the function returns you dont expect the stack variable to have changed. Same with FreeRTOS.

heinbali01 wrote on Thursday, November 19, 2015:

Hi Gaurav

Here is a very rough sketch:

    int global_counter;	// Always exists, accessible for all tasks
	static char name[32]; // Always exists, accessible for all functions in this module
	void foo( int var1 )
	// "int var1" is a function parameter, accessible for the caller task only
	int results[ 20 ];	// A variable on stack, will disappear after returning
    static unsigned sum = 0; // A variable static in this function
    // the same instance continues to exist

        // Do something with results

And please note that [automatic] variables often only exists in registers, because the compiler “optimised them away”. But officially they are all placed on the stack, which is visible for the task only.

The contents of your variables is never saved as a task-context, only the necessary registers are pushed on stack. Just like what would happen if an interrupt handler is being called.

If I were you I’d google for these terms: “automatic variables”, “program stack” or read K&R once again :slight_smile: