signal.go 896 B

1234567891011121314151617181920212223242526272829303132333435
  1. package h2mux
  2. // Signal describes an event that can be waited on for at least one signal.
  3. // Signalling the event while it is in the signalled state is a noop.
  4. // When the waiter wakes up, the signal is set to unsignalled.
  5. // It is a way for any number of writers to inform a reader (without blocking)
  6. // that an event has happened.
  7. type Signal struct {
  8. c chan struct{}
  9. }
  10. // NewSignal creates a new Signal.
  11. func NewSignal() Signal {
  12. return Signal{c: make(chan struct{}, 1)}
  13. }
  14. // Signal signals the event.
  15. func (s Signal) Signal() {
  16. // This channel is buffered, so the nonblocking send will always succeed if the buffer is empty.
  17. select {
  18. case s.c <- struct{}{}:
  19. default:
  20. }
  21. }
  22. // Wait for the event to be signalled.
  23. func (s Signal) Wait() {
  24. <-s.c
  25. }
  26. // WaitChannel returns a channel that is readable after Signal is called.
  27. func (s Signal) WaitChannel() <-chan struct{} {
  28. return s.c
  29. }