-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathroutine_storage.go
73 lines (61 loc) · 1.31 KB
/
routine_storage.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
package routine
import (
"runtime"
"sync"
)
// We should limit the number of LocalStorage, to avoid performance issue.
// How about 64K at most? nobody would ever need so many storages...
const keyCnt = 1 << 16
// record using key, to support allocating and releasing
var (
keyMap = map[int]bool{}
keyLock sync.Mutex
keyIndex = 1000000
)
// allocate an unique key of storage.
func allocateKey() (key int, succ bool) {
keyLock.Lock()
defer keyLock.Unlock()
if len(keyMap) >= keyCnt {
return 0, false
}
for keyMap[keyIndex] {
keyIndex++
}
keyMap[keyIndex] = true
return keyIndex, true
}
// release the unique key of storage, it could be reused in future.
func releaseKey(id int) {
keyLock.Lock()
defer keyLock.Unlock()
delete(keyMap, id)
}
func keyCount() int {
keyLock.Lock()
defer keyLock.Unlock()
return len(keyMap)
}
type storage struct {
key int
}
func newStorage() *storage {
key, succ := allocateKey()
if !succ {
panic("Too many storages")
}
s := &storage{key: key}
runtime.SetFinalizer(s, func(s *storage) {
releaseKey(s.key)
})
return s
}
func (t *storage) Get() (v interface{}) {
return loadStore().get(t.key)
}
func (t *storage) Set(v interface{}) (oldValue interface{}) {
return loadStore().set(t.key, v)
}
func (t *storage) Del() (v interface{}) {
return loadStore().del(t.key)
}