Skip to content

Commit 5e7302b

Browse files
authored
Merge pull request #5 from hstern/context
Add context awareness
2 parents 5582a67 + 0da8c97 commit 5e7302b

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

sizedwaitgroup.go

+20-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
package sizedwaitgroup
1111

1212
import (
13+
"context"
1314
"math"
1415
"sync"
1516
)
@@ -47,8 +48,26 @@ func New(limit int) SizedWaitGroup {
4748
//
4849
// See sync.WaitGroup documentation for more information.
4950
func (s *SizedWaitGroup) Add() {
50-
s.current <- struct{}{}
51+
s.AddWithContext(context.Background())
52+
}
53+
54+
// AddWithContext increments the internal WaitGroup counter.
55+
// It can be blocking if the limit of spawned goroutines
56+
// has been reached. It will stop blocking when Done is
57+
// been called, or when the context is canceled. Returns nil on
58+
// success or an error if the context is canceled before the lock
59+
// is acquired.
60+
//
61+
// See sync.WaitGroup documentation for more information.
62+
func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error {
63+
select {
64+
case <-ctx.Done():
65+
return ctx.Err()
66+
case s.current <- struct{}{}:
67+
break
68+
}
5169
s.wg.Add(1)
70+
return nil
5271
}
5372

5473
// Done decrements the SizedWaitGroup counter.

sizedwaitgroup_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sizedwaitgroup
22

33
import (
4+
"context"
45
"sync/atomic"
56
"testing"
67
)
@@ -66,3 +67,19 @@ func TestNoThrottling(t *testing.T) {
6667
t.Fatalf("%d, not all routines have been executed.", c)
6768
}
6869
}
70+
71+
func TestAddWithContext(t *testing.T) {
72+
ctx, cancelFunc := context.WithCancel(context.TODO())
73+
74+
swg := New(1)
75+
76+
if err := swg.AddWithContext(ctx); err != nil {
77+
t.Fatalf("AddContext returned error: %v", err)
78+
}
79+
80+
cancelFunc()
81+
if err := swg.AddWithContext(ctx); err != context.Canceled {
82+
t.Fatalf("AddContext returned non-context.Canceled error: %v", err)
83+
}
84+
85+
}

0 commit comments

Comments
 (0)