0
0
FreeRTOSprogramming~5 mins

vTaskDelete() for task removal in FreeRTOS

Choose your learning style9 modes available
Introduction

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.

When a task has finished its job and should not run anymore.
To stop a task that is causing errors or is stuck.
To clean up tasks dynamically created during program execution.
When you want to save memory by removing unused tasks.
To control system behavior by removing tasks based on conditions.
Syntax
FreeRTOS
void vTaskDelete(TaskHandle_t xTaskToDelete);

If xTaskToDelete is NULL, the calling task deletes itself.

Deleted tasks will not run again unless recreated.

Examples
The current running task deletes itself.
FreeRTOS
vTaskDelete(NULL);
Deletes the task referenced by xHandle.
FreeRTOS
vTaskDelete(xHandle);
Sample Program

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.

FreeRTOS
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.