sync: Add Monitor.BorrowReturn
This commit is contained in:
parent
b9369570ae
commit
6e902df516
@ -25,7 +25,7 @@ func (this *Monitor[T]) Set (value T) {
|
||||
// Borrow borrows the value from the Monitor, and returns a function that must
|
||||
// immediately be deferred, like this:
|
||||
//
|
||||
// value, done := Monitor.Borrow()
|
||||
// value, done := monitor.Borrow()
|
||||
// defer done()
|
||||
//
|
||||
// From the time Borrow is called to the time the done function is called, it is
|
||||
@ -35,6 +35,19 @@ func (this *Monitor[T]) Borrow () (T, func ()) {
|
||||
return this.value, this.mutex.Unlock
|
||||
}
|
||||
|
||||
// BorrowReturn is like borrow, but returns a "done" function that takes in an
|
||||
// updated value. The intended use of this function is like this:
|
||||
//
|
||||
// value, done := monitor.BorrowReturn()
|
||||
// defer done(value)
|
||||
func (this *Monitor[T]) BorrowReturn () (T, func (T)) {
|
||||
this.mutex.Lock()
|
||||
return this.value, func (value T) {
|
||||
defer this.mutex.Unlock()
|
||||
this.value = value
|
||||
}
|
||||
}
|
||||
|
||||
// RWMonitor guards separate read/write access to a value.
|
||||
type RWMonitor[T any] struct {
|
||||
value T
|
||||
@ -59,7 +72,7 @@ func (this *RWMonitor[T]) Set (value T) {
|
||||
// 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()
|
||||
// value, done := monitor.Borrow()
|
||||
// defer done()
|
||||
//
|
||||
// From the time Borrow is called to the time the done function is called, it is
|
||||
@ -69,6 +82,19 @@ func (this *RWMonitor[T]) Borrow () (T, func ()) {
|
||||
return this.value, this.mutex.Unlock
|
||||
}
|
||||
|
||||
// BorrowReturn is like borrow, but returns a "done" function that takes in an
|
||||
// updated value. The intended use of this function is like this:
|
||||
//
|
||||
// value, done := monitor.BorrowReturn()
|
||||
// defer done(value)
|
||||
func (this *RWMonitor[T]) BorrowReturn () (T, func (T)) {
|
||||
this.mutex.Lock()
|
||||
return this.value, func (value T) {
|
||||
defer this.mutex.Unlock()
|
||||
this.value = value
|
||||
}
|
||||
}
|
||||
|
||||
// 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 ()) {
|
||||
|
Loading…
Reference in New Issue
Block a user