Skip to content

Instantly share code, notes, and snippets.

@michiwend
Created May 31, 2015 17:13
Show Gist options
  • Save michiwend/4330d226440d1e863c2e to your computer and use it in GitHub Desktop.
Save michiwend/4330d226440d1e863c2e to your computer and use it in GitHub Desktop.
Limited wait group in Go (Golang)
type LimitedWaitGroup struct {
limit int
count int
countChan chan int
}
func NewLimitedWaitGroup(limit int) *LimitedWaitGroup {
wg := LimitedWaitGroup{limit: limit}
wg.countChan = make(chan int)
return &wg
}
func (wg *LimitedWaitGroup) Add(delta int) {
if delta > wg.limit {
panic("delta higher then limit")
}
if wg.count+delta > wg.limit {
for <-wg.countChan+delta > wg.limit {
}
}
wg.count += delta
}
func (wg *LimitedWaitGroup) Done() {
wg.count--
wg.countChan <- wg.count
}
func (wg *LimitedWaitGroup) Wait() {
for <-wg.countChan > 0 {
}
close(wg.countChan)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment