Semaphore Weighted Concurrency Limit

Use weighted semaphore for concurrency limiting with different resource weights.

GoResilience

Code

gosnippet
12 lines
package main
import ("context";"golang.org/x/sync/semaphore";"fmt")
func runWithLimit(ctx context.Context, weight int64, limit *semaphore.Weighted, fn func() error) error {
    if err := limit.Acquire(ctx, weight); err != nil { return err }
    defer limit.Release(weight)
    return fn()
}
func main() {
    limit := semaphore.NewWeighted(10)
    ctx := context.Background()
    runWithLimit(ctx, 3, limit, func() error { fmt.Println("heavy task"); return nil })
}

What the code does

Semaphore Weighted Concurrency Limit keeps everything in the functions runWithLimit and main.

Nothing falls through silently — 1 checkpoint test err != nil on the way through. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Points of care

  • Plan for an install step: golang.org/x/sync/semaphore is a real dependency, resolved by the package manager.
  • Failure is a return value (error), which keeps control flow explicit at every call site.

Applying it

Entry signature: func runWithLimit(ctx context.Context, weight int64, limit *semaphore.Weighted, fn func() error) error

The demo output is labeled (heavy task), so every line of output can be traced to the operation that made it.

The entry point wires runWithLimit together — run it once and the whole demo flows.

Statements that matter

func runWithLimit(ctx context.Context, weight int64, limit *semaphore.Weighted, fn func() error) error {
    if err := limit.Acquire(ctx, weight); err != nil { return err }
    defer limit.Release(weight)
    return fn()
}
func main() {
    limit := semaphore.NewWeighted(10)
    ctx := context.Background()
    runWithLimit(ctx, 3, limit, func() error { fmt.Println("heavy task"); return nil })
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As returned `error` values — 1 site in the snippet check `err` before using other results.
Which packages must be installed first?
Yes. The imports resolve to `golang.org/x/sync/semaphore`, which the package manager must provide.