-
Notifications
You must be signed in to change notification settings - Fork 28
/
thread_local_map.go
82 lines (72 loc) · 1.63 KB
/
thread_local_map.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 routine
var unset entry = &object{}
type object struct {
none bool //nolint:unused
}
type threadLocalMap struct {
table []entry
}
func (mp *threadLocalMap) get(index int) entry {
lookup := mp.table
if index < len(lookup) {
return lookup[index]
}
return unset
}
func (mp *threadLocalMap) set(index int, value entry) {
lookup := mp.table
if index < len(lookup) {
lookup[index] = value
return
}
mp.expandAndSet(index, value)
}
func (mp *threadLocalMap) remove(index int) {
lookup := mp.table
if index < len(lookup) {
lookup[index] = unset
}
}
func (mp *threadLocalMap) expandAndSet(index int, value entry) {
oldArray := mp.table
oldCapacity := len(oldArray)
newCapacity := index
newCapacity |= newCapacity >> 1
newCapacity |= newCapacity >> 2
newCapacity |= newCapacity >> 4
newCapacity |= newCapacity >> 8
newCapacity |= newCapacity >> 16
newCapacity++
newArray := make([]entry, newCapacity)
copy(newArray, oldArray)
fill(newArray, oldCapacity, newCapacity, unset)
newArray[index] = value
mp.table = newArray
}
func createInheritedMap() *threadLocalMap {
parent := currentThread(false)
if parent == nil {
return nil
}
parentMap := parent.inheritableThreadLocals
if parentMap == nil {
return nil
}
lookup := parentMap.table
if lookup == nil {
return nil
}
table := make([]entry, len(lookup))
copy(table, lookup)
for i := 0; i < len(table); i++ {
if c, ok := entryAssert[Cloneable](table[i]); ok {
table[i] = entry(c.Clone())
}
}
return &threadLocalMap{table: table}
}
func fill[T any](a []T, fromIndex int, toIndex int, val T) {
for i := fromIndex; i < toIndex; i++ {
a[i] = val
}
}