Skip to content

Instantly share code, notes, and snippets.

@cstockton
Last active November 30, 2018 12:27
Show Gist options
  • Save cstockton/d611ced26bb6b4d3f7d4237abb8613c4 to your computer and use it in GitHub Desktop.
Save cstockton/d611ced26bb6b4d3f7d4237abb8613c4 to your computer and use it in GitHub Desktop.
Another example of sync.cond.
package xsync
import (
"fmt"
"sync"
"time"
)
type LimitGroup struct {
wg sync.WaitGroup
mu *sync.Mutex
c *sync.Cond
l, n int
}
func NewLimitGroup(n int) *LimitGroup {
mu := new(sync.Mutex)
return &LimitGroup{
mu: mu,
c: sync.NewCond(mu),
l: n,
n: n,
}
}
func (lg *LimitGroup) Add(delta int) {
lg.mu.Lock()
defer lg.mu.Unlock()
if delta > lg.l {
panic(`LimitGroup: delta must not exceed limit`)
}
for lg.n < 1 {
lg.c.Wait()
}
lg.n -= delta
lg.wg.Add(delta)
}
func (lg *LimitGroup) Done() {
lg.mu.Lock()
defer lg.mu.Unlock()
lg.n++
lg.c.Signal()
lg.wg.Done()
}
func (lg *LimitGroup) Wait() { lg.wg.Wait() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment