From 00c45345746feb607c5de08000158bb019b0d97c Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Mon, 8 May 2023 14:15:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20AtomGetSet=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/synchronization/map.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/utils/synchronization/map.go b/utils/synchronization/map.go index 21dd227..81f877e 100644 --- a/utils/synchronization/map.go +++ b/utils/synchronization/map.go @@ -26,6 +26,16 @@ func (slf *Map[Key, Value]) Get(key Key) Value { return slf.data[key] } +// AtomGetSet 原子方式获取一个值并在之后进行赋值 +func (slf *Map[Key, Value]) AtomGetSet(key Key, handle func(value Value, exist bool) (newValue Value, isSet bool)) { + slf.lock.Lock() + defer slf.lock.Unlock() + value, exist := slf.data[key] + if newValue, isSet := handle(value, exist); isSet { + slf.data[key] = newValue + } +} + func (slf *Map[Key, Value]) Exist(key Key) bool { slf.lock.RLock() _, exist := slf.data[key]