Semaphore Weighted Concurrency Limit

Use weighted semaphore for concurrency limiting with different resource weights.

GoResilience

Code

snippet
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 })
}