From a276942d27eb7ab9bc74b1d2a5b4bd29ad136bfa Mon Sep 17 00:00:00 2001 From: chenkeyu Date: Mon, 24 Jun 2024 17:39:15 +0800 Subject: [PATCH] Add lock mutex to safemap Issue:https://gitee.com/openharmony/commonlibrary_c_utils/issues/IA7SVU?from=project-issue Signed-off-by: chenkeyu --- base/include/safe_map.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/base/include/safe_map.h b/base/include/safe_map.h index cf01000..8cd8a35 100644 --- a/base/include/safe_map.h +++ b/base/include/safe_map.h @@ -33,14 +33,17 @@ public: SafeMap(const SafeMap& rhs) { - map_ = rhs.map_; + operator=(rhs); } SafeMap& operator=(const SafeMap& rhs) { - if (&rhs != this) { - map_ = rhs.map_; + if (this == &rhs) { + return *this; } + auto tmp = rhs.Clone(); + std::lock_guard lock(mutex_); + map_ = std::move(tmp); return *this; } @@ -211,8 +214,14 @@ public: } private: - std::mutex mutex_; + mutable std::mutex mutex_; std::map map_; + + std::map Clone() const noexcept + { + std::lock_guard lock(mutex_); + return map_; + } }; } // namespace OHOS -- Gitee