-
Notifications
You must be signed in to change notification settings - Fork 16
/
gen_int.go
504 lines (473 loc) · 16.2 KB
/
gen_int.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Code generated by gen.go; DO NOT EDIT.
package skipmap
import (
"sync"
"sync/atomic"
"unsafe"
)
// IntMap represents a map based on skip list.
type IntMap[valueT any] struct {
length int64
highestLevel uint64 // highest level for now
header *intnode[valueT]
}
type intnode[valueT any] struct {
key int
value unsafe.Pointer // *any
flags bitflag
level uint32
mu sync.Mutex
next optionalArray // [level]*intnode
}
func newIntNode[valueT any](key int, value valueT, level int) *intnode[valueT] {
node := &intnode[valueT]{
key: key,
level: uint32(level),
}
node.storeVal(value)
if level > op1 {
node.next.extra = new([op2]unsafe.Pointer)
}
return node
}
func (n *intnode[valueT]) storeVal(value valueT) {
atomic.StorePointer(&n.value, unsafe.Pointer(&value))
}
func (n *intnode[valueT]) loadVal() valueT {
return *(*valueT)(atomic.LoadPointer(&n.value))
}
func (n *intnode[valueT]) loadNext(i int) *intnode[valueT] {
return (*intnode[valueT])(n.next.load(i))
}
func (n *intnode[valueT]) storeNext(i int, node *intnode[valueT]) {
n.next.store(i, unsafe.Pointer(node))
}
func (n *intnode[valueT]) atomicLoadNext(i int) *intnode[valueT] {
return (*intnode[valueT])(n.next.atomicLoad(i))
}
func (n *intnode[valueT]) atomicStoreNext(i int, node *intnode[valueT]) {
n.next.atomicStore(i, unsafe.Pointer(node))
}
// findNode takes a key and two maximal-height arrays then searches exactly as in a sequential skipmap.
// The returned preds and succs always satisfy preds[i] > key >= succs[i].
// (without fullpath, if find the node will return immediately)
func (s *IntMap[valueT]) findNode(key int, preds *[maxLevel]*intnode[valueT], succs *[maxLevel]*intnode[valueT]) *intnode[valueT] {
x := s.header
for i := int(atomic.LoadUint64(&s.highestLevel)) - 1; i >= 0; i-- {
succ := x.atomicLoadNext(i)
for succ != nil && (succ.key < key) {
x = succ
succ = x.atomicLoadNext(i)
}
preds[i] = x
succs[i] = succ
// Check if the key already in the skipmap.
if succ != nil && succ.key == key {
return succ
}
}
return nil
}
// findNodeDelete takes a key and two maximal-height arrays then searches exactly as in a sequential skip-list.
// The returned preds and succs always satisfy preds[i] > key >= succs[i].
func (s *IntMap[valueT]) findNodeDelete(key int, preds *[maxLevel]*intnode[valueT], succs *[maxLevel]*intnode[valueT]) int {
// lFound represents the index of the first layer at which it found a node.
lFound, x := -1, s.header
for i := int(atomic.LoadUint64(&s.highestLevel)) - 1; i >= 0; i-- {
succ := x.atomicLoadNext(i)
for succ != nil && (succ.key < key) {
x = succ
succ = x.atomicLoadNext(i)
}
preds[i] = x
succs[i] = succ
// Check if the key already in the skip list.
if lFound == -1 && succ != nil && succ.key == key {
lFound = i
}
}
return lFound
}
func unlockint[valueT any](preds [maxLevel]*intnode[valueT], highestLevel int) {
var prevPred *intnode[valueT]
for i := highestLevel; i >= 0; i-- {
if preds[i] != prevPred { // the node could be unlocked by previous loop
preds[i].mu.Unlock()
prevPred = preds[i]
}
}
}
// Store sets the value for a key.
func (s *IntMap[valueT]) Store(key int, value valueT) {
level := s.randomlevel()
var preds, succs [maxLevel]*intnode[valueT]
for {
nodeFound := s.findNode(key, &preds, &succs)
if nodeFound != nil { // indicating the key is already in the skip-list
if !nodeFound.flags.Get(marked) {
// We don't need to care about whether or not the node is fully linked,
// just replace the value.
nodeFound.storeVal(value)
return
}
// If the node is marked, represents some other goroutines is in the process of deleting this node,
// we need to add this node in next loop.
continue
}
// Add this node into skip list.
var (
highestLocked = -1 // the highest level being locked by this process
valid = true
pred, succ, prevPred *intnode[valueT]
)
for layer := 0; valid && layer < level; layer++ {
pred = preds[layer] // target node's previous node
succ = succs[layer] // target node's next node
if pred != prevPred { // the node in this layer could be locked by previous loop
pred.mu.Lock()
highestLocked = layer
prevPred = pred
}
// valid check if there is another node has inserted into the skip list in this layer during this process.
// It is valid if:
// 1. The previous node and next node both are not marked.
// 2. The previous node's next node is succ in this layer.
valid = !pred.flags.Get(marked) && (succ == nil || !succ.flags.Get(marked)) && pred.loadNext(layer) == succ
}
if !valid {
unlockint(preds, highestLocked)
continue
}
nn := newIntNode(key, value, level)
for layer := 0; layer < level; layer++ {
nn.storeNext(layer, succs[layer])
preds[layer].atomicStoreNext(layer, nn)
}
nn.flags.SetTrue(fullyLinked)
unlockint(preds, highestLocked)
atomic.AddInt64(&s.length, 1)
return
}
}
// randomlevel returns a random level and update the highest level if needed.
func (s *IntMap[valueT]) randomlevel() int {
// Generate random level.
level := randomLevel()
// Update highest level if possible.
for {
hl := atomic.LoadUint64(&s.highestLevel)
if uint64(level) <= hl {
break
}
if atomic.CompareAndSwapUint64(&s.highestLevel, hl, uint64(level)) {
break
}
}
return level
}
// Load returns the value stored in the map for a key, or nil if no
// value is present.
// The ok result indicates whether value was found in the map.
func (s *IntMap[valueT]) Load(key int) (value valueT, ok bool) {
x := s.header
for i := int(atomic.LoadUint64(&s.highestLevel)) - 1; i >= 0; i-- {
nex := x.atomicLoadNext(i)
for nex != nil && (nex.key < key) {
x = nex
nex = x.atomicLoadNext(i)
}
// Check if the key already in the skip list.
if nex != nil && nex.key == key {
if nex.flags.MGet(fullyLinked|marked, fullyLinked) {
return nex.loadVal(), true
}
return
}
}
return
}
// LoadAndDelete deletes the value for a key, returning the previous value if any.
// The loaded result reports whether the key was present.
// (Modified from Delete)
func (s *IntMap[valueT]) LoadAndDelete(key int) (value valueT, loaded bool) {
var (
nodeToDelete *intnode[valueT]
isMarked bool // represents if this operation mark the node
topLayer = -1
preds, succs [maxLevel]*intnode[valueT]
)
for {
lFound := s.findNodeDelete(key, &preds, &succs)
if isMarked || // this process mark this node or we can find this node in the skip list
lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (int(succs[lFound].level)-1) == lFound {
if !isMarked { // we don't mark this node for now
nodeToDelete = succs[lFound]
topLayer = lFound
nodeToDelete.mu.Lock()
if nodeToDelete.flags.Get(marked) {
// The node is marked by another process,
// the physical deletion will be accomplished by another process.
nodeToDelete.mu.Unlock()
return
}
nodeToDelete.flags.SetTrue(marked)
isMarked = true
}
// Accomplish the physical deletion.
var (
highestLocked = -1 // the highest level being locked by this process
valid = true
pred, succ, prevPred *intnode[valueT]
)
for layer := 0; valid && (layer <= topLayer); layer++ {
pred, succ = preds[layer], succs[layer]
if pred != prevPred { // the node in this layer could be locked by previous loop
pred.mu.Lock()
highestLocked = layer
prevPred = pred
}
// valid check if there is another node has inserted into the skip list in this layer
// during this process, or the previous is deleted by another process.
// It is valid if:
// 1. the previous node exists.
// 2. no another node has inserted into the skip list in this layer.
valid = !pred.flags.Get(marked) && pred.loadNext(layer) == succ
}
if !valid {
unlockint(preds, highestLocked)
continue
}
for i := topLayer; i >= 0; i-- {
// Now we own the `nodeToDelete`, no other goroutine will modify it.
// So we don't need `nodeToDelete.loadNext`
preds[i].atomicStoreNext(i, nodeToDelete.loadNext(i))
}
nodeToDelete.mu.Unlock()
unlockint(preds, highestLocked)
atomic.AddInt64(&s.length, -1)
return nodeToDelete.loadVal(), true
}
return
}
}
// LoadOrStore returns the existing value for the key if present.
// Otherwise, it stores and returns the given value.
// The loaded result is true if the value was loaded, false if stored.
// (Modified from Store)
func (s *IntMap[valueT]) LoadOrStore(key int, value valueT) (actual valueT, loaded bool) {
var (
level int
preds, succs [maxLevel]*intnode[valueT]
hl = int(atomic.LoadUint64(&s.highestLevel))
)
for {
nodeFound := s.findNode(key, &preds, &succs)
if nodeFound != nil { // indicating the key is already in the skip-list
if !nodeFound.flags.Get(marked) {
// We don't need to care about whether or not the node is fully linked,
// just return the value.
return nodeFound.loadVal(), true
}
// If the node is marked, represents some other goroutines is in the process of deleting this node,
// we need to add this node in next loop.
continue
}
// Add this node into skip list.
var (
highestLocked = -1 // the highest level being locked by this process
valid = true
pred, succ, prevPred *intnode[valueT]
)
if level == 0 {
level = s.randomlevel()
if level > hl {
// If the highest level is updated, usually means that many goroutines
// are inserting items. Hopefully we can find a better path in next loop.
// TODO(zyh): consider filling the preds if s.header[level].next == nil,
// but this strategy's performance is almost the same as the existing method.
continue
}
}
for layer := 0; valid && layer < level; layer++ {
pred = preds[layer] // target node's previous node
succ = succs[layer] // target node's next node
if pred != prevPred { // the node in this layer could be locked by previous loop
pred.mu.Lock()
highestLocked = layer
prevPred = pred
}
// valid check if there is another node has inserted into the skip list in this layer during this process.
// It is valid if:
// 1. The previous node and next node both are not marked.
// 2. The previous node's next node is succ in this layer.
valid = !pred.flags.Get(marked) && (succ == nil || !succ.flags.Get(marked)) && pred.loadNext(layer) == succ
}
if !valid {
unlockint(preds, highestLocked)
continue
}
nn := newIntNode(key, value, level)
for layer := 0; layer < level; layer++ {
nn.storeNext(layer, succs[layer])
preds[layer].atomicStoreNext(layer, nn)
}
nn.flags.SetTrue(fullyLinked)
unlockint(preds, highestLocked)
atomic.AddInt64(&s.length, 1)
return value, false
}
}
// LoadOrStoreLazy returns the existing value for the key if present.
// Otherwise, it stores and returns the given value from f, f will only be called once.
// The loaded result is true if the value was loaded, false if stored.
// (Modified from LoadOrStore)
func (s *IntMap[valueT]) LoadOrStoreLazy(key int, f func() valueT) (actual valueT, loaded bool) {
var (
level int
preds, succs [maxLevel]*intnode[valueT]
hl = int(atomic.LoadUint64(&s.highestLevel))
)
for {
nodeFound := s.findNode(key, &preds, &succs)
if nodeFound != nil { // indicating the key is already in the skip-list
if !nodeFound.flags.Get(marked) {
// We don't need to care about whether or not the node is fully linked,
// just return the value.
return nodeFound.loadVal(), true
}
// If the node is marked, represents some other goroutines is in the process of deleting this node,
// we need to add this node in next loop.
continue
}
// Add this node into skip list.
var (
highestLocked = -1 // the highest level being locked by this process
valid = true
pred, succ, prevPred *intnode[valueT]
)
if level == 0 {
level = s.randomlevel()
if level > hl {
// If the highest level is updated, usually means that many goroutines
// are inserting items. Hopefully we can find a better path in next loop.
// TODO(zyh): consider filling the preds if s.header[level].next == nil,
// but this strategy's performance is almost the same as the existing method.
continue
}
}
for layer := 0; valid && layer < level; layer++ {
pred = preds[layer] // target node's previous node
succ = succs[layer] // target node's next node
if pred != prevPred { // the node in this layer could be locked by previous loop
pred.mu.Lock()
highestLocked = layer
prevPred = pred
}
// valid check if there is another node has inserted into the skip list in this layer during this process.
// It is valid if:
// 1. The previous node and next node both are not marked.
// 2. The previous node's next node is succ in this layer.
valid = !pred.flags.Get(marked) && pred.loadNext(layer) == succ && (succ == nil || !succ.flags.Get(marked))
}
if !valid {
unlockint(preds, highestLocked)
continue
}
value := f()
nn := newIntNode(key, value, level)
for layer := 0; layer < level; layer++ {
nn.storeNext(layer, succs[layer])
preds[layer].atomicStoreNext(layer, nn)
}
nn.flags.SetTrue(fullyLinked)
unlockint(preds, highestLocked)
atomic.AddInt64(&s.length, 1)
return value, false
}
}
// Delete deletes the value for a key.
func (s *IntMap[valueT]) Delete(key int) bool {
var (
nodeToDelete *intnode[valueT]
isMarked bool // represents if this operation mark the node
topLayer = -1
preds, succs [maxLevel]*intnode[valueT]
)
for {
lFound := s.findNodeDelete(key, &preds, &succs)
if isMarked || // this process mark this node or we can find this node in the skip list
lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (int(succs[lFound].level)-1) == lFound {
if !isMarked { // we don't mark this node for now
nodeToDelete = succs[lFound]
topLayer = lFound
nodeToDelete.mu.Lock()
if nodeToDelete.flags.Get(marked) {
// The node is marked by another process,
// the physical deletion will be accomplished by another process.
nodeToDelete.mu.Unlock()
return false
}
nodeToDelete.flags.SetTrue(marked)
isMarked = true
}
// Accomplish the physical deletion.
var (
highestLocked = -1 // the highest level being locked by this process
valid = true
pred, succ, prevPred *intnode[valueT]
)
for layer := 0; valid && (layer <= topLayer); layer++ {
pred, succ = preds[layer], succs[layer]
if pred != prevPred { // the node in this layer could be locked by previous loop
pred.mu.Lock()
highestLocked = layer
prevPred = pred
}
// valid check if there is another node has inserted into the skip list in this layer
// during this process, or the previous is deleted by another process.
// It is valid if:
// 1. the previous node exists.
// 2. no another node has inserted into the skip list in this layer.
valid = !pred.flags.Get(marked) && pred.atomicLoadNext(layer) == succ
}
if !valid {
unlockint(preds, highestLocked)
continue
}
for i := topLayer; i >= 0; i-- {
// Now we own the `nodeToDelete`, no other goroutine will modify it.
// So we don't need `nodeToDelete.loadNext`
preds[i].atomicStoreNext(i, nodeToDelete.loadNext(i))
}
nodeToDelete.mu.Unlock()
unlockint(preds, highestLocked)
atomic.AddInt64(&s.length, -1)
return true
}
return false
}
}
// Range calls f sequentially for each key and value present in the skipmap.
// If f returns false, range stops the iteration.
//
// Range does not necessarily correspond to any consistent snapshot of the Map's
// contents: no key will be visited more than once, but if the value for any key
// is stored or deleted concurrently, Range may reflect any mapping for that key
// from any point during the Range call.
func (s *IntMap[valueT]) Range(f func(key int, value valueT) bool) {
x := s.header.atomicLoadNext(0)
for x != nil {
if !x.flags.MGet(fullyLinked|marked, fullyLinked) {
x = x.atomicLoadNext(0)
continue
}
if !f(x.key, x.loadVal()) {
break
}
x = x.atomicLoadNext(0)
}
}
// Len returns the length of this skipmap.
func (s *IntMap[valueT]) Len() int {
return int(atomic.LoadInt64(&s.length))
}