semaphore.go 691 B

12345678910111213141516171819202122232425262728293031
  1. package chansync
  2. import (
  3. "github.com/anacrolix/chansync/events"
  4. )
  5. // Channel semaphore, as is popular for controlling access to limited resources. Should not be used
  6. // zero-initialized.
  7. type Semaphore struct {
  8. ch chan struct{}
  9. }
  10. // Returns an initialized semaphore with n slots.
  11. func NewSemaphore(n int) Semaphore {
  12. return Semaphore{ch: make(chan struct{}, n)}
  13. }
  14. // Returns a channel for acquiring a slot.
  15. func (me Semaphore) Acquire() events.Acquire {
  16. return me.ch
  17. }
  18. // Returns a channel for releasing a slot.
  19. func (me Semaphore) Release() events.Release {
  20. return me.ch
  21. }
  22. // Returns the current number of acquired values.
  23. func (me Semaphore) Value() int {
  24. return len(me.ch)
  25. }