1 Star 2 Fork 0

TimAndy/routine

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
thread_local.go 1.39 KB
一键复制 编辑 原始数据 按行查看 历史
TimAndy 提交于 2022-07-20 21:10 . Rename type Any to any
package routine
import "sync/atomic"
var threadLocalIndex int32 = -1
func nextThreadLocalIndex() int {
index := atomic.AddInt32(&threadLocalIndex, 1)
if index < 0 {
atomic.AddInt32(&threadLocalIndex, -1)
panic("too many thread-local indexed variables")
}
return int(index)
}
type threadLocal struct {
index int
supplier Supplier
}
func (tls *threadLocal) 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 *threadLocal) 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 *threadLocal) Remove() {
t := currentThread(false)
if t == nil {
return
}
mp := tls.getMap(t)
if mp != nil {
mp.remove(tls.index)
}
}
func (tls *threadLocal) getMap(t *thread) *threadLocalMap {
return t.threadLocals
}
func (tls *threadLocal) createMap(t *thread, firstValue any) {
mp := &threadLocalMap{}
mp.set(tls.index, firstValue)
t.threadLocals = mp
}
func (tls *threadLocal) 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 *threadLocal) 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

搜索帮助