From 27743dcf8717ade69f93b6e00f8236514abc63a0 Mon Sep 17 00:00:00 2001 From: Umputun Date: Mon, 16 Nov 2026 23:37:29 -0600 Subject: [PATCH] Add DiscardAfterThreshold option for SizedGroup DiscardAfterThreshold(n) accepts up to n calls in flight, running or waiting to run, and discards the rest. Go never blocks: accepted calls beyond the group size wait in their goroutines. A second semaphore of size n gates admission, released when the call's goroutine ends, including the canceled skip path. With n above the group size the option overrides Preemptive and Discard in any order, since either left on would block the caller or drop an admitted call holding its slot. With n at or below the group size, 0 included, it works as Discard. ErrSizedGroup treats it as Discard. Fixed #5 --- README.md | 12 ++++++ group_options.go | 13 +++++++ sizedgroup.go | 17 ++++++++- sizedgroup_test.go | 94 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 134 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6655389..6684c91 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/group_options.go b/group_options.go index 58c5de3..7614ab5 100644 --- a/group_options.go +++ b/group_options.go @@ -7,6 +7,7 @@ type options struct { preLock bool termOnError bool discardIfFull bool + threshold int } // GroupOption functional option type @@ -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 + } +} diff --git a/sizedgroup.go b/sizedgroup.go index 93e6f0a..75f67a8 100644 --- a/sizedgroup.go +++ b/sizedgroup.go @@ -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 @@ -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 } @@ -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 { @@ -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() { diff --git a/sizedgroup_test.go b/sizedgroup_test.go index bf2c178..d61f771 100644 --- a/sizedgroup_test.go +++ b/sizedgroup_test.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "runtime" + "sync" "sync/atomic" "testing" "time" @@ -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() {