You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
792 B

  1. package sync
  2. // Waker is used to wake up a sleeper when some event occurs. It debounces
  3. // multiple wakeup calls occurring between each sleep, and wakeups are
  4. // non-blocking to avoid having to coordinate goroutines.
  5. type Waker struct {
  6. wakeCh chan struct{}
  7. }
  8. // NewWaker creates a new Waker.
  9. func NewWaker() *Waker {
  10. return &Waker{
  11. wakeCh: make(chan struct{}, 1), // buffer used for debouncing
  12. }
  13. }
  14. // Sleep returns a channel that blocks until Wake() is called.
  15. func (w *Waker) Sleep() <-chan struct{} {
  16. return w.wakeCh
  17. }
  18. // Wake wakes up the sleeper.
  19. func (w *Waker) Wake() {
  20. // A non-blocking send with a size 1 buffer ensures that we never block, and
  21. // that we queue up at most a single wakeup call between each Sleep().
  22. select {
  23. case w.wakeCh <- struct{}{}:
  24. default:
  25. }
  26. }