aboutsummaryrefslogtreecommitdiff
path: root/src/sync/map.go
diff options
context:
space:
mode:
authorHiro <laciferin@gmail.com>2024-01-03 00:10:58 +0000
committerGopher Robot <gobot@golang.org>2024-02-01 15:34:22 +0000
commit5b6cd3d0cbd3f3f0a645e37526fabe35a7e75319 (patch)
tree70b282bd7b0fb3cf463948a0e94c8b980b580e5f /src/sync/map.go
parent2f6a25f4478905db5e169019bf9dc39ab2a50f89 (diff)
downloadgo-5b6cd3d0cbd3f3f0a645e37526fabe35a7e75319.tar.xz
sync: add Map.Clear
Fixes #61696 Change-Id: I0a31afd3bc433fc84280d56f2798bda10da61eba GitHub-Last-Rev: 17bedc864f1685178a42b59f7083677a6124f831 GitHub-Pull-Request: golang/go#61702 Reviewed-on: https://go-review.googlesource.com/c/go/+/515015 Auto-Submit: Bryan Mills <bcmills@google.com> Reviewed-by: Cherry Mui <cherryyz@google.com> Reviewed-by: qiulaidongfeng <2645477756@qq.com> Reviewed-by: Bryan Mills <bcmills@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Diffstat (limited to 'src/sync/map.go')
-rw-r--r--src/sync/map.go20
1 files changed, 20 insertions, 0 deletions
diff --git a/src/sync/map.go b/src/sync/map.go
index 7a9eebdce3..1f26cdd8bb 100644
--- a/src/sync/map.go
+++ b/src/sync/map.go
@@ -155,6 +155,26 @@ func (m *Map) Store(key, value any) {
_, _ = m.Swap(key, value)
}
+// Clear deletes all the keys.
+func (m *Map) Clear() {
+ read := m.loadReadOnly()
+ if len(read.m) == 0 && !read.amended {
+ // Avoid allocating a new readOnly when the map is already clear.
+ return
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ read = m.loadReadOnly()
+ if len(read.m) > 0 || read.amended {
+ m.read.Store(&readOnly{})
+ }
+
+ clear(m.dirty)
+ m.misses = 0 // Don't immediately promote the newly-cleared dirty map on the next operation
+}
+
// tryCompareAndSwap compare the entry with the given old value and swaps
// it with a new value if the entry is equal to the old value, and the entry
// has not been expunged.