-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgls.go
More file actions
55 lines (48 loc) · 933 Bytes
/
gls.go
File metadata and controls
55 lines (48 loc) · 933 Bytes
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
package gls
import (
"fmt"
"runtime"
"strconv"
"strings"
"sync"
)
var gls struct {
m map[int64]map[interface{}]interface{}
sync.RWMutex
}
func init() {
gls.m = make(map[int64]map[interface{}]interface{})
}
func GetGoId() int64 {
var (
buf [64]byte
n = runtime.Stack(buf[:], false)
stk = strings.TrimPrefix(string(buf[:n]), "goroutine ")
)
idField := strings.Fields(stk)[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Errorf("can not get goroutine id: %v", err))
}
return int64(id)
}
func Get(key interface{}) interface{} {
gls.RLock()
defer gls.RUnlock()
goId := GetGoId()
return gls.m[goId][key]
}
func Set(key interface{}, v interface{}) {
gls.Lock()
defer gls.Unlock()
goId := GetGoId()
if _, ok := gls.m[goId][key]; !ok {
gls.m[goId] = make(map[interface{}]interface{})
}
gls.m[goId][key] = v
}
func Clean() {
gls.Lock()
defer gls.Unlock()
delete(gls.m, GetGoId())
}