Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ Another option is `Discard`, which will skip (won't start) goroutines if the sem
swg.Wait()
```

`DiscardAfterThreshold(n)` sits between the default mode and `Discard`. The group accepts up to `n` calls in flight, running or waiting to run, and discards the rest. The `Go` call never blocks: accepted calls beyond the group size wait in their goroutines until a slot frees up. With `n` above the group size, this option overrides `Preemptive` and `Discard`. With `n` at or below the group size, including 0, it works as `Discard`. It applies to `SizedGroup` only; `ErrSizedGroup` treats it as `Discard`.

```go
swg := syncs.NewSizedGroup(5, syncs.DiscardAfterThreshold(8)) // max 5 running, 3 more can wait
for i :=0; i<10; i++ {
swg.Go(func(ctx context.Context){
doThings(ctx) // 5 run in parallel, up to 3 wait for a free slot, the rest are discarded
})
}
swg.Wait()
```


### ErrSizedGroup

Expand Down
13 changes: 13 additions & 0 deletions group_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ type options struct {
preLock bool
termOnError bool
discardIfFull bool
threshold int
}

// GroupOption functional option type
Expand Down Expand Up @@ -34,3 +35,15 @@ func Discard(o *options) {
o.discardIfFull = true
o.preLock = true // discard implies preemptive
}

// DiscardAfterThreshold accepts up to threshold calls in flight, running or waiting to run, and
// discards the rest. The Go call never blocks: accepted calls past the group size wait in their
// goroutines. With threshold above the group size it overrides Preemptive and Discard in any order,
// otherwise it works as Discard. SizedGroup only, ErrSizedGroup treats it as Discard.
func DiscardAfterThreshold(threshold int) GroupOption {
return func(o *options) {
o.threshold = threshold
o.discardIfFull = true
o.preLock = true
}
}
17 changes: 15 additions & 2 deletions sizedgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import (
// SizedGroup interface enforces constructor usage and doesn't allow direct creation of sizedGroup
type SizedGroup struct {
options
wg sync.WaitGroup
sema Locker
wg sync.WaitGroup
sema Locker
admit Locker // caps calls in flight with DiscardAfterThreshold above size, nil otherwise
}

// NewSizedGroup makes wait group with limited size alive goroutines
Expand All @@ -21,6 +22,11 @@ func NewSizedGroup(size int, opts ...GroupOption) *SizedGroup {
for _, opt := range opts {
opt(&res.options)
}
if res.threshold > max(size, 1) { // match NewSemaphore's minimum size of 1
res.admit = NewSemaphore(res.threshold)
// left on, Preemptive blocks the caller and Discard drops an admitted call holding its slot
res.preLock, res.discardIfFull = false, false
}
return &res
}

Expand All @@ -40,6 +46,10 @@ func (g *SizedGroup) Go(fn func(ctx context.Context)) {
return
}

if g.admit != nil && !g.admit.TryLock() {
return
}

if g.preLock {
lockOk := g.sema.TryLock()
if !lockOk && g.discardIfFull {
Expand All @@ -54,6 +64,9 @@ func (g *SizedGroup) Go(fn func(ctx context.Context)) {
g.wg.Add(1)
go func() {
defer g.wg.Done()
if g.admit != nil {
defer g.admit.Unlock()
}

isLocked := g.preLock // with preLock the permit is already held by the time goroutine starts
defer func() {
Expand Down
94 changes: 94 additions & 0 deletions sizedgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -121,6 +122,99 @@ func TestSizedGroup_CanceledPreemptiveReleasesPermit(t *testing.T) {
swg.sema.Unlock()
}

func TestSizedGroup_DiscardAfterThreshold(t *testing.T) {
tests := []struct {
name string
opts []GroupOption
wantRun int32
}{
{name: "above size", opts: []GroupOption{DiscardAfterThreshold(7)}, wantRun: 7},
{name: "equal to size", opts: []GroupOption{DiscardAfterThreshold(3)}, wantRun: 3},
{name: "below size", opts: []GroupOption{DiscardAfterThreshold(1)}, wantRun: 3},
{name: "zero", opts: []GroupOption{DiscardAfterThreshold(0)}, wantRun: 3},
{name: "negative", opts: []GroupOption{DiscardAfterThreshold(-1)}, wantRun: 3},
{name: "preemptive before", opts: []GroupOption{Preemptive, DiscardAfterThreshold(7)}, wantRun: 7},
{name: "preemptive after", opts: []GroupOption{DiscardAfterThreshold(7), Preemptive}, wantRun: 7},
{name: "discard before", opts: []GroupOption{Discard, DiscardAfterThreshold(7)}, wantRun: 7},
{name: "discard after", opts: []GroupOption{DiscardAfterThreshold(7), Discard}, wantRun: 7},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
swg := NewSizedGroup(3, tt.opts...)
gate := make(chan struct{})
var mu sync.Mutex
var ran, running, maxRunning int32

submitted := make(chan struct{})
go func() {
defer close(submitted)
for range 20 {
swg.Go(func(context.Context) {
mu.Lock()
running++
maxRunning = max(maxRunning, running)
mu.Unlock()
<-gate
mu.Lock()
running--
ran++
mu.Unlock()
})
}
}()
select {
case <-submitted:
case <-time.After(time.Second):
close(gate)
t.Fatal("Go blocked the caller")
}
close(gate)
swg.Wait()

assert.Equal(t, tt.wantRun, ran)
assert.LessOrEqual(t, maxRunning, int32(3))
})
}
}

func TestSizedGroup_NegativeSizeRunsEveryCall(t *testing.T) {
swg := NewSizedGroup(-1)
gate := make(chan struct{})
var ran atomic.Int32
swg.Go(func(context.Context) {
<-gate
ran.Add(1)
})
swg.Go(func(context.Context) { ran.Add(1) })
close(gate)
swg.Wait()
assert.Equal(t, int32(2), ran.Load())
}

func TestSizedGroup_DiscardAfterThresholdCanceledReleasesSlots(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
swg := NewSizedGroup(1, DiscardAfterThreshold(3), Context(ctx))

release := make(chan struct{})
started := make(chan struct{})
swg.Go(func(context.Context) {
close(started)
<-release
})
<-started
swg.Go(func(context.Context) {})
swg.Go(func(context.Context) {})
cancel()
close(release)
swg.Wait()

for range 3 {
require.True(t, swg.admit.TryLock(), "every admitted call must return its slot")
}
}

// illustrates the use of a SizedGroup for concurrent, limited execution of goroutines.
func ExampleSizedGroup_go() {

Expand Down
Loading