github.com/timandy/routine@v1.1.4-0.20240507073150-e4a3e1fe2ba5/api_thread_local.go (about)

     1  package routine
     2  
     3  // ThreadLocal provides goroutine-local variables.
     4  type ThreadLocal[T any] interface {
     5  	// Get returns the value in the current goroutine's local threadLocals or inheritableThreadLocals, if it was set before.
     6  	Get() T
     7  
     8  	// Set copy the value into the current goroutine's local threadLocals or inheritableThreadLocals.
     9  	Set(value T)
    10  
    11  	// Remove delete the value from the current goroutine's local threadLocals or inheritableThreadLocals.
    12  	Remove()
    13  }
    14  
    15  // Supplier provides a function that returns a value of type T.
    16  type Supplier[T any] func() T
    17  
    18  // NewThreadLocal create and return a new ThreadLocal instance.
    19  // The initial value stored with the default value of type T.
    20  func NewThreadLocal[T any]() ThreadLocal[T] {
    21  	return &threadLocal[T]{index: nextThreadLocalIndex()}
    22  }
    23  
    24  // NewThreadLocalWithInitial create and return a new ThreadLocal instance.
    25  // The initial value stored as the return value of the method supplier.
    26  func NewThreadLocalWithInitial[T any](supplier Supplier[T]) ThreadLocal[T] {
    27  	return &threadLocal[T]{index: nextThreadLocalIndex(), supplier: supplier}
    28  }
    29  
    30  // NewInheritableThreadLocal create and return a new ThreadLocal instance.
    31  // The initial value stored with the default value of type T.
    32  // The value can be inherited to sub goroutines witch started by Go, GoWait, GoWaitResult methods.
    33  // The value can be captured to FutureTask which created by WrapTask, WrapWaitTask, WrapWaitResultTask methods.
    34  func NewInheritableThreadLocal[T any]() ThreadLocal[T] {
    35  	return &inheritableThreadLocal[T]{index: nextInheritableThreadLocalIndex()}
    36  }
    37  
    38  // NewInheritableThreadLocalWithInitial create and return a new ThreadLocal instance.
    39  // The initial value stored as the return value of the method supplier.
    40  // The value can be inherited to sub goroutines witch started by Go, GoWait, GoWaitResult methods.
    41  // The value can be captured to FutureTask which created by WrapTask, WrapWaitTask, WrapWaitResultTask methods.
    42  func NewInheritableThreadLocalWithInitial[T any](supplier Supplier[T]) ThreadLocal[T] {
    43  	return &inheritableThreadLocal[T]{index: nextInheritableThreadLocalIndex(), supplier: supplier}
    44  }