Created
March 18, 2019 13:42
-
-
Save maorfr/9f8ad44e732e489d498d6ddebf181a49 to your computer and use it in GitHub Desktop.
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
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