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 571 B

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