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

event.go 629 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package sync2
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. )
  7. var ErrEventClosed = errors.New("event is closed")
  8. var ErrContextCanceled = errors.New("context canceled")
  9. type Event struct {
  10. ch chan any
  11. closeOnce sync.Once
  12. }
  13. func NewEvent() Event {
  14. return Event{
  15. ch: make(chan any, 1),
  16. }
  17. }
  18. func (e *Event) Set() {
  19. select {
  20. case e.ch <- nil:
  21. default:
  22. }
  23. }
  24. func (e *Event) Wait(ctx context.Context) error {
  25. select {
  26. case _, ok := <-e.ch:
  27. if ok {
  28. return nil
  29. }
  30. return ErrEventClosed
  31. case <-ctx.Done():
  32. return ErrContextCanceled
  33. }
  34. }
  35. func (e *Event) Close() {
  36. e.closeOnce.Do(func() {
  37. close(e.ch)
  38. })
  39. }