File tree 2 files changed +37
-1
lines changed
2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change 10
10
package sizedwaitgroup
11
11
12
12
import (
13
+ "context"
13
14
"math"
14
15
"sync"
15
16
)
@@ -47,8 +48,26 @@ func New(limit int) SizedWaitGroup {
47
48
//
48
49
// See sync.WaitGroup documentation for more information.
49
50
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
+ }
51
69
s .wg .Add (1 )
70
+ return nil
52
71
}
53
72
54
73
// Done decrements the SizedWaitGroup counter.
Original file line number Diff line number Diff line change 1
1
package sizedwaitgroup
2
2
3
3
import (
4
+ "context"
4
5
"sync/atomic"
5
6
"testing"
6
7
)
@@ -66,3 +67,19 @@ func TestNoThrottling(t *testing.T) {
66
67
t .Fatalf ("%d, not all routines have been executed." , c )
67
68
}
68
69
}
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
+ }
You can’t perform that action at this time.
0 commit comments