mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
util/coalescedop: add Wait
Wait blocks until no execution is in progress or pending, so a caller can make sure the requested work is done before shutting down. Updates tailscale/corp#52076 Signed-off-by: Nick Khyl <nickk@tailscale.com> Signed-off-by: Guy J Grigsby <guy@tailscale.com>
This commit is contained in:
1 parent
aab5f09be1
commit
4f3bddecff
2 files changed
+35
-1
No files matched your search
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user