Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alist-org
GitHub Repository: alist-org/alist
Path: blob/main/pkg/generic_sync/map.go
1560 views
1
// Copyright 2016 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
4
5
package generic_sync
6
7
import (
8
"sync"
9
"sync/atomic"
10
"unsafe"
11
)
12
13
// MapOf is like a Go map[interface{}]interface{} but is safe for concurrent use
14
// by multiple goroutines without additional locking or coordination.
15
// Loads, stores, and deletes run in amortized constant time.
16
//
17
// The MapOf type is specialized. Most code should use a plain Go map instead,
18
// with separate locking or coordination, for better type safety and to make it
19
// easier to maintain other invariants along with the map content.
20
//
21
// The MapOf type is optimized for two common use cases: (1) when the entry for a given
22
// key is only ever written once but read many times, as in caches that only grow,
23
// or (2) when multiple goroutines read, write, and overwrite entries for disjoint
24
// sets of keys. In these two cases, use of a MapOf may significantly reduce lock
25
// contention compared to a Go map paired with a separate Mutex or RWMutex.
26
//
27
// The zero MapOf is empty and ready for use. A MapOf must not be copied after first use.
28
type MapOf[K comparable, V any] struct {
29
mu sync.Mutex
30
31
// read contains the portion of the map's contents that are safe for
32
// concurrent access (with or without mu held).
33
//
34
// The read field itself is always safe to load, but must only be stored with
35
// mu held.
36
//
37
// Entries stored in read may be updated concurrently without mu, but updating
38
// a previously-expunged entry requires that the entry be copied to the dirty
39
// map and unexpunged with mu held.
40
read atomic.Value // readOnly
41
42
// dirty contains the portion of the map's contents that require mu to be
43
// held. To ensure that the dirty map can be promoted to the read map quickly,
44
// it also includes all of the non-expunged entries in the read map.
45
//
46
// Expunged entries are not stored in the dirty map. An expunged entry in the
47
// clean map must be unexpunged and added to the dirty map before a new value
48
// can be stored to it.
49
//
50
// If the dirty map is nil, the next write to the map will initialize it by
51
// making a shallow copy of the clean map, omitting stale entries.
52
dirty map[K]*entry[V]
53
54
// misses counts the number of loads since the read map was last updated that
55
// needed to lock mu to determine whether the key was present.
56
//
57
// Once enough misses have occurred to cover the cost of copying the dirty
58
// map, the dirty map will be promoted to the read map (in the unamended
59
// state) and the next store to the map will make a new dirty copy.
60
misses int
61
}
62
63
// readOnly is an immutable struct stored atomically in the MapOf.read field.
64
type readOnly[K comparable, V any] struct {
65
m map[K]*entry[V]
66
amended bool // true if the dirty map contains some key not in m.
67
}
68
69
// expunged is an arbitrary pointer that marks entries which have been deleted
70
// from the dirty map.
71
var expunged = unsafe.Pointer(new(interface{}))
72
73
// An entry is a slot in the map corresponding to a particular key.
74
type entry[V any] struct {
75
// p points to the interface{} value stored for the entry.
76
//
77
// If p == nil, the entry has been deleted and m.dirty == nil.
78
//
79
// If p == expunged, the entry has been deleted, m.dirty != nil, and the entry
80
// is missing from m.dirty.
81
//
82
// Otherwise, the entry is valid and recorded in m.read.m[key] and, if m.dirty
83
// != nil, in m.dirty[key].
84
//
85
// An entry can be deleted by atomic replacement with nil: when m.dirty is
86
// next created, it will atomically replace nil with expunged and leave
87
// m.dirty[key] unset.
88
//
89
// An entry's associated value can be updated by atomic replacement, provided
90
// p != expunged. If p == expunged, an entry's associated value can be updated
91
// only after first setting m.dirty[key] = e so that lookups using the dirty
92
// map find the entry.
93
p unsafe.Pointer // *interface{}
94
}
95
96
func newEntry[V any](i V) *entry[V] {
97
return &entry[V]{p: unsafe.Pointer(&i)}
98
}
99
100
// Load returns the value stored in the map for a key, or nil if no
101
// value is present.
102
// The ok result indicates whether value was found in the map.
103
func (m *MapOf[K, V]) Load(key K) (value V, ok bool) {
104
read, _ := m.read.Load().(readOnly[K, V])
105
e, ok := read.m[key]
106
if !ok && read.amended {
107
m.mu.Lock()
108
// Avoid reporting a spurious miss if m.dirty got promoted while we were
109
// blocked on m.mu. (If further loads of the same key will not miss, it's
110
// not worth copying the dirty map for this key.)
111
read, _ = m.read.Load().(readOnly[K, V])
112
e, ok = read.m[key]
113
if !ok && read.amended {
114
e, ok = m.dirty[key]
115
// Regardless of whether the entry was present, record a miss: this key
116
// will take the slow path until the dirty map is promoted to the read
117
// map.
118
m.missLocked()
119
}
120
m.mu.Unlock()
121
}
122
if !ok {
123
return value, false
124
}
125
return e.load()
126
}
127
128
func (m *MapOf[K, V]) Has(key K) bool {
129
_, ok := m.Load(key)
130
return ok
131
}
132
133
func (e *entry[V]) load() (value V, ok bool) {
134
p := atomic.LoadPointer(&e.p)
135
if p == nil || p == expunged {
136
return value, false
137
}
138
return *(*V)(p), true
139
}
140
141
// Store sets the value for a key.
142
func (m *MapOf[K, V]) Store(key K, value V) {
143
read, _ := m.read.Load().(readOnly[K, V])
144
if e, ok := read.m[key]; ok && e.tryStore(&value) {
145
return
146
}
147
148
m.mu.Lock()
149
read, _ = m.read.Load().(readOnly[K, V])
150
if e, ok := read.m[key]; ok {
151
if e.unexpungeLocked() {
152
// The entry was previously expunged, which implies that there is a
153
// non-nil dirty map and this entry is not in it.
154
m.dirty[key] = e
155
}
156
e.storeLocked(&value)
157
} else if e, ok := m.dirty[key]; ok {
158
e.storeLocked(&value)
159
} else {
160
if !read.amended {
161
// We're adding the first new key to the dirty map.
162
// Make sure it is allocated and mark the read-only map as incomplete.
163
m.dirtyLocked()
164
m.read.Store(readOnly[K, V]{m: read.m, amended: true})
165
}
166
m.dirty[key] = newEntry(value)
167
}
168
m.mu.Unlock()
169
}
170
171
// tryStore stores a value if the entry has not been expunged.
172
//
173
// If the entry is expunged, tryStore returns false and leaves the entry
174
// unchanged.
175
func (e *entry[V]) tryStore(i *V) bool {
176
for {
177
p := atomic.LoadPointer(&e.p)
178
if p == expunged {
179
return false
180
}
181
if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) {
182
return true
183
}
184
}
185
}
186
187
// unexpungeLocked ensures that the entry is not marked as expunged.
188
//
189
// If the entry was previously expunged, it must be added to the dirty map
190
// before m.mu is unlocked.
191
func (e *entry[V]) unexpungeLocked() (wasExpunged bool) {
192
return atomic.CompareAndSwapPointer(&e.p, expunged, nil)
193
}
194
195
// storeLocked unconditionally stores a value to the entry.
196
//
197
// The entry must be known not to be expunged.
198
func (e *entry[V]) storeLocked(i *V) {
199
atomic.StorePointer(&e.p, unsafe.Pointer(i))
200
}
201
202
// LoadOrStore returns the existing value for the key if present.
203
// Otherwise, it stores and returns the given value.
204
// The loaded result is true if the value was loaded, false if stored.
205
func (m *MapOf[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
206
// Avoid locking if it's a clean hit.
207
read, _ := m.read.Load().(readOnly[K, V])
208
if e, ok := read.m[key]; ok {
209
actual, loaded, ok := e.tryLoadOrStore(value)
210
if ok {
211
return actual, loaded
212
}
213
}
214
215
m.mu.Lock()
216
read, _ = m.read.Load().(readOnly[K, V])
217
if e, ok := read.m[key]; ok {
218
if e.unexpungeLocked() {
219
m.dirty[key] = e
220
}
221
actual, loaded, _ = e.tryLoadOrStore(value)
222
} else if e, ok := m.dirty[key]; ok {
223
actual, loaded, _ = e.tryLoadOrStore(value)
224
m.missLocked()
225
} else {
226
if !read.amended {
227
// We're adding the first new key to the dirty map.
228
// Make sure it is allocated and mark the read-only map as incomplete.
229
m.dirtyLocked()
230
m.read.Store(readOnly[K, V]{m: read.m, amended: true})
231
}
232
m.dirty[key] = newEntry(value)
233
actual, loaded = value, false
234
}
235
m.mu.Unlock()
236
237
return actual, loaded
238
}
239
240
// tryLoadOrStore atomically loads or stores a value if the entry is not
241
// expunged.
242
//
243
// If the entry is expunged, tryLoadOrStore leaves the entry unchanged and
244
// returns with ok==false.
245
func (e *entry[V]) tryLoadOrStore(i V) (actual V, loaded, ok bool) {
246
p := atomic.LoadPointer(&e.p)
247
if p == expunged {
248
return actual, false, false
249
}
250
if p != nil {
251
return *(*V)(p), true, true
252
}
253
254
// Copy the interface after the first load to make this method more amenable
255
// to escape analysis: if we hit the "load" path or the entry is expunged, we
256
// shouldn'V bother heap-allocating.
257
ic := i
258
for {
259
if atomic.CompareAndSwapPointer(&e.p, nil, unsafe.Pointer(&ic)) {
260
return i, false, true
261
}
262
p = atomic.LoadPointer(&e.p)
263
if p == expunged {
264
return actual, false, false
265
}
266
if p != nil {
267
return *(*V)(p), true, true
268
}
269
}
270
}
271
272
// Delete deletes the value for a key.
273
func (m *MapOf[K, V]) Delete(key K) {
274
read, _ := m.read.Load().(readOnly[K, V])
275
e, ok := read.m[key]
276
if !ok && read.amended {
277
m.mu.Lock()
278
read, _ = m.read.Load().(readOnly[K, V])
279
e, ok = read.m[key]
280
if !ok && read.amended {
281
delete(m.dirty, key)
282
}
283
m.mu.Unlock()
284
}
285
if ok {
286
e.delete()
287
}
288
}
289
290
func (e *entry[V]) delete() (hadValue bool) {
291
for {
292
p := atomic.LoadPointer(&e.p)
293
if p == nil || p == expunged {
294
return false
295
}
296
if atomic.CompareAndSwapPointer(&e.p, p, nil) {
297
return true
298
}
299
}
300
}
301
302
// Range calls f sequentially for each key and value present in the map.
303
// If f returns false, range stops the iteration.
304
//
305
// Range does not necessarily correspond to any consistent snapshot of the MapOf's
306
// contents: no key will be visited more than once, but if the value for any key
307
// is stored or deleted concurrently, Range may reflect any mapping for that key
308
// from any point during the Range call.
309
//
310
// Range may be O(N) with the number of elements in the map even if f returns
311
// false after a constant number of calls.
312
func (m *MapOf[K, V]) Range(f func(key K, value V) bool) {
313
// We need to be able to iterate over all of the keys that were already
314
// present at the start of the call to Range.
315
// If read.amended is false, then read.m satisfies that property without
316
// requiring us to hold m.mu for a long time.
317
read, _ := m.read.Load().(readOnly[K, V])
318
if read.amended {
319
// m.dirty contains keys not in read.m. Fortunately, Range is already O(N)
320
// (assuming the caller does not break out early), so a call to Range
321
// amortizes an entire copy of the map: we can promote the dirty copy
322
// immediately!
323
m.mu.Lock()
324
read, _ = m.read.Load().(readOnly[K, V])
325
if read.amended {
326
read = readOnly[K, V]{m: m.dirty}
327
m.read.Store(read)
328
m.dirty = nil
329
m.misses = 0
330
}
331
m.mu.Unlock()
332
}
333
334
for k, e := range read.m {
335
v, ok := e.load()
336
if !ok {
337
continue
338
}
339
if !f(k, v) {
340
break
341
}
342
}
343
}
344
345
// Values returns a slice of the values in the map.
346
func (m *MapOf[K, V]) Values() []V {
347
var values []V
348
m.Range(func(key K, value V) bool {
349
values = append(values, value)
350
return true
351
})
352
return values
353
}
354
355
func (m *MapOf[K, V]) Count() int {
356
return len(m.dirty)
357
}
358
359
func (m *MapOf[K, V]) Empty() bool {
360
return m.Count() == 0
361
}
362
363
func (m *MapOf[K, V]) ToMap() map[K]V {
364
ans := make(map[K]V)
365
m.Range(func(key K, value V) bool {
366
ans[key] = value
367
return true
368
})
369
return ans
370
}
371
372
func (m *MapOf[K, V]) Clear() {
373
m.Range(func(key K, value V) bool {
374
m.Delete(key)
375
return true
376
})
377
}
378
379
func (m *MapOf[K, V]) missLocked() {
380
m.misses++
381
if m.misses < len(m.dirty) {
382
return
383
}
384
m.read.Store(readOnly[K, V]{m: m.dirty})
385
m.dirty = nil
386
m.misses = 0
387
}
388
389
func (m *MapOf[K, V]) dirtyLocked() {
390
if m.dirty != nil {
391
return
392
}
393
394
read, _ := m.read.Load().(readOnly[K, V])
395
m.dirty = make(map[K]*entry[V], len(read.m))
396
for k, e := range read.m {
397
if !e.tryExpungeLocked() {
398
m.dirty[k] = e
399
}
400
}
401
}
402
403
func (e *entry[V]) tryExpungeLocked() (isExpunged bool) {
404
p := atomic.LoadPointer(&e.p)
405
for p == nil {
406
if atomic.CompareAndSwapPointer(&e.p, nil, expunged) {
407
return true
408
}
409
p = atomic.LoadPointer(&e.p)
410
}
411
return p == expunged
412
}
413
414