Created
May 31, 2015 17:13
-
-
Save michiwend/4330d226440d1e863c2e to your computer and use it in GitHub Desktop.
Limited wait group in Go (Golang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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