Middle
Are you familiar with the concept of a weighted semaphore? What is it?
sobes.tech AI
Answer from AI
A weighted semaphore is an extension of the classic semaphore that limits the number of operations executing simultaneously. Unlike a regular semaphore, where each request occupies one resource (unit), a weighted semaphore allows requests to occupy different amounts of resources (weight).
For example, if you have a limit of 10 resource units, one request might occupy 3 units, another — 5, and so on. The semaphore blocks new requests if the total weight of occupied resources reaches the limit.
In Go, this is useful for controlling concurrency with tasks of varying "costs." The standard library includes golang.org/x/sync/semaphore, which implements a weighted semaphore.
Example usage:
import (
"context"
"golang.org/x/sync/semaphore"
)
func main() {
sem := semaphore.NewWeighted(10) // limit of 10 units
ctx := context.Background()
// Request occupies 3 units
if err := sem.Acquire(ctx, 3); err != nil {
// handle error
}
// ... work
sem.Release(3)
}