2017-02-13 17:29:34 -05:00
|
|
|
package signal
|
|
|
|
|
2018-04-14 03:59:30 -04:00
|
|
|
// Semaphore is an implementation of semaphore.
|
2017-02-13 17:29:34 -05:00
|
|
|
type Semaphore struct {
|
2018-02-08 09:39:46 -05:00
|
|
|
token chan struct{}
|
2017-02-13 17:29:34 -05:00
|
|
|
}
|
|
|
|
|
2018-04-14 03:59:30 -04:00
|
|
|
// NewSemaphore create a new Semaphore with n permits.
|
2017-02-13 17:29:34 -05:00
|
|
|
func NewSemaphore(n int) *Semaphore {
|
|
|
|
s := &Semaphore{
|
2018-02-08 09:39:46 -05:00
|
|
|
token: make(chan struct{}, n),
|
2017-02-13 17:29:34 -05:00
|
|
|
}
|
|
|
|
for i := 0; i < n; i++ {
|
2018-02-08 09:39:46 -05:00
|
|
|
s.token <- struct{}{}
|
2017-02-13 17:29:34 -05:00
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2018-04-14 03:59:30 -04:00
|
|
|
// Wait returns a channel for acquiring a permit.
|
2018-02-08 09:39:46 -05:00
|
|
|
func (s *Semaphore) Wait() <-chan struct{} {
|
2017-02-13 17:29:34 -05:00
|
|
|
return s.token
|
|
|
|
}
|
|
|
|
|
2018-04-14 03:59:30 -04:00
|
|
|
// Signal releases a permit into the Semaphore.
|
2017-02-13 17:29:34 -05:00
|
|
|
func (s *Semaphore) Signal() {
|
2018-02-08 09:39:46 -05:00
|
|
|
s.token <- struct{}{}
|
2017-02-13 17:29:34 -05:00
|
|
|
}
|