是否有必要释放由 xSemaphoreCreateMutex() 创建的互斥量?
Is it necessary to free a mutex created by xSemaphoreCreateMutex()?
FreeRTOS 和 ESP-IDF 提供 xSemaphoreCreateMutex()
分配和初始化互斥量。他们的文档说:
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).
但是,我找不到任何关于是否有必要释放互斥锁创建的内存的信息。如果将 C++ 与互斥成员变量一起使用,这将很重要,例如:
class MyClass
{
MyClass::MyClass()
{
mAccessMutex = xSemaphoreCreateMutex();
}
MyClass::~MyClass()
{
// What to do here??
}
SemaphoreHandle_t mAccessMutex;
}
参考资料
根据 FreeRTOS API reference,destroy/delete 互斥锁的正确方法是 vSemaphoreDelete()
Deletes a semaphore, including mutex type semaphores and recursive
semaphores.
Do not delete a semaphore that has tasks blocked on it.
如果您使用的是 heap_1,则无法删除。此外,请确保您在使用前完全了解嵌入式系统中动态内存分配的风险。如果要在regular/periodic基础上创建和销毁MyClass
,这可能会导致问题。
所以是的,有必要在 ~MyClass()
中调用 vSemaphoreDelete(mAccessMutex)
。但最好确保 MyClass
个实例永远不会被销毁。在我的项目中,我通常在初始化期间使用一次性动态分配和忘记来实现适当的析构函数(这是我需要改正的坏习惯)。
FreeRTOS 和 ESP-IDF 提供 xSemaphoreCreateMutex()
分配和初始化互斥量。他们的文档说:
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).
但是,我找不到任何关于是否有必要释放互斥锁创建的内存的信息。如果将 C++ 与互斥成员变量一起使用,这将很重要,例如:
class MyClass
{
MyClass::MyClass()
{
mAccessMutex = xSemaphoreCreateMutex();
}
MyClass::~MyClass()
{
// What to do here??
}
SemaphoreHandle_t mAccessMutex;
}
参考资料
根据 FreeRTOS API reference,destroy/delete 互斥锁的正确方法是 vSemaphoreDelete()
Deletes a semaphore, including mutex type semaphores and recursive semaphores.
Do not delete a semaphore that has tasks blocked on it.
如果您使用的是 heap_1,则无法删除。此外,请确保您在使用前完全了解嵌入式系统中动态内存分配的风险。如果要在regular/periodic基础上创建和销毁MyClass
,这可能会导致问题。
所以是的,有必要在 ~MyClass()
中调用 vSemaphoreDelete(mAccessMutex)
。但最好确保 MyClass
个实例永远不会被销毁。在我的项目中,我通常在初始化期间使用一次性动态分配和忘记来实现适当的析构函数(这是我需要改正的坏习惯)。