You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
877 B

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