semaphore.go 342 B

1234567891011121314151617181920212223
  1. package signal
  2. type Semaphore struct {
  3. token chan struct{}
  4. }
  5. func NewSemaphore(n int) *Semaphore {
  6. s := &Semaphore{
  7. token: make(chan struct{}, n),
  8. }
  9. for i := 0; i < n; i++ {
  10. s.token <- struct{}{}
  11. }
  12. return s
  13. }
  14. func (s *Semaphore) Wait() <-chan struct{} {
  15. return s.token
  16. }
  17. func (s *Semaphore) Signal() {
  18. s.token <- struct{}{}
  19. }