2024-03-09 20:00:12 +03:00
|
|
|
package sync
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type WaitGroup struct {
|
2024-03-09 22:52:24 +03:00
|
|
|
wg *sync.WaitGroup
|
2024-03-09 22:59:35 +03:00
|
|
|
c int
|
2024-03-09 22:55:42 +03:00
|
|
|
mu sync.Mutex
|
2024-03-09 20:00:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func WrapWaitGroup(wg *sync.WaitGroup) *WaitGroup {
|
|
|
|
g := &WaitGroup{
|
2024-03-09 22:52:24 +03:00
|
|
|
wg: wg,
|
2024-03-09 20:00:12 +03:00
|
|
|
}
|
|
|
|
return g
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWaitGroup() *WaitGroup {
|
|
|
|
var wg sync.WaitGroup
|
2024-03-09 22:55:42 +03:00
|
|
|
return WrapWaitGroup(&wg)
|
2024-03-09 20:00:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *WaitGroup) Add(n int) {
|
2024-03-09 22:52:24 +03:00
|
|
|
g.mu.Lock()
|
2024-03-09 22:59:35 +03:00
|
|
|
g.c += n
|
2024-03-09 20:00:12 +03:00
|
|
|
g.wg.Add(n)
|
2024-03-09 22:52:24 +03:00
|
|
|
g.mu.Unlock()
|
2024-03-09 20:00:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *WaitGroup) Done() {
|
2024-03-09 22:52:24 +03:00
|
|
|
g.mu.Lock()
|
2024-03-09 22:59:35 +03:00
|
|
|
g.c += -1
|
2024-03-09 22:52:24 +03:00
|
|
|
g.wg.Add(-1)
|
|
|
|
g.mu.Unlock()
|
2024-03-09 20:00:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *WaitGroup) Wait() {
|
|
|
|
g.wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *WaitGroup) WaitContext(ctx context.Context) {
|
|
|
|
done := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
g.wg.Wait()
|
|
|
|
close(done)
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
2024-03-09 22:52:24 +03:00
|
|
|
g.mu.Lock()
|
2024-03-09 22:59:35 +03:00
|
|
|
g.wg.Add(-g.c)
|
2024-03-09 22:52:24 +03:00
|
|
|
<-done
|
2024-03-09 22:59:35 +03:00
|
|
|
g.wg.Add(g.c)
|
2024-03-09 22:52:24 +03:00
|
|
|
g.mu.Unlock()
|
2024-03-09 20:03:24 +03:00
|
|
|
return
|
2024-03-09 20:00:12 +03:00
|
|
|
case <-done:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2024-03-09 22:52:24 +03:00
|
|
|
|
|
|
|
func (g *WaitGroup) Waiters() int {
|
2024-03-09 22:59:35 +03:00
|
|
|
g.mu.Lock()
|
|
|
|
c := g.c
|
|
|
|
g.mu.Unlock()
|
|
|
|
return c
|
2024-03-09 22:52:24 +03:00
|
|
|
}
|