/
localstorage.go
94 lines (81 loc) · 1.85 KB
/
localstorage.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
// Copyright 2021 冯立强 fenglq@tingyun.com. All rights reserved.
package tingyun3
import (
"sync"
)
// Unit is The GoRoutine LocalStorage Unit
type Unit struct {
lock sync.RWMutex
items map[int64]interface{}
}
func (u *Unit) init() {
u.items = nil
}
func (u *Unit) Exec(gid int64, update func(value interface{}) interface{}) {
u.lock.Lock()
defer u.lock.Unlock()
if u.items == nil {
if v := update(nil); v != nil {
u.items = map[int64]interface{}{gid: v}
}
} else {
if v, found := u.items[gid]; !found {
if v = update(nil); v != nil {
u.items[gid] = v
}
} else {
if n := update(v); n == nil {
delete(u.items, gid)
if len(u.items) == 0 {
u.items = nil
}
} else if n != v {
u.items[gid] = n
}
}
}
}
const (
// StorageNodes : The GoRoutine LocalStorage ArrayCount
localStorageNodes = 32768
)
var storages [localStorageNodes]Unit
func init() {
for i := 0; i < localStorageNodes; i++ {
storages[i].init()
}
}
func executeRoutineLocal(gid int64, update func(value interface{}) interface{}) {
storages[gid%localStorageNodes].Exec(gid, update)
}
// Get is Return the goroutine local storage value
func routineLocalExec(update func(value interface{}) interface{}) {
executeRoutineLocal(GetGID(), update)
}
func removeRoutineLocal(gid int64) interface{} {
var r interface{} = nil
executeRoutineLocal(gid, func(local interface{}) interface{} {
r = local
return nil
})
return r
}
// Remove is clean the goroutine local storage
func routineLocalRemove() interface{} {
var r interface{} = nil
routineLocalExec(func(local interface{}) interface{} {
r = local
return nil
})
return r
}
// Clear Routine Local Storage
func LocalClear() {
routineLocalRemove()
}
// RoutineLocal : 事务线程局部存储对象
type RoutineLocal struct {
action *Action
component *Component
pointers map[int]interface{}
}