go-util/sync/locker.go
Sasha Koshka a7cb9b50dc sync: Rename Locker to Monitor
Locker is an interface type in the stdlib sync package.
2024-12-22 19:11:50 -05:00

78 lines
2.0 KiB
Go

package usync
import "sync"
// Monitor guards access to a value. It must not be copied after first use.
type Monitor[T any] struct {
value T
mutex sync.Mutex
}
// NewMonitor creates a new Monitor with the specified value.
func NewMonitor[T any] (value T) Monitor[T] {
return Monitor[T] {
value: value,
}
}
// Set sets the value of the Monitor.
func (this *Monitor[T]) Set (value T) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.value = value
}
// Borrow borrows the value from the Monitor, and returns a function that must
// immediately be deferred, like this:
//
// value, done := Monitor.Borrow()
// defer done()
//
// From the time Borrow is called to the time the done function is called, it is
// safe to access the locked object from within the current goroutine.
func (this *Monitor[T]) Borrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}
// RWMonitor guards separate read/write access to a value.
type RWMonitor[T any] struct {
value T
mutex sync.RWMutex
}
// NewRWMonitor creates a new Monitor with the specified value. It must not be
// copied after first use.
func NewRWMonitor[T any] (value T) RWMonitor[T] {
return RWMonitor[T] {
value: value,
}
}
// Set sets the value of the Monitor.
func (this *RWMonitor[T]) Set (value T) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.value = value
}
// Borrow borrows the value from the Monitor for write access, and returns a
// function that must immediately be deferred, like this:
//
// value, done := Monitor.Borrow()
// defer done()
//
// From the time Borrow is called to the time the done function is called, it is
// safe to access the locked object from within the current goroutine.
func (this *RWMonitor[T]) Borrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}
// RBorrow is like Borrow, but returns the item for read access only. Do not
// under any circumstances modify anything returned by this method.
func (this *RWMonitor[T]) RBorrow () (T, func ()) {
this.mutex.Lock()
return this.value, this.mutex.Unlock
}