From 6e902df516361ad59ae6effff0af84b2c4b2de01 Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Sun, 29 Dec 2024 02:32:13 -0500 Subject: [PATCH] sync: Add Monitor.BorrowReturn --- sync/monitor.go | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/sync/monitor.go b/sync/monitor.go index d7712d0..7c5804d 100644 --- a/sync/monitor.go +++ b/sync/monitor.go @@ -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 ()) {