-
Notifications
You must be signed in to change notification settings - Fork 8
/
sync.go
51 lines (41 loc) · 804 Bytes
/
sync.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"sync"
)
type LimitedWaitGroup struct {
wg sync.WaitGroup
mu *sync.Mutex
cond *sync.Cond
limit, copasity int
}
func NewLimitedWaitGroup(limit int) *LimitedWaitGroup {
mu := new(sync.Mutex)
return &LimitedWaitGroup{
mu: mu,
cond: sync.NewCond(mu),
limit: limit,
copasity: limit,
}
}
func (lg *LimitedWaitGroup) Add(delta int) {
lg.mu.Lock()
defer lg.mu.Unlock()
if delta > lg.limit {
panic(`LimitedWaitGroup: delta must not exceed limit`)
}
for lg.copasity < 1 {
lg.cond.Wait()
}
lg.copasity -= delta
lg.wg.Add(delta)
}
func (lg *LimitedWaitGroup) Done() {
lg.mu.Lock()
defer lg.mu.Unlock()
lg.copasity++
lg.cond.Signal()
lg.wg.Done()
}
func (lg *LimitedWaitGroup) Wait() {
lg.wg.Wait()
}