Semaphore Weighted Concurrency Limit
Use weighted semaphore for concurrency limiting with different resource weights.
Code
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 })
}Report a problem with this exampleOpens a pre-filled issue on GitHub.