gitee.com/h79/goutils@v1.22.10/common/system/event.go (about)

     1  package system
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  )
     7  
     8  // Event represents a one-time event that may occur in the future.
     9  type Event struct {
    10  	fired int32
    11  	c     chan struct{}
    12  	o     sync.Once
    13  }
    14  
    15  // Fire causes e to complete.  It is safe to call multiple times, and
    16  // concurrently.  It returns true iff this call to Fire caused the signaling
    17  // channel returned by Done to close.
    18  func (e *Event) Fire() bool {
    19  	ret := false
    20  	e.o.Do(func() {
    21  		atomic.StoreInt32(&e.fired, 1)
    22  		close(e.c)
    23  		ret = true
    24  	})
    25  	return ret
    26  }
    27  
    28  // Done returns a channel that will be closed when Fire is called.
    29  func (e *Event) Done() <-chan struct{} {
    30  	return e.c
    31  }
    32  
    33  // HasFired returns true if Fire has been called.
    34  func (e *Event) HasFired() bool {
    35  	return atomic.LoadInt32(&e.fired) == 1
    36  }
    37  
    38  // NewEvent returns a new, ready-to-use Event.
    39  func NewEvent() *Event {
    40  	return &Event{c: make(chan struct{})}
    41  }