From 3c93d6b979e174b90b85ee2ab70dcdad9029e591 Mon Sep 17 00:00:00 2001 From: Sam Haves Date: Wed, 7 Jan 2026 09:29:06 -0800 Subject: [PATCH] Move cache creation into lambda initializer to avoid data race. PiperOrigin-RevId: 853295269 Change-Id: Ic1c8f3d2fec876070da432f8b709b341f3c6cc0a --- src/user/user_api.cc | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/user/user_api.cc b/src/user/user_api.cc index ac4f7888..5e8214b4 100644 --- a/src/user/user_api.cc +++ b/src/user/user_api.cc @@ -1922,12 +1922,15 @@ void mj_clearCache(mjCache* cache) { // get the internal asset cache used by the compiler mjCache* mj_getCache() { - static mjCache cache_cwrapper = {0}; - // mjCCache is not trivially destructible and so the global cache needs to - // allocated on the heap - if constexpr (kGlobalCacheSize != 0) { - static mjCCache* cache = new(std::nothrow) mjCCache(kGlobalCacheSize); - cache_cwrapper.impl_ = cache->Capacity() > 0 ? cache : nullptr; - } + static mjCache cache_cwrapper = []() { + mjCache c = {0}; + // mjCCache is not trivially destructible and so the global cache needs to + // allocated on the heap + if constexpr (kGlobalCacheSize != 0) { + static mjCCache* cache = new (std::nothrow) mjCCache(kGlobalCacheSize); + c.impl_ = cache->Capacity() > 0 ? cache : nullptr; + } + return c; + }(); return &cache_cwrapper; }