-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadMeta.go
82 lines (71 loc) · 1.61 KB
/
threadMeta.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
package threadMeta
import (
"context"
"runtime"
"unsafe"
)
var threadMetaFlag uint64
func init() {
for i, b := range []byte("g.labels") {
t := uint64(b) << uint8(i*8)
threadMetaFlag |= t
}
}
// 48b
type threadMeta struct {
labels labelMap // pprof.labelMap
flag uint64 // 64bit flag
gid uint64 // goroutine id
ctx context.Context // runtime.iface
data interface{} // runtime.eface
}
func SetMeta(ctx context.Context, data interface{}) {
cm := currentMeta(true)
cm.ctx = ctx
cm.data = data
}
func GetMeta() (ctx context.Context, data interface{}) {
cm := currentMeta(false)
if cm != nil {
ctx, data = cm.ctx, cm.data
}
return
}
//go:norace
//go:nocheckptr
func currentMeta(create bool) (cm *threadMeta) {
ptr := runtime_getProfLabel()
gid := getg().goid
if !create {
if ptr == nil {
return nil
}
if cm = (*threadMeta)(ptr); cm.flag == threadMetaFlag && cm.gid == gid {
return cm
}
return nil
}
if ptr == nil {
cm = &threadMeta{flag: threadMetaFlag, gid: gid}
runtime.SetFinalizer(cm, (*threadMeta).finalize)
runtime_setProfLabel(unsafe.Pointer(cm))
} else if cm = (*threadMeta)(ptr); cm.flag != threadMetaFlag ||
cm.gid != gid { // inherits the labels of the goroutine that created it. todo recreate threadMeta
cm = &threadMeta{
labels: cm.labels,
flag: threadMetaFlag,
gid: gid,
}
runtime.SetFinalizer(cm, (*threadMeta).finalize)
runtime_setProfLabel(unsafe.Pointer(cm))
}
return cm
}
// finalize reset thread's memory.
func (t *threadMeta) finalize() {
t.labels = nil
t.flag = 0
t.gid = 0
t.ctx = nil
t.data = nil
}