vTaskDelete() is used to stop and remove a task from running in FreeRTOS. It helps free up resources when a task is no longer needed.
vTaskDelete() for task removal in FreeRTOS
void vTaskDelete(TaskHandle_t xTaskToDelete);
If xTaskToDelete is NULL, the calling task deletes itself.
Deleted tasks will not run again unless recreated.
vTaskDelete(NULL);
vTaskDelete(xHandle);
This program creates two tasks. Task 1 starts and delays for 1000 ms but gets deleted by Task 2 before resuming and printing its deletion message. Task 2 delays for 500 ms, deletes Task 1, prints confirmation, then deletes itself. The print statements show the order of events.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> TaskHandle_t xTask1Handle = NULL; void vTask1(void *pvParameters) { printf("Task 1 started\n"); vTaskDelay(pdMS_TO_TICKS(1000)); printf("Task 1 deleting itself\n"); vTaskDelete(NULL); // Task deletes itself } void vTask2(void *pvParameters) { printf("Task 2 started\n"); vTaskDelay(pdMS_TO_TICKS(500)); printf("Task 2 deleting Task 1\n"); vTaskDelete(xTask1Handle); // Delete Task 1 printf("Task 2 running after deleting Task 1\n"); vTaskDelete(NULL); // Task 2 deletes itself } int main(void) { xTaskCreate(vTask1, "Task1", 1000, NULL, 1, &xTask1Handle); xTaskCreate(vTask2, "Task2", 1000, NULL, 1, NULL); vTaskStartScheduler(); // Should never reach here for(;;); return 0; }
Once a task is deleted, its stack and resources are freed by the kernel.
Do not use a deleted task handle after deletion; it becomes invalid.
Deleting the current task with vTaskDelete(NULL) stops it immediately.
vTaskDelete() removes a task from FreeRTOS to free resources.
Use NULL to delete the current running task.
Always ensure deleted tasks are not referenced again.