Deleting a Task
In earlier tutorials, we saw how to create tasks and used.
In this tutorial, we will see how to delete a task once its job is done.
Here we will discuss some of the most frequently used APIs related to tasks.
1.xTaskCreate(): This interface is used to create a new Task, if the task is successfully created then it returns pdPass(1) or else errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY(-1). Check this link for more details.
2.vTaskDelay(): This function is used to delay/block the task for specified delay time(ticks). INCLUDE_vTaskDelay needs to be set to 1 in FreeRtosConfig.h file for using this function. Check this link for more details.
3.vTaskDelete():This function is used to delete as task. We need to pass the taskHandle of the task to be deleted.
To delete the own task we should pass NULL as parameter.
Please check this link for details.
In this example, we are going to create 3-Tasks with different priorities.
Each task will run for some time and then goes to blocked state allowing the other tasks to run. Once the Task completes its job, it will delete itself.
- Cpu chooses Task3 out of the 4-Tasks(1,2,3,and idle) as it has higher priority. Task3 will run for some time and goes to wait/blocked state for 150ms.
- At this point 3-Tasks(1,2,idle) are available and scheduler chooses Task2. It runs for some time and goes to blocked state for 150ms.
- Now 2-Tasks(1,Idle) are available and Task1 runs because of its higher priority. It also goes to blocked state for 100ms
- Now scheduler is left out with the Idle task and it keeps running till one of the tasks waiting time is elapsed and comes out of blocked state.
- Since Task1 was blocked for only 100ms, it will come out of the blocked state and starts running. And finally, it deletes itself once its job is done.
- Now again Idle task will start running as there are no other tasks to run.
- At this point Task3 will come out of the waiting/blocked state and preempts the Idle task and starts running. It also deletes itself.
- By this time Task2 is also out of blocked state and runs for some time and deletes itself.
- Now there is only one task ie.The idle task and it keeps running.
Download the complete project and libraries from here.
Have an opinion, suggestion , question or feedback about the article let it out here!