[#4] limiting: Add limiter

Signed-off-by: Aleksey Savchuk <a.savchuk@yadro.com>
This commit is contained in:
Aleksey Savchuk 2025-02-04 17:32:01 +03:00
parent 30e83428fd
commit 59fb93fb23
Signed by: a-savchuk
GPG key ID: 70C0A7FF6F9C4639
3 changed files with 240 additions and 0 deletions

View file

@ -0,0 +1,27 @@
package semaphore
import (
"sync/atomic"
)
type Semaphore struct {
count atomic.Int64
limit int64
}
func NewSemaphore(size int64) *Semaphore {
return &Semaphore{limit: size}
}
func (s *Semaphore) Acquire() bool {
v := s.count.Add(1)
if v > s.limit {
s.count.Add(-1)
return false
}
return true
}
func (s *Semaphore) Release() {
s.count.Add(-1)
}