Last active
November 30, 2018 12:27
-
-
Save cstockton/d611ced26bb6b4d3f7d4237abb8613c4 to your computer and use it in GitHub Desktop.
Another example of sync.cond.
This file contains hidden or 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 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