From fbbca59453fcbc91ff63256b617523b5962b28f8 Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Fri, 31 May 2024 19:18:38 +0200 Subject: [PATCH] Make RegexCache thread-safe --- src/libexpr/primops.cc | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 22d7f188f..9177b0a2f 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -4062,17 +4062,23 @@ static RegisterPrimOp primop_convertHash({ struct RegexCache { - // TODO use C++20 transparent comparison when available - std::unordered_map cache; - std::list keys; + struct State + { + // TODO use C++20 transparent comparison when available + std::unordered_map cache; + std::list keys; + }; + + Sync state_; std::regex get(std::string_view re) { - auto it = cache.find(re); - if (it != cache.end()) + auto state(state_.lock()); + auto it = state->cache.find(re); + if (it != state->cache.end()) return it->second; - keys.emplace_back(re); - return cache.emplace(keys.back(), std::regex(keys.back(), std::regex::extended)).first->second; + state->keys.emplace_back(re); + return state->cache.emplace(state->keys.back(), std::regex(state->keys.back(), std::regex::extended)).first->second; } };