1 Star 2 Fork 0

TimAndy/routine

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
thread_local_inheritable.go 1.55 KB
一键复制 编辑 原始数据 按行查看 历史
TimAndy 提交于 2022-07-20 21:10 +08:00 . Rename type Any to any
package routine
import "sync/atomic"
var inheritableThreadLocalIndex int32 = -1
func nextInheritableThreadLocalIndex() int {
index := atomic.AddInt32(&inheritableThreadLocalIndex, 1)
if index < 0 {
atomic.AddInt32(&inheritableThreadLocalIndex, -1)
panic("too many inheritable-thread-local indexed variables")
}
return int(index)
}
type inheritableThreadLocal struct {
index int
supplier Supplier
}
func (tls *inheritableThreadLocal) Get() any {
t := currentThread(true)
mp := tls.getMap(t)
if mp != nil {
v := mp.get(tls.index)
if v != unset {
return v
}
}
return tls.setInitialValue(t)
}
func (tls *inheritableThreadLocal) Set(value any) {
t := currentThread(true)
mp := tls.getMap(t)
if mp != nil {
mp.set(tls.index, value)
} else {
tls.createMap(t, value)
}
}
func (tls *inheritableThreadLocal) Remove() {
t := currentThread(false)
if t == nil {
return
}
mp := tls.getMap(t)
if mp != nil {
mp.remove(tls.index)
}
}
func (tls *inheritableThreadLocal) getMap(t *thread) *threadLocalMap {
return t.inheritableThreadLocals
}
func (tls *inheritableThreadLocal) createMap(t *thread, firstValue any) {
mp := &threadLocalMap{}
mp.set(tls.index, firstValue)
t.inheritableThreadLocals = mp
}
func (tls *inheritableThreadLocal) setInitialValue(t *thread) any {
value := tls.initialValue()
mp := tls.getMap(t)
if mp != nil {
mp.set(tls.index, value)
} else {
tls.createMap(t, value)
}
return value
}
func (tls *inheritableThreadLocal) initialValue() any {
if tls.supplier == nil {
return nil
}
return tls.supplier()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/timandy/routine.git
git@gitee.com:timandy/routine.git
timandy
routine
routine
main

搜索帮助