Page 1 of 1

Why vTaskDelete(NULL) does not actually delete task?

Posted: Tue Jul 31, 2018 9:30 am
by dmitryga
Hi everybody!

I've noticed a problem when using vTaskDelete(NULL). This is the last statement in task function and I expect it to delete task itself and release resources allocated for task. But unfortunately I see that task state changes from eBlocked/eRunning state to eReady state.

Here is a little snippet of code, illustrating this problem:

Code: Select all

#define SLEEP(ms)                   vTaskDelay(ms / portTICK_PERIOD_MS)
...
    TaskHandle_t handle = NULL;
    xTaskCreate(&testTask, "TestTask", 4096, NULL, 10, &handle);
    ESP_LOGE(TAG, "Test task handle is 0x%.8X", handle);
    while (1)
    {
        volatile eTaskState state = eTaskGetState(handle);
        ESP_LOGI(TAG, "Task 0x%.8X state is %u", handle, state); // State is 2 when task is running (that's expected,
                                                                 // cause task is sleeping most of time
                                                                 // But when task is completed, state is changed to 1
                                                                 // and remains 1 forever
        SLEEP(500);
    }
...
void testTask(void *pvParameters)
{
    ESP_LOGW(TAG, "Test task started");
    for (uint8_t i = 0; i < 60; i++)
    {
        SLEEP(1000);
        ESP_LOGW(TAG, "Test task iteration %u", i);
    }
    ESP_LOGW(TAG, "Test task ended");
    vTaskDelete(NULL);
}
This is not a problem when you start tasks which are running during application lifetime, but I use the approach with worker tasks executing for lengthy operations. And each subsequent worker task runs twice slower than previous one (for example, first task takes 10 seconds for completion, second - 20 seconds, third - 40 seconds, forth - 80 seconds and so on). I suppose this happens because of orphaned tasks, which are waiting for something...

Re: Why vTaskDelete(NULL) does not actually delete task?

Posted: Tue Jul 31, 2018 11:39 am
by ESP_Dazz
Are you sure you aren't attempting to get the state of a task that has already been deleted? eTaskGetState() doesn't actually check if the task exists. It is implemented in such a way that it'll simply return eReady if it can't find the task in the any of the other lists (ready, event, blocked). I suggest you try running vTaskGetRunTimeStats() to check if the task has actually been deleted.

Re: Why vTaskDelete(NULL) does not actually delete task?

Posted: Tue Jul 31, 2018 12:58 pm
by dmitryga
Thank you for this idea!

Indeed, the task is deleted normally and is not displayed in vTaskGetRunTimeStats output.

But I still wonder if there is a way to check if task handle is valid (points to existing and running task) or not (points to deleted task)? Is it possible, that some task will get the handle of previously deleted task?

Re: Why vTaskDelete(NULL) does not actually delete task?

Posted: Tue Jul 31, 2018 5:09 pm
by WiFive