Files
netbird/util/semaphore-group/semaphore_group.go
Zoltan Papp 9ba067391f [client] Fix semaphore slot leaks (#5018)
- Remove WaitGroup, make SemaphoreGroup a pure semaphore
- Make Add() return error instead of silently failing on context cancel
- Remove context parameter from Done() to prevent slot leaks
- Fix missing Done() call in conn.go error path
2026-01-03 09:10:02 +01:00

34 lines
722 B
Go

package semaphoregroup
import (
"context"
)
// SemaphoreGroup is a custom type that combines sync.WaitGroup and a semaphore.
type SemaphoreGroup struct {
semaphore chan struct{}
}
// NewSemaphoreGroup creates a new SemaphoreGroup with the specified semaphore limit.
func NewSemaphoreGroup(limit int) *SemaphoreGroup {
return &SemaphoreGroup{
semaphore: make(chan struct{}, limit),
}
}
// Add acquire a slot
func (sg *SemaphoreGroup) Add(ctx context.Context) error {
// Acquire semaphore slot
select {
case <-ctx.Done():
return ctx.Err()
case sg.semaphore <- struct{}{}:
return nil
}
}
// Done releases a slot. Must be called after a successful Add.
func (sg *SemaphoreGroup) Done() {
<-sg.semaphore
}