semaphore.go 522 B

123456789101112131415161718192021222324252627
  1. package semaphore
  2. // Instance is an implementation of semaphore.
  3. type Instance struct {
  4. token chan struct{}
  5. }
  6. // New create a new Semaphore with n permits.
  7. func New(n int) *Instance {
  8. s := &Instance{
  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 *Instance) Wait() <-chan struct{} {
  18. return s.token
  19. }
  20. // Signal releases a permit into the semaphore.
  21. func (s *Instance) Signal() {
  22. s.token <- struct{}{}
  23. }