github.com/hdt3213/godis@v1.2.9/lib/sync/wait/wait.go (about) 1 package wait 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 // Wait is similar with sync.WaitGroup which can wait with timeout 9 type Wait struct { 10 wg sync.WaitGroup 11 } 12 13 // Add adds delta, which may be negative, to the WaitGroup counter. 14 func (w *Wait) Add(delta int) { 15 w.wg.Add(delta) 16 } 17 18 // Done decrements the WaitGroup counter by one 19 func (w *Wait) Done() { 20 w.wg.Done() 21 } 22 23 // Wait blocks until the WaitGroup counter is zero. 24 func (w *Wait) Wait() { 25 w.wg.Wait() 26 } 27 28 // WaitWithTimeout blocks until the WaitGroup counter is zero or timeout 29 // returns true if timeout 30 func (w *Wait) WaitWithTimeout(timeout time.Duration) bool { 31 c := make(chan struct{}, 1) 32 go func() { 33 defer close(c) 34 w.Wait() 35 c <- struct{}{} 36 }() 37 select { 38 case <-c: 39 return false // completed normally 40 case <-time.After(timeout): 41 return true // timed out 42 } 43 }