[#4] limiting: Add limiter
Signed-off-by: Aleksey Savchuk <a.savchuk@yadro.com>
This commit is contained in:
parent
30e83428fd
commit
59fb93fb23
3 changed files with 240 additions and 0 deletions
27
limiting/semaphore/semaphore.go
Normal file
27
limiting/semaphore/semaphore.go
Normal 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)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue