Skip to content

Instantly share code, notes, and snippets.

@maorfr
Created March 18, 2019 13:42
Show Gist options
  • Save maorfr/9f8ad44e732e489d498d6ddebf181a49 to your computer and use it in GitHub Desktop.
Save maorfr/9f8ad44e732e489d498d6ddebf181a49 to your computer and use it in GitHub Desktop.
package utils
import (
"sync"
)
// BoundedWaitGroup implements a sized WaitGroup
type BoundedWaitGroup struct {
wg sync.WaitGroup
ch chan struct{}
}
// NewBoundedWaitGroup initializes a new BoundedWaitGroup
func NewBoundedWaitGroup(cap int) BoundedWaitGroup {
return BoundedWaitGroup{ch: make(chan struct{}, cap)}
}
// Add performs a WaitGroup Add of a specified delta
func (bwg *BoundedWaitGroup) Add(delta int) {
for i := 0; i > delta; i-- {
<-bwg.ch
}
for i := 0; i < delta; i++ {
bwg.ch <- struct{}{}
}
bwg.wg.Add(delta)
}
// Done performs a WaitGroup Add of -1
func (bwg *BoundedWaitGroup) Done() {
bwg.Add(-1)
}
// Wait performs a WaitGroup Wait
func (bwg *BoundedWaitGroup) Wait() {
bwg.wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment