mercury/internal/concurrent/value.go

31 lines
454 B
Go
Raw Normal View History

2023-09-04 03:33:13 +02:00
package concurrent
import "sync"
// Value is a struct providing concurrent access to another type.
// Note: T should be a concrete type, not a pointer.
type Value[T any] struct {
val T
mu sync.RWMutex
}
func NewValue[T any](value T) *Value[T] {
return &Value[T]{
val: value,
}
}
func (v *Value[T]) Get() T {
v.mu.RLock()
val := v.val
v.mu.RUnlock()
return val
}
func (v *Value[T]) Set(new T) {
v.mu.Lock()
v.val = new
v.mu.Unlock()
}