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