finish
All checks were successful
pr / test (pull_request) Successful in 2m31s
lint / lint (pull_request) Successful in 10m38s

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2024-03-09 22:59:35 +03:00
parent 1759bec5a9
commit cf877845a1

View File

@ -3,19 +3,17 @@ package sync
import (
"context"
"sync"
"sync/atomic"
)
type WaitGroup struct {
wg *sync.WaitGroup
c *atomic.Int64
c int
mu sync.Mutex
}
func WrapWaitGroup(wg *sync.WaitGroup) *WaitGroup {
g := &WaitGroup{
wg: wg,
c: &(atomic.Int64{}),
}
return g
}
@ -27,14 +25,14 @@ func NewWaitGroup() *WaitGroup {
func (g *WaitGroup) Add(n int) {
g.mu.Lock()
g.c.Add(int64(n))
g.c += n
g.wg.Add(n)
g.mu.Unlock()
}
func (g *WaitGroup) Done() {
g.mu.Lock()
g.c.Add(int64(-1))
g.c += -1
g.wg.Add(-1)
g.mu.Unlock()
}
@ -53,9 +51,9 @@ func (g *WaitGroup) WaitContext(ctx context.Context) {
select {
case <-ctx.Done():
g.mu.Lock()
g.wg.Add(-int(g.c.Load()))
g.wg.Add(-g.c)
<-done
g.wg.Add(int(g.c.Load()))
g.wg.Add(g.c)
g.mu.Unlock()
return
case <-done:
@ -64,5 +62,8 @@ func (g *WaitGroup) WaitContext(ctx context.Context) {
}
func (g *WaitGroup) Waiters() int {
return int(g.c.Load())
g.mu.Lock()
c := g.c
g.mu.Unlock()
return c
}