github.com/cyub/threadlocal@v0.0.0-20220816024249-5db4997a97f4/README.md (about)

     1  # Go ThreadLocal
     2  
     3  Go version of ThreadLocal is like [Java ThreadLocal](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html)
     4  
     5  ## Usage
     6  
     7  ```go
     8  import (
     9  	"fmt"
    10  	"sync"
    11  
    12  	"github.com/cyub/threadlocal"
    13  )
    14  
    15  var wg sync.WaitGroup
    16  
    17  func main() {
    18  	tl1 := threadlocal.New()
    19  	tl1.Set("hello, world")
    20  
    21  	n := 10
    22  	wg.Add(n)
    23  	for i := 0; i < n; i++ {
    24  		go func(idx int) {
    25  			defer wg.Done()
    26  			fmt.Printf("id: %d, tid: %d, val: %v\n", idx, threadlocal.ThreadId(), tl1.Get())
    27  		}(i)
    28  	}
    29  	wg.Wait()
    30  	fmt.Printf("id: %d, tid: %d, val: %v\n", n, threadlocal.ThreadId(), tl1.Get())
    31  }
    32  ```
    33  
    34  You can run the following line of code to test:
    35  
    36  > go run example/main.go