go / expert
Snippet
Resource Throttling with Weighted Semaphores
Weighted semaphores allow you to control access to a shared resource pool where different tasks may consume different amounts of that resource. Unlike a simple channel-based semaphore which only counts units, the weighted semaphore can grant access based on a variable 'cost' per operation, making it ideal for managing memory-intensive or CPU-bound tasks with varying weights.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
var sem = semaphore.NewWeighted(100)func handleRequest(ctx context.Context, cost int64) error {if err := sem.Acquire(ctx, cost); err != nil {return err}defer sem.Release(cost)doHeavyWork()return nil}
Breakdown
1
semaphore.NewWeighted(100)
Initializes a semaphore with a total available capacity of 100 units.
2
sem.Acquire(ctx, cost)
Blocks until the requested capacity is available or the context is cancelled.