Search code examples
esp32freertos

Is it necessary to free a mutex created by xSemaphoreCreateMutex()?


FreeRTOS and ESP-IDF provide xSemaphoreCreateMutex() which allocates and initializes a mutex. Their docs say:

If a mutex is created using xSemaphoreCreateMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see http://www.freertos.org/a00111.html).

However, I can't find any info on whether it is necessary to free the memory created by the mutex. This would be important if using C++ with a mutex member variable, like:

class MyClass
{
    MyClass::MyClass()
    {
        mAccessMutex = xSemaphoreCreateMutex();
    }
    
    MyClass::~MyClass()
    {
        // What to do here??
    }
    
    SemaphoreHandle_t mAccessMutex;
}

REFERENCE

https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/freertos.html?highlight=xsemaphore#semaphore-api


Solution

  • According to FreeRTOS API reference, the proper way to destroy/delete a mutex is vSemaphoreDelete()

    Deletes a semaphore, including mutex type semaphores and recursive semaphores.

    Do not delete a semaphore that has tasks blocked on it.

    If you're using heap_1, deleting is not possible. Also, make sure that you fully understand the perils of dynamic memory allocation in embedded systems before using it. If MyClass is going to be created and destroyed in a regular/periodic basis, this may cause problems.

    So yes, it's necessary to call vSemaphoreDelete(mAccessMutex) in ~MyClass(). But it's probably best to make sure that MyClass instances never get destroyed. In my projects, I generally use one-time dynamic allocation during initialization and forget to implement a proper destructor (which is a bad habit that I need to fix).