Thread safe memory allocation

aggarg-aws wrote on Monday, August 19, 2019:

I cloned the newlib source and I do not see lock and unlock functions as weak in mlock.c:

void
__malloc_lock (ptr)
     struct _reent *ptr;
{
#ifndef __SINGLE_THREAD__
  __lock_acquire_recursive (__malloc_recursive_mutex);
#endif
}

void
__malloc_unlock (ptr)
     struct _reent *ptr;
{
#ifndef __SINGLE_THREAD__
  __lock_release_recursive (__malloc_recursive_mutex);
#endif
}

I may be looking in incorrect place though.

However, as Dave suggested, you can use GCC wrap feature. Pass the following flags to GCC:

-Wl,--wrap=__malloc_lock
-Wl,--wrap=__malloc_unlock

And then implement the following functions:

void __wrap___malloc_lock(struct _reent *r)
{
	vTaskSuspendAll();
}

void __wrap___malloc_unlock(struct _reent *r)
{
	xTaskResumeAll();
}

Thanks.