Documentation
¶
Overview ¶
Package concurrency provides small, typed building blocks for in-process concurrent work: futures, bounded structured groups, ordered parallel maps, reusable worker pools, a token-bucket rate limiter and an adaptive (AIMD) concurrency limiter.
Choose an abstraction by the shape and lifetime of the work:
- Future, created by Go, Completed or Failed: one asynchronous result that is awaited later.
- Group: a scoped batch of related callbacks that share cancellation and join their errors.
- ParallelMap: one function applied to a slice with bounded concurrency, results in input order.
- Pool: an ongoing stream of typed inputs processed by one reusable worker function, with separate worker and queue limits.
- Limiter: a token bucket that caps the rate of operations or bytes.
- Adaptive: a concurrency limit that follows downstream feedback.
Futures, groups, pools, limiters and permits are safe for concurrent use. Operations that block take a context.Context and return context.Cause when it is done first. Configuration and state errors are the sentinels ErrClosed, ErrInvalidLimit and ErrNilFunction; compare them with errors.Is.
The package depends only on the Go standard library and does no logging.
Example ¶
Square numbers with at most two concurrent calls; results keep input order.
package main
import (
"context"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
ctx := context.Background()
squares, err := concurrency.ParallelMap(ctx, []int{1, 2, 3, 4}, 2, func(ctx context.Context, n int) (int, error) {
if err := context.Cause(ctx); err != nil {
return 0, err
}
return n * n, nil
})
if err != nil {
panic(err)
}
fmt.Println(squares)
}
Output: [1 4 9 16]
Index ¶
Examples ¶
Constants ¶
const DefaultAdaptiveDecreaseFactor = 0.7
DefaultAdaptiveDecreaseFactor is the AdaptiveOptions.DecreaseFactor used when the option is zero.
Variables ¶
var ( // ErrClosed is returned by Group.Go after Group.Wait was called and by // Pool.Submit after Pool.Close was called. ErrClosed = errors.New("concurrency: closed") // ErrInvalidLimit is returned for an invalid group or map limit, pool // worker or queue size, limiter rate, burst or token count, or adaptive // option. ErrInvalidLimit = errors.New("concurrency: invalid limit") // ErrNilFunction is returned when a required callback or worker function // is nil. ErrNilFunction = errors.New("concurrency: nil function") )
Sentinel errors returned by this package. Their values and texts are part of the API; compare with errors.Is.
Functions ¶
func ParallelMap ¶
func ParallelMap[T, R any](ctx context.Context, values []T, limit int, fn func(context.Context, T) (R, error)) ([]R, error)
ParallelMap calls fn for every element of values with at most limit calls running at once and returns the results in input order. Calls share a context derived from ctx that is canceled by the first error. On any error ParallelMap stops admitting new elements, waits for the admitted calls and returns a nil slice with the callback errors joined in input order, or with the admission error (such as the cancellation cause of ctx) if no callback failed. It returns ErrNilFunction for a nil fn and ErrInvalidLimit for a non-positive limit.
Example ¶
package main
import (
"context"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
values, _ := concurrency.ParallelMap(context.Background(), []int{1, 2, 3}, 2, func(_ context.Context, value int) (int, error) {
return value * value, nil
})
fmt.Println(values)
}
Output: [1 4 9]
Types ¶
type Adaptive ¶
type Adaptive struct {
// contains filtered or unexported fields
}
Adaptive is a concurrency limiter whose limit adapts with additive increase and multiplicative decrease (AIMD). Successes slowly raise the limit up to Max; overloads quickly lower it down to Min. Blocked Acquire calls are admitted in FIFO order whenever a permit is released or the limit grows. An Adaptive is safe for concurrent use.
After the limit decreases, overloads reported by permits acquired before that decrease do not decrease it again, so one burst of concurrent overloads shrinks the limit once rather than once per in-flight request.
Example ¶
package main
import (
"context"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
adaptive, err := concurrency.NewAdaptive(concurrency.AdaptiveOptions{
Min: 1,
Max: 8,
Initial: 4,
IncreaseAfter: 1,
DecreaseFactor: 0.5,
})
if err != nil {
panic(err)
}
permit, err := adaptive.Acquire(context.Background())
if err != nil {
panic(err)
}
permit.Release(concurrency.Success)
fmt.Println(adaptive.Limit())
permit, err = adaptive.Acquire(context.Background())
if err != nil {
panic(err)
}
permit.Release(concurrency.Overload) // For example, the server answered 429.
fmt.Println(adaptive.Limit())
}
Output: 5 2
func NewAdaptive ¶
func NewAdaptive(options AdaptiveOptions) (*Adaptive, error)
NewAdaptive returns an AIMD concurrency limiter. It returns ErrInvalidLimit unless 1 <= Min <= Initial <= Max after defaults, IncreaseAfter >= 0, and DecreaseFactor is in (0, 1).
func (*Adaptive) Acquire ¶
Acquire blocks until fewer than Limit permits are in flight and no earlier Acquire is waiting, then returns a permit. If ctx is done first, it returns context.Cause(ctx); a permit granted before the cancellation was observed wins and is returned with a nil error.
type AdaptiveOptions ¶
type AdaptiveOptions struct {
Min int
Max int
Initial int
IncreaseAfter int
DecreaseFactor float64
}
AdaptiveOptions configures NewAdaptive.
Max is required. Min defaults to 1 and Initial defaults to Min. IncreaseAfter is the number of Success releases that raise the limit by one; 0 uses the current limit, which grows the limit by about one per window of completed work. DecreaseFactor in (0, 1) scales the limit down on Overload and defaults to DefaultAdaptiveDecreaseFactor.
type Future ¶
type Future[T any] struct { // contains filtered or unexported fields }
Future is the result of one asynchronous operation: a value of type T and an error. It is resolved exactly once; later resolutions are ignored. The zero Future is not usable; create futures with Go, Completed or Failed, or obtain them from Pool.Submit. A Future is safe for concurrent use and may be awaited by any number of goroutines.
func Go ¶
Go runs fn(ctx) in a new goroutine and returns a future for its result. ctx controls the work; Go itself never blocks. If fn is nil, the returned future is already resolved with ErrNilFunction. Panics in fn are not recovered.
Example ¶
package main
import (
"context"
"errors"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
workCtx, cancelWork := context.WithCancel(context.Background())
defer cancelWork()
release := make(chan struct{})
future := concurrency.Go(workCtx, func(ctx context.Context) (int, error) {
select {
case <-release:
return 42, nil
case <-ctx.Done():
return 0, context.Cause(ctx)
}
})
// Canceling the context of one Await does not cancel the work.
waitCtx, cancelWait := context.WithCancel(context.Background())
cancelWait()
_, err := future.Await(waitCtx)
fmt.Println(errors.Is(err, context.Canceled))
close(release)
value, err := future.Await(context.Background())
fmt.Println(value, err)
}
Output: true 42 <nil>
func (*Future[T]) Await ¶
Await blocks until the future is resolved or ctx is done. It returns the published value and error. If ctx is done first, Await returns the zero value and context.Cause(ctx); a result that is already published wins over the cancellation. Canceling ctx affects only this wait, never the work.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group runs a scoped batch of related callbacks with bounded concurrency. Callbacks share a context derived from the group's parent; the first callback error cancels it with that error as the cause. Wait closes the group to new work, drains admitted callbacks and joins their errors in submission order. A Group is single-use and safe for concurrent use.
Example ¶
package main
import (
"context"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
group, err := concurrency.NewGroup(context.Background(), 2)
if err != nil {
panic(err)
}
inputs := []int{1, 2, 3}
results := make([]int, len(inputs))
for index, value := range inputs {
if err := group.Go(func(ctx context.Context) error {
if err := context.Cause(ctx); err != nil {
return err
}
results[index] = value * value
return nil
}); err != nil {
_ = group.Wait()
panic(err)
}
}
if err := group.Wait(); err != nil {
panic(err)
}
fmt.Println(results)
}
Output: [1 4 9]
func NewGroup ¶
NewGroup returns a group whose callbacks run under a context derived from parent, with at most limit callbacks running at once. It returns ErrInvalidLimit if limit is not positive.
func (*Group) Go ¶
Go admits fn and runs it in a new goroutine with the group context. It blocks while limit callbacks are running. It returns ErrNilFunction for a nil fn, ErrClosed once Wait has been called (including while Go is blocked waiting for capacity), and the context cause if the group context is done before fn is admitted; in those cases fn does not run. Panics in fn are not recovered.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is a token bucket. It holds at most burst tokens and refills at rate tokens per second. It starts full. Waiters are served in FIFO order, so a large request is not starved by smaller ones. A Limiter is safe for concurrent use.
A rate of 0 never refills: only the initial burst is available until SetRate raises the rate. A rate of math.Inf(1) is unlimited: every request succeeds immediately, including requests larger than burst.
Example ¶
package main
import (
"context"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
limiter, err := concurrency.NewLimiter(1000, 2)
if err != nil {
panic(err)
}
fmt.Println(limiter.TryAcquire(2), limiter.TryAcquire(1))
fmt.Println(limiter.Wait(context.Background(), 1))
}
Output: true false <nil>
func NewLimiter ¶
NewLimiter returns a full token bucket with the given refill rate in tokens per second and capacity burst. It returns ErrInvalidLimit if rate is negative or NaN, or if burst is not positive.
func (*Limiter) SetRate ¶
SetRate changes the refill rate. Tokens accrued at the previous rate are kept, leaving an unlimited rate starts from a full bucket, and blocked waiters are re-evaluated immediately. It returns ErrInvalidLimit, leaving the rate unchanged, if rate is negative or NaN.
func (*Limiter) TryAcquire ¶
TryAcquire takes n tokens if they are available now and no Wait call is queued ahead of it. It never blocks. It reports false for negative n and, unless the rate is unlimited, for n greater than burst.
func (*Limiter) Wait ¶
Wait blocks until n tokens are available and takes them, or until ctx is done. It returns ErrInvalidLimit for negative n and, unless the rate is unlimited, for n greater than burst. If ctx is done first, Wait returns context.Cause(ctx) and takes no tokens; tokens granted before the cancellation was observed win, and Wait returns nil.
type Outcome ¶
type Outcome int
Outcome reports how the work guarded by a Permit went.
const ( // Success counts toward an additive increase of the limit. Success Outcome = iota // Overload multiplicatively decreases the limit. Use it for signals that // the downstream is saturated, such as HTTP 429 or 503 responses and // timeouts. Overload // Failure leaves the limit unchanged. Use it for errors that say nothing // about downstream capacity. Failure )
type Permit ¶
type Permit struct {
// contains filtered or unexported fields
}
Permit is one unit of admitted concurrency. Release it exactly once when the guarded work finishes; later calls are no-ops. The zero Permit is a no-op.
type Pool ¶
type Pool[I, O any] struct { // contains filtered or unexported fields }
Pool processes typed inputs with one reusable worker function. At most workers worker calls run at once, and at most workers+queue submissions are admitted (running or queued) at a time. Each admitted submission gets its own Future; a worker error resolves only that future and does not affect other submissions. Call Close to reject new submissions and Wait to drain admitted work. A Pool is safe for concurrent use.
Example ¶
package main
import (
"context"
"fmt"
concurrency "github.com/justusschock/concurrency"
)
func main() {
ctx := context.Background()
pool, err := concurrency.NewPool(ctx, 2, 2, func(_ context.Context, value int) (int, error) {
return value * value, nil
})
if err != nil {
panic(err)
}
futures := make([]*concurrency.Future[int], 0, 4)
for _, value := range []int{1, 2, 3, 4} {
future, err := pool.Submit(ctx, value)
if err != nil {
panic(err)
}
futures = append(futures, future)
}
pool.Close()
pool.Wait()
for _, future := range futures {
value, err := future.Await(ctx)
fmt.Println(value, err)
}
}
Output: 1 <nil> 4 <nil> 9 <nil> 16 <nil>
func NewPool ¶
func NewPool[I, O any](ctx context.Context, workers, queue int, worker func(context.Context, I) (O, error)) (*Pool[I, O], error)
NewPool returns a pool that runs worker with ctx for every admitted input. It returns ErrInvalidLimit if workers is not positive or queue is negative and ErrNilFunction if worker is nil.
func (*Pool[I, O]) Close ¶
func (p *Pool[I, O]) Close()
Close rejects new submissions and unblocks submissions waiting for capacity with ErrClosed. Admitted work keeps running. Close is idempotent.
func (*Pool[I, O]) Submit ¶
Submit blocks until the pool admits input or ctx is done, and returns the future of the admitted job. ctx bounds only the admission wait: once admitted, the worker runs with the pool context and canceling ctx does not cancel it. Submit returns ErrClosed after Close (including while blocked waiting for capacity) and context.Cause(ctx) if ctx is done before admission. Panics in the worker are not recovered.