28 lines
363 B
Go
28 lines
363 B
Go
|
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)
|
||
|
}
|