semaphore.go 543 B

123456789101112131415161718192021222324252627
  1. package signal
  2. // Semaphore is an implementation of semaphore.
  3. type Semaphore struct {
  4. token chan struct{}
  5. }
  6. // NewSemaphore create a new Semaphore with n permits.
  7. func NewSemaphore(n int) *Semaphore {
  8. s := &Semaphore{
  9. token: make(chan struct{}, n),
  10. }
  11. for i := 0; i < n; i++ {
  12. s.token <- struct{}{}
  13. }
  14. return s
  15. }
  16. // Wait returns a channel for acquiring a permit.
  17. func (s *Semaphore) Wait() <-chan struct{} {
  18. return s.token
  19. }
  20. // Signal releases a permit into the Semaphore.
  21. func (s *Semaphore) Signal() {
  22. s.token <- struct{}{}
  23. }