Use golang.org/x/sync/semaphore to create a weighted semaphore that limits concurrent operations by acquiring tokens with specific weights.
import "golang.org/x/sync/semaphore"
// Create a semaphore allowing 5 concurrent units of work
sem := semaphore.NewWeighted(5)
// Acquire 2 units of work (blocks if insufficient capacity)
if err := sem.Acquire(ctx, 2); err != nil {
return err
}
defer sem.Release(2)
// Perform your work here