Weighted Semaphore Limiter
Bound concurrent work by cost using a weighted semaphore, admitting tasks only while capacity remains.
Code
package limiter
import (
"context"
"errors"
"sync"
)
var ErrExhausted = errors.New("capacity exhausted")
type Weighted struct {
mu sync.Mutex
capacity int64
inUse int64
}
func New(capacity int64) *Weighted {
return &Weighted{capacity: capacity}
}
func (w *Weighted) TryAcquire(weight int64) error {
if weight <= 0 || weight > w.capacity {
return ErrExhausted
}
w.mu.Lock()
defer w.mu.Unlock()
if w.inUse+weight > w.capacity {
return ErrExhausted
}
w.inUse += weight
return nil
}
func (w *Weighted) Release(weight int64) {
w.mu.Lock()
defer w.mu.Unlock()
w.inUse -= weight
if w.inUse < 0 {
w.inUse = 0
}
}
func (w *Weighted) WithContext(ctx context.Context, weight int64, fn func() error) error {
if err := w.TryAcquire(weight); err != nil {
return err
}
defer w.Release(weight)
return fn()
}Inside the snippet
Structurally, expect the functions New, TryAcquire, Release and WithContext and nothing else.
Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Watch out for
- Errors are ordinary return values; skipping the
errcheck means using a zero value silently.
Using it
The entry-point signature is func New(capacity int64) *Weighted
New is the public entry point; everything else in the file exists to support it.
Key statements
func (w *Weighted) WithContext(ctx context.Context, weight int64, fn func() error) error {
if err := w.TryAcquire(weight); err != nil {
return err
}
defer w.Release(weight)
return fn()
}
func (w *Weighted) TryAcquire(weight int64) error {
if weight <= 0 || weight > w.capacity {
return ErrExhausted
}
w.mu.Lock()
defer w.mu.Unlock()
if w.inUse+weight > w.capacity {
return ErrExhausted
}
w.inUse += weight
return nil
}
func (w *Weighted) Release(weight int64) {
w.mu.Lock()
defer w.mu.Unlock()
w.inUse -= weight
if w.inUse < 0 {
w.inUse = 0
}
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does the snippet panic on failure?
- No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `New`, `TryAcquire`, `Release` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.