recursive mutexes memory management

jean-marc wrote on Monday, October 07, 2019:

Hi everyone,
I have have modified the ethernet library for STM32 in the Arduino environment, to make it multitasking-friendly. I am facing a problem with memory leaks, because of the following mechanism:
On initialization I create a recursive mutex that protects the SPI communication with the W5X00 ethernet chip.
When an timeout or other spurious disconnection occur, I exit any loop I can be in, and go back to the initialisation phase of the ethernet chip to attempt a new connection.
However, I am realizing that doing so does not free the memory that was allocated when the mutex was created.
I could not find any API function to destroy an existing mutex.
Actually, if such a function existed, it would not work for me since I have compiled my project using the lightest heap allocation source file, that cannot free the already allocated memory.
So I would rather like, when initializing my ethernet connection, to check wether the recursive mutex already exists. This is easy, as if the variable that points to the mutex is not null, it means that a mutex had already be created. I can then merely reuse it.
However, I am unsure of the nesting level of the mutex at this time, though I took care to Give the,mutex back before exiting any function that has a TakeRecursiveMutex. However, I would like to ensure that the mutex is reinitialized. I thought of adding a loop containing a GiveRecursiveMutex based of the current recursion count of the mutex, but I did not find the appropriate function to get this number.
How can I do? Or is there another way to handle this mechanism?
Thanks in advance.
JM

rtel wrote on Monday, October 07, 2019:

https://www.freertos.org/uxSemaphoreGetCount.html

jean-marc wrote on Monday, October 07, 2019:

I have seen this function, but:
it is not explicitely defined to work with Recursive mutexes ;
the count decrease when the semaphore is taken, and increased when it is given, which is not compatible with a limitless recursion.
Or am I mistaken?

richard_damon wrote on Monday, October 07, 2019:

When you create a mutex, you get a handle, which will never be zero. You are supposed to save that handle so you can access the Mutex. Check if the handle is 0, if so you need to create it, if it isn’t the existing mutex can be used.

You can delete a mutex with vSemaphoreDelete()

uxSemaphoreGetCount doesn’t look like it will get the number of times the semaphore is held, but will tell you IF the semaphore is held. You could just loop on the give until the count says zero, and the mutex has been released, but you also need to check if the give fails, as someone else might take it after you make the give that released it before you can check.