-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
131 lines (99 loc) · 2.5 KB
/
map.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
package observer
import (
"runtime"
"sync"
"sync/atomic"
)
type entry struct {
key, val interface{}
del, ok bool
}
type store struct {
count uint64
values map[interface{}]interface{}
}
func (s *store) loadCount() uint64 { return atomic.LoadUint64(&s.count) }
func (s *store) setEntry(e *entry) {
if e.ok {
if !e.del {
s.values[e.key] = e.val
} else {
delete(s.values, e.key)
}
}
}
const flagAorB uint64 = 1 << 63
type Map struct {
count uint64
a, b store
writeMu sync.Mutex
writeCount uint64
writeEntry entry
}
func (m *Map) read(x uint64) *store {
if x >= flagAorB {
return &m.a
}
return &m.b
}
func (m *Map) write(x uint64) *store {
if x < flagAorB {
return &m.a
}
return &m.b
}
func (m *Map) Get(key interface{}) (val interface{}, ok bool) {
x := atomic.AddUint64(&m.count, 1) // rlock
read := m.read(x)
val, ok = read.values[key]
atomic.AddUint64(&read.count, 1) // rlock
return val, ok
}
func (m *Map) set(key, val interface{}, del bool) {
m.writeMu.Lock()
defer m.writeMu.Unlock()
x := atomic.LoadUint64(&m.count)
write := m.write(x)
// Spin until all readers have left.
for c := write.loadCount(); c != m.writeCount; c = write.loadCount() {
runtime.Gosched()
}
if write.values == nil {
write.values = make(map[interface{}]interface{})
}
write.setEntry(&m.writeEntry)
m.writeEntry = entry{key: key, val: val, del: del, ok: true}
write.setEntry(&m.writeEntry)
write.count = 0
// Switch A and B.
x = atomic.AddUint64(&m.count, flagAorB-m.writeCount)
m.writeCount = x & ^flagAorB
}
func (m *Map) Set(key, val interface{}) { m.set(key, val, false) }
func (m *Map) Del(key interface{}) { m.set(key, nil, true) }
type TxFn func(val interface{}, ok bool) (interface{}, bool)
func (m *Map) Tx(key interface{}, fn TxFn) (val interface{}, ok bool) {
m.writeMu.Lock()
defer m.writeMu.Unlock()
x := atomic.LoadUint64(&m.count)
write := m.write(x)
// Spin until all readers have left.
for c := write.loadCount(); c != m.writeCount; c = write.loadCount() {
runtime.Gosched()
}
if write.values == nil {
write.values = make(map[interface{}]interface{})
}
// Set entry from write on previous map.
write.setEntry(&m.writeEntry)
val, ok = write.values[key]
val, ok = fn(val, ok)
m.writeEntry = entry{key: key, val: val, del: false, ok: ok}
// Write entry from current write.
write.setEntry(&m.writeEntry)
write.count = 0
// Switch A and B.
x = atomic.AddUint64(&m.count, flagAorB-m.writeCount)
m.writeCount = x & ^flagAorB
return val, ok
}