Skip to main content
Visitor II
June 8, 2021
Solved

Free RTOS threads and osDelay function.

  • June 8, 2021
  • 1 reply
  • 2382 views

Hey, I have a question about osDealy, my teacher gave me this code and I don't really understand how does ir wotk:

void GreenTask(void *argument)

{ /* USER CODE BEGIN GreenTask */

uint8_t RunCount = 0;

osStatus_t status;

/* Infinite loop */

for(;;)

{ printf("GreenTask running\n");

HAL_GPIO_TogglePin(LD4_GPIO_Port, LD4_Pin);

osDelay(1000);

RunCount++;

if(RunCount == 10) { printf("Deleting GreenTask\n");

HAL_GPIO_WritePin(LD4_GPIO_Port, LD4_Pin, GPIO_PIN_RESET);

status = osThreadTerminate(myGreenTaskHandle);

if(status != osOK) HAL_GPIO_WritePin(LD5_GPIO_Port, LD5_Pin, GPIO_PIN_SET);

} } /* USER CODE END GreenTask */

}

I understand that it lights green LED then waits for 1 s., then increases RunCount and repeats till counter has 10 then terminates this thread. The question I Have is with osDelay, it blocks this function for 1 s. then kernel runs another thread, when this one becomes READY and other ends scheduler should run GrennTask again, but since osDelay is in the middle of this thread, shouldn't RunCount never increment? Does thread, after osDelay function, continues where it was blocked or does it start from the beginning until it gets to osDelay again?

    This topic has been closed for replies.
    Best answer by DWeb_2

    The kernel will first save the state of the processor before exiting the task context via osDelay. When you re-enter from another task, the CPU Registers,.. will be set back to when you left GreenTask. Thus you will continue exactly where you left. As long as RunCount is (in this case) on the task stack it will persist and keep it's value.

    1 reply

    DWeb_2Answer
    Visitor II
    June 8, 2021

    The kernel will first save the state of the processor before exiting the task context via osDelay. When you re-enter from another task, the CPU Registers,.. will be set back to when you left GreenTask. Thus you will continue exactly where you left. As long as RunCount is (in this case) on the task stack it will persist and keep it's value.

    DSimp.1Author
    Visitor II
    June 8, 2021

    thank you very much.