30 lines
454 B
Go
30 lines
454 B
Go
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()
|
|
}
|