semaphore.go 572 B

12345678910111213141516171819202122232425
  1. package util
  2. // Semaphore implements a non-weighted semaphore for restricting
  3. // concurrent access to a limited number of processes.
  4. type Semaphore struct {
  5. s chan bool
  6. }
  7. // Acquire blocks until access can be granted to the caller
  8. func (s *Semaphore) Acquire() {
  9. s.s <- true
  10. }
  11. // Return releases access from the caller, opening it for acquisition
  12. func (s *Semaphore) Return() {
  13. <-s.s
  14. }
  15. // NewSemaphore creates a new Semaphore that allows max number of
  16. // concurrent access
  17. func NewSemaphore(max int) *Semaphore {
  18. return &Semaphore{
  19. s: make(chan bool, max),
  20. }
  21. }