|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- package sync2
-
- import (
- "context"
- "errors"
- "sync"
- )
-
- var ErrEventClosed = errors.New("event is closed")
-
- type Event struct {
- ch chan any
- closeOnce sync.Once
- }
-
- func NewEvent() Event {
- return Event{
- ch: make(chan any, 1),
- }
- }
-
- func (e *Event) Set() {
- select {
- case e.ch <- nil:
- default:
- }
- }
-
- func (e *Event) Wait(ctx context.Context) error {
- select {
- case _, ok := <-e.ch:
- if ok {
- return nil
- }
-
- return ErrEventClosed
-
- case <-ctx.Done():
- return context.Canceled
- }
- }
-
- func (e *Event) Close() {
- e.closeOnce.Do(func() {
- close(e.ch)
- })
- }
|