github.com/number571/tendermint@v0.34.11-gost/internal/libs/sync/closer.go (about) 1 package sync 2 3 import "sync" 4 5 // Closer implements a primitive to close a channel that signals process 6 // termination while allowing a caller to call Close multiple times safely. It 7 // should be used in cases where guarantees cannot be made about when and how 8 // many times closure is executed. 9 type Closer struct { 10 closeOnce sync.Once 11 doneCh chan struct{} 12 } 13 14 // NewCloser returns a reference to a new Closer. 15 func NewCloser() *Closer { 16 return &Closer{doneCh: make(chan struct{})} 17 } 18 19 // Done returns the internal done channel allowing the caller either block or wait 20 // for the Closer to be terminated/closed. 21 func (c *Closer) Done() <-chan struct{} { 22 return c.doneCh 23 } 24 25 // Close gracefully closes the Closer. A caller should only call Close once, but 26 // it is safe to call it successive times. 27 func (c *Closer) Close() { 28 c.closeOnce.Do(func() { 29 close(c.doneCh) 30 }) 31 }