diff --git a/util/coalescedop/coalescedop.go b/util/coalescedop/coalescedop.go index 3454fb88c..23e2f6252 100644 --- a/util/coalescedop/coalescedop.go +++ b/util/coalescedop/coalescedop.go @@ -22,6 +22,7 @@ import "sync" // The zero value is not valid; use [New]. type CoalescedOp struct { mu sync.Mutex + idle sync.Cond // on mu; signaled when running becomes false fn func() running bool pending bool @@ -29,7 +30,9 @@ type CoalescedOp struct { // New returns a CoalescedOp that calls fn. func New(fn func()) *CoalescedOp { - return &CoalescedOp{fn: fn} + c := &CoalescedOp{fn: fn} + c.idle.L = &c.mu + return c } // Do requests that the operation be run. If no execution is in @@ -50,6 +53,16 @@ func (c *CoalescedOp) Do() { go c.run() } +// Wait blocks until no execution is in progress or pending. +// It must not be called from the function itself. +func (c *CoalescedOp) Wait() { + c.mu.Lock() + defer c.mu.Unlock() + for c.running { + c.idle.Wait() + } +} + func (c *CoalescedOp) run() { for { c.fn() @@ -57,6 +70,7 @@ func (c *CoalescedOp) run() { c.mu.Lock() if !c.pending { c.running = false + c.idle.Broadcast() c.mu.Unlock() return } diff --git a/util/coalescedop/coalescedop_test.go b/util/coalescedop/coalescedop_test.go index 8eee8226c..2837f4b86 100644 --- a/util/coalescedop/coalescedop_test.go +++ b/util/coalescedop/coalescedop_test.go @@ -89,3 +89,23 @@ func TestNoPendingIfNotRequested(t *testing.T) { } }) } + +func TestWait(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var n atomic.Int32 + op := coalescedop.New(func() { + time.Sleep(time.Second) + n.Add(1) + }) + + op.Wait() // returns immediately when idle + + op.Do() + time.Sleep(time.Millisecond) // wait for the first execution to start + op.Do() + op.Wait() + if got := n.Load(); got != 2 { + t.Errorf("n=%d; want 2 (Wait should cover the pending execution)", got) + } + }) +}