As I said, I think there IS a function already that newlib will call during startup to give you the opportunity to create the Mutex. My point was that either you need to create the Mutex with xSemaphoreCreateMutexStatic, or the heap function needs to check if the Mutex actually HAS been created before taking it (and then skip the take/give), to avoid a chicken and egg problem.
It depends a lot on how much you are using the heap, if you are using it a lot, that might be a better choice, especially if you have tasks with tight timing margins that the schedule suspend might influence.
It should be ok to create the mutex early in
main right before doing anything else with
xSemaphoreCreateMutexStatic as Richard proposed.
If unsure and/or using C++ with static or global objects, which might use the heap in their constructors using an
is_initialized flag in
__malloc_lock (with newlib) could be a reasonable solution to skip the mutex until initialized in
main before starting the scheduler.
Thank you richard-damon your answer is clear. What is the newlib function name called during startup?
I would need to dig out the newlib documentation to find the name of the function out, I do remember there was some function that was called during library init time to setup this (and other similar) locks in the library.
For this one, as was mentioned, it would also be ok to test if a mutex has been setup by checking for a Null handle, and skip the take/give if it is zero, and create the Mutex in main before starting the scheduler, since there is no race conditions possible before starting the scheduler.
make sure to use a recursive mutex. There are low memory conditions under which the runtime libs call malloc_lock() recursively in which case you would deadlock yourself if you don’t use recursive muteces (btdt)
thank you for you reply it was useful I have been using free rtos for a short time and I didn’t know about recursive mutex.