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

     1  package threadlocal
     2  
     3  import (
     4  	"runtime"
     5  	"sync/atomic"
     6  )
     7  
     8  const HASH_INCREMENT = 0x61c88647
     9  
    10  type Threadlocal struct {
    11  	HashCode int
    12  }
    13  
    14  var nextHashCode = func() func() int {
    15  	var incr = int64(HASH_INCREMENT)
    16  	return func() int {
    17  		return int(atomic.AddInt64(&incr, 1))
    18  	}
    19  }()
    20  
    21  func New() *Threadlocal {
    22  	return &Threadlocal{
    23  		HashCode: nextHashCode(),
    24  	}
    25  }
    26  
    27  func (tl *Threadlocal) Set(data interface{}) {
    28  	if tl == nil {
    29  		panic("you should not directly set the threadlocal variable to nil")
    30  	}
    31  
    32  	runtime.LockOSThread()
    33  	defer runtime.UnlockOSThread()
    34  	currentThreadLocalMap().Set(tl, data)
    35  }
    36  
    37  func (tl *Threadlocal) Get() interface{} {
    38  	if tl == nil {
    39  		panic("you should not directly set the threadlocal variable to nil")
    40  	}
    41  
    42  	runtime.LockOSThread()
    43  	defer runtime.UnlockOSThread()
    44  	return currentThreadLocalMap().Get(tl)
    45  }
    46  
    47  func (tl *Threadlocal) Remove() {
    48  	if tl == nil {
    49  		panic("you should not directly set the threadlocal variable to nil")
    50  	}
    51  
    52  	runtime.LockOSThread()
    53  	defer runtime.UnlockOSThread()
    54  	currentThreadLocalMap().Remove(tl)
    55  }