2
0

sync.go 498 B

123456789101112131415161718192021222324252627282930313233343536
  1. package sync
  2. type Semaphore struct {
  3. ch chan struct{}
  4. }
  5. func NewSemaphore(size int) Semaphore {
  6. return Semaphore{
  7. ch: make(chan struct{}, size),
  8. }
  9. }
  10. func (sem Semaphore) Acquire() {
  11. sem.ch <- struct{}{}
  12. }
  13. func (sem Semaphore) AcquireMaybe() bool {
  14. select {
  15. case sem.ch <- struct{}{}:
  16. return true
  17. default:
  18. return false
  19. }
  20. }
  21. func (sem Semaphore) Release() {
  22. <-sem.ch
  23. }
  24. func (sem Semaphore) Len() int {
  25. return len(sem.ch)
  26. }
  27. func (sem Semaphore) Cap() int {
  28. return cap(sem.ch)
  29. }