safe_signal.go 788 B

12345678910111213141516171819202122232425262728293031323334
  1. package signal
  2. import (
  3. "sync"
  4. )
  5. // Signal lets goroutines signal that some event has occurred. Other goroutines can wait for the signal.
  6. type Signal struct {
  7. ch chan struct{}
  8. once sync.Once
  9. }
  10. // New wraps a channel and turns it into a signal for a one-time event.
  11. func New(ch chan struct{}) *Signal {
  12. return &Signal{
  13. ch: ch,
  14. once: sync.Once{},
  15. }
  16. }
  17. // Notify alerts any goroutines waiting on this signal that the event has occurred.
  18. // After the first call to Notify(), future calls are no-op.
  19. func (s *Signal) Notify() {
  20. s.once.Do(func() {
  21. close(s.ch)
  22. })
  23. }
  24. // Wait returns a channel which will be written to when Notify() is called for the first time.
  25. // This channel will never be written to a second time.
  26. func (s *Signal) Wait() <-chan struct{} {
  27. return s.ch
  28. }