1
1
package lrc
2
2
3
3
import (
4
- "fmt"
5
4
"runtime"
6
- "sync"
7
5
"sync/atomic"
8
6
)
9
7
10
- const read_left int32 = - 1
11
- const read_right int32 = 1
8
+ const ReadOnLeft int32 = - 1
9
+ const ReadOnRight int32 = 1
12
10
13
11
type LRMap struct {
14
- readIndicators [2 ]* ReadIndicator
12
+ readIndicators [2 ]* readIndicator
15
13
versionIndex * int32
16
- leftRight * int32
14
+ sideToRead * int32
17
15
18
16
left map [int ]int
19
17
right map [int ]int
20
-
21
- wm sync.Mutex
22
18
}
23
19
24
20
func New () * LRMap {
25
21
26
22
m := & LRMap {
27
- readIndicators : [2 ]* ReadIndicator {
23
+ readIndicators : [2 ]* readIndicator {
28
24
newReadIndicator (),
29
25
newReadIndicator (),
30
26
},
31
27
versionIndex : new (int32 ),
32
- leftRight : new (int32 ),
28
+ sideToRead : new (int32 ),
33
29
34
30
left : make (map [int ]int ),
35
31
right : make (map [int ]int ),
36
-
37
- wm : sync.Mutex {},
38
32
}
39
33
40
34
* m .versionIndex = 0
41
- * m .leftRight = read_left
35
+ * m .sideToRead = ReadOnLeft
42
36
return m
43
37
}
44
38
@@ -73,8 +67,8 @@ func (lr *LRMap) Get(k int) (val int, exist bool) {
73
67
74
68
lvi := lr .arrive ()
75
69
76
- which := atomic .LoadInt32 (lr .leftRight )
77
- if which == read_left {
70
+ which := atomic .LoadInt32 (lr .sideToRead )
71
+ if which == ReadOnLeft {
78
72
val , exist = lr .left [k ]
79
73
} else {
80
74
val , exist = lr .right [k ]
@@ -86,20 +80,20 @@ func (lr *LRMap) Get(k int) (val int, exist bool) {
86
80
87
81
func (lr * LRMap ) Put (key , val int ) {
88
82
89
- which := atomic .LoadInt32 (lr .leftRight )
90
- if which == read_left {
83
+ side := atomic .LoadInt32 (lr .sideToRead )
84
+ if side == ReadOnLeft {
91
85
// write on right
92
86
lr .right [key ] = val
93
- atomic .StoreInt32 (lr .leftRight , read_right )
87
+ atomic .StoreInt32 (lr .sideToRead , ReadOnRight )
94
88
lr .toggleVersionAndWait ()
95
89
lr .left [key ] = val
96
- } else if which == read_right {
90
+ } else if side == ReadOnRight {
97
91
// write on left
98
92
lr .left [key ] = val
99
- atomic .StoreInt32 (lr .leftRight , read_left )
93
+ atomic .StoreInt32 (lr .sideToRead , ReadOnLeft )
100
94
lr .toggleVersionAndWait ()
101
95
lr .right [key ] = val
102
96
} else {
103
- fmt . Println ( "fuuuu " )
97
+ panic ( "illegal state: you can only read on LEFT or RIGHT " )
104
98
}
105
99
}
0 commit comments