-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsingleton.go
executable file
·95 lines (82 loc) · 1.77 KB
/
singleton.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
package purl
import (
"sync"
)
var (
num = 1 //0 is nil
mutex sync.Mutex
once sync.Once
index *indexTable
)
func getNext() int {
mutex.Lock()
ret := num
num++
mutex.Unlock()
return ret
}
//https://github.com/golang/go/issues/9477
type indexTable struct {
//key: string, the original key or value
//val: int
forwardIndex sync.Map
//key: int
//val: string, the original key or value
backwardIndex sync.Map
//key: string, the original key or value
//val: *sync.WaitGroup
waitMap sync.Map
//key: string, the original key or value
//val: *sync.RWMutex
forwardMutex sync.Map
//key: int
//val: *sync.RWMutex
backwardMutex sync.Map
}
func init() {
once.Do(func() {
index = new(indexTable)
})
}
func getIndex(skey string) (ikey int) {
if locker, ok := index.forwardMutex.Load(skey); ok {
locker.(*sync.RWMutex).RLock()
key, ok := index.forwardIndex.Load(skey)
locker.(*sync.RWMutex).RUnlock()
if ok {
ikey = key.(int)
return
}
}
obj := sync.WaitGroup{}
obj.Add(1)
wg, wgLoaded := index.waitMap.LoadOrStore(skey, &obj)
if !wgLoaded {
//only one goroutine execute here at a same time.
num := getNext()
locker := sync.RWMutex{}
index.forwardMutex.Store(skey, &locker)
index.backwardMutex.Store(num, &locker)
locker.Lock()
index.forwardIndex.Store(skey, num)
index.backwardIndex.Store(num, skey)
locker.Unlock()
wg.(*sync.WaitGroup).Done()
ikey = num
} else {
wg.(*sync.WaitGroup).Wait()
key, _ := index.forwardIndex.Load(skey)
ikey = key.(int)
}
return ikey
}
func getString(ikey int) (skey string) {
if locker, ok := index.backwardMutex.Load(ikey); ok {
locker.(*sync.RWMutex).RLock()
if key, ok := index.backwardIndex.Load(ikey); ok {
skey = key.(string)
}
locker.(*sync.RWMutex).RUnlock()
}
return skey
}