Go version of ThreadLocal is like Java ThreadLocal
import (
"fmt"
"sync"
"github.com/cyub/threadlocal"
)
var wg sync.WaitGroup
func main() {
tl1 := threadlocal.New()
tl1.Set("hello, world")
n := 10
wg.Add(n)
for i := 0; i < n; i++ {
go func(idx int) {
defer wg.Done()
fmt.Printf("id: %d, tid: %d, val: %v\n", idx, threadlocal.ThreadId(), tl1.Get())
}(i)
}
wg.Wait()
fmt.Printf("id: %d, tid: %d, val: %v\n", n, threadlocal.ThreadId(), tl1.Get())
}
You can run the following line of code to test:
go run example/main.go