forked from timandy/routine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_local_map.go
85 lines (75 loc) · 1.64 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
83
84
85
package routine
var unset = &object{}
type object struct {
value Any
}
type threadLocalMap struct {
table []Any
}
func (mp *threadLocalMap) get(key ThreadLocal) Any {
index := key.Id()
lookup := mp.table
if index < len(lookup) {
return lookup[index]
}
return unset
}
func (mp *threadLocalMap) set(key ThreadLocal, value Any) {
index := key.Id()
lookup := mp.table
if index < len(lookup) {
lookup[index] = value
return
}
mp.expandAndSet(index, value)
}
func (mp *threadLocalMap) remove(key ThreadLocal) {
index := key.Id()
lookup := mp.table
if index < len(lookup) {
lookup[index] = unset
}
}
func (mp *threadLocalMap) expandAndSet(index int, value Any) {
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([]Any, 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([]Any, len(lookup))
copy(table, lookup)
for i := 0; i < len(table); i++ {
if c, ok := table[i].(Cloneable); ok {
table[i] = c.Clone()
}
}
return &threadLocalMap{table: table}
}
func fill(a []Any, fromIndex int, toIndex int, val Any) {
for i := fromIndex; i < toIndex; i++ {
a[i] = val
}
}