github.com/searKing/golang/go@v1.2.117/sync/event.go (about) 1 // Copyright 2021 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package sync 6 7 import ( 8 "sync" 9 "sync/atomic" 10 ) 11 12 // Event represents a one-time event that may occur in the future. 13 // we use a fast path to avoid the more-expensive "select" below after the Event has returned once. 14 type Event struct { 15 // This is on the RPC path, so we use a fast path to avoid the 16 // more-expensive "select" below after the resolver has returned once. 17 fired int32 18 c chan struct{} 19 o sync.Once 20 } 21 22 // Fire causes e to complete. It is safe to call multiple times, and 23 // concurrently. It returns true iff this call to Fire caused the signaling 24 // channel returned by Done to close. 25 func (e *Event) Fire() bool { 26 ret := false 27 e.o.Do(func() { 28 atomic.StoreInt32(&e.fired, 1) 29 close(e.c) 30 ret = true 31 }) 32 return ret 33 } 34 35 // Done returns a channel that will be closed when Fire is called. 36 func (e *Event) Done() <-chan struct{} { 37 return e.c 38 } 39 40 // HasFired returns true if Fire has been called. 41 // we use a fast path to avoid the more-expensive "select" below after the Event has returned once. 42 func (e *Event) HasFired() bool { 43 return atomic.LoadInt32(&e.fired) == 1 44 } 45 46 // NewEvent returns a new, ready-to-use Event. 47 func NewEvent() *Event { 48 return &Event{c: make(chan struct{})} 49 }