From 5e76874ca1db047857cf2ae5a4c3ecda52b7562d Mon Sep 17 00:00:00 2001 From: yurekami Date: Sun, 4 Jan 2026 18:35:42 +0900 Subject: [PATCH] fix: Remove race condition in memory allocator initialization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #315 The gAllocatorInited boolean flag had a race condition where: - Multiple threads could see gAllocatorInited=false simultaneously - Memory ordering issues could cause threads to see gAllocatorInited=true before gAllocator was fully initialized The fix removes the redundant flag and relies solely on std::call_once, which already provides thread-safe initialization with proper memory ordering guarantees and an efficient fast-path after first execution. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- src/memory/common/GlobalMemoryAllocator.cc | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/memory/common/GlobalMemoryAllocator.cc b/src/memory/common/GlobalMemoryAllocator.cc index fbf9935f..c6589fc0 100644 --- a/src/memory/common/GlobalMemoryAllocator.cc +++ b/src/memory/common/GlobalMemoryAllocator.cc @@ -14,7 +14,6 @@ namespace hf3fs::memory { #ifdef OVERRIDE_CXX_NEW_DELETE static std::once_flag gInitOnce; -static bool gAllocatorInited = false; static MemoryAllocatorInterface *gAllocator = nullptr; static thread_local hf3fs::memory::AllocatedMemoryCounter gMemCounter; @@ -73,10 +72,7 @@ static void loadMemoryAllocatorLib() { } void *allocate(size_t size) { - if (!gAllocatorInited) { - std::call_once(gInitOnce, loadMemoryAllocatorLib); - gAllocatorInited = true; - } + std::call_once(gInitOnce, loadMemoryAllocatorLib); #ifdef SAVE_ALLOCATE_SIZE const size_t headerSize = kHeaderSize; @@ -130,10 +126,7 @@ void deallocate(void *mem) { } void *memalign(size_t alignment, size_t size) { - if (!gAllocatorInited) { - std::call_once(gInitOnce, loadMemoryAllocatorLib); - gAllocatorInited = true; - } + std::call_once(gInitOnce, loadMemoryAllocatorLib); #ifdef SAVE_ALLOCATE_SIZE const size_t alignedHeaderSize = std::max(alignment, kHeaderSize);