Context switching not happening between two tasks of same priority

Hello,

I am a newbie to freeRTOS. Request some insights on the below issue.

I have implemented two simple tasks of same priority. Have given osDelay() as part of the tasks for context switching. But always task 1 is running.

taskA()
{
     //somecode;
     osDelay(1000);
}
taskB()
{
     //somecode;
     osDelay(1000);
}

Thanks

How do you know that taskB is not running ?
Did you verify that both tasks created successfully ?
Is taskB running if not creating taskA ?
You’re using preemptive, time sliced scheduling (configured in FreeRTOSConfig.h) and the SysTicks runs properly i.e. a delay of 1000 ms is a delay of 1000 ms ?

Hello,

Thanks for your insights.

It seems like the taskB is not created successfully. I have given 512 in place of stack size argument of osThreadCreate() function and 512 for taskB. taskB creation is failing after taskA creation. But taskB is successfully created without taskA.

I reduced the stack size for both taskA and taskB to 256. Now both tasks are running as expected. I presume that the problem is exceeding stack size.

I am using an STM32L462RE series controller having RAM size of 168KB and have the following questions.

  1. Even though I specified only 512 in the stack size argument(in Bytes) during thread creation, I could see in the task analyzer that the actual thread size allocated was 2048 Bytes (512 x 4). Why is it so?
  2. How do I know the total available FREERTOS stack size for a particular microcontroller type having specific RAM size?
  3. How do I calculate the optimal stack size required for particular task ?

Any insights and references would be of much help.

Thanks

Assuming you are calling xTaskCreate API, you are running out of heap space and not stack. Which FreeRTOS heap are you using? If you are using heap_4, can you try increasing the value of configTOTAL_HEAP_SIZE in your FreeRTOSConfig.h?

You can use uxTaskGetStackHighWaterMark to tune stack size of a task.

Thanks.

In addition see the xTaskCreate API documentation regarding the configSTACK_DEPTH_TYPE of the stack size argument.
I’m not aware of the osThreadCreate wrapper specification (regarding the stack size) but I guess, it’s documented as well.

In addition to what Gaurav wrote: Be aware that the mechanism is unreliable unless you can prove that all possible code paths have been taken once you check the high water mark. In practice, determining stack size is frequently a mixture of pencil-and-paper worst case analysis, observing stacks in debug mode using the blank signature and adding a few dozen bytes for good measure (unless of course your target is so tight on RAM that you have to fight for every single byte).

Sounds derogatory, but there is nothing wrong with that; one always have to compromise somewhere.