diff --git a/src/lib/support/CHIPMem.cpp b/src/lib/support/CHIPMem.cpp index 4d94430b3da89c..80f674e2e34801 100644 --- a/src/lib/support/CHIPMem.cpp +++ b/src/lib/support/CHIPMem.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -36,31 +37,51 @@ namespace Platform { extern CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize); extern void MemoryAllocatorShutdown(); -static std::atomic_int memoryInitializationCount{ 0 }; +#if !CHIP_SYSTEM_CONFIG_NO_LOCKING +static chip::System::Mutex gMemoryLock; +#endif +static int memoryInitializationCount{ 0 }; CHIP_ERROR MemoryInit(void * buf, size_t bufSize) { - if (memoryInitializationCount++ > 0) + CHIP_ERROR err = CHIP_NO_ERROR; +#if !CHIP_SYSTEM_CONFIG_NO_LOCKING + gMemoryLock.Lock(); +#endif + do { - return CHIP_NO_ERROR; - } - // Initialize the allocator. - CHIP_ERROR err = MemoryAllocatorInit(buf, bufSize); - if (err != CHIP_NO_ERROR) - { - return err; - } - // Here we do things like mbedtls_platform_set_calloc_free(), depending on configuration. + if (memoryInitializationCount++ > 0) + { + // Already initialized + break; + } + // Initialize the allocator. + err = MemoryAllocatorInit(buf, bufSize); + if (err != CHIP_NO_ERROR) + { + break; + } + // Here we do things like mbedtls_platform_set_calloc_free(), depending on configuration. + } while (0); +#if !CHIP_SYSTEM_CONFIG_NO_LOCKING + gMemoryLock.Unlock(); +#endif return err; } void MemoryShutdown() { +#if !CHIP_SYSTEM_CONFIG_NO_LOCKING + gMemoryLock.Lock(); +#endif if ((memoryInitializationCount > 0) && (--memoryInitializationCount == 0)) { // Here we undo things like mbedtls_platform_set_calloc_free() MemoryAllocatorShutdown(); } +#if !CHIP_SYSTEM_CONFIG_NO_LOCKING + gMemoryLock.Unlock(); +#endif } } // namespace Platform diff --git a/src/lib/support/CHIPMem.h b/src/lib/support/CHIPMem.h index 3bd852210de5a4..2215987ec0ca01 100644 --- a/src/lib/support/CHIPMem.h +++ b/src/lib/support/CHIPMem.h @@ -46,6 +46,7 @@ namespace Platform { * This function is platform specific and might be empty in certain cases. * For example, this function is doing nothing when the C Standard Library malloc() * and free() functions are used for memory allocation. + * Note- The MemoryInit and MemoryShutdown APIs are thread-safe, unless CHIP_SYSTEM_CONFIG_NO_LOCKING is enabled * * @param[in] buf A pointer to a dedicated memory buffer, which should be used as * a memory pool for CHIP memory allocation. @@ -73,6 +74,7 @@ extern CHIP_ERROR MemoryInit(void * buf = nullptr, size_t bufSize = 0); * This function can be an empty call if there is no need to release resources. For example, * this is the case when the C Standard Library malloc() and free() functions are used * for memory allocation. + * Note- The MemoryInit and MemoryShutdown APIs are thread-safe, unless CHIP_SYSTEM_CONFIG_NO_LOCKING is enabled * */ extern void MemoryShutdown();