done.go 830 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package done
  2. import (
  3. "sync"
  4. )
  5. // Instance is a utility for notifications of something being done.
  6. type Instance struct {
  7. access sync.Mutex
  8. c chan struct{}
  9. closed bool
  10. }
  11. // New returns a new Done.
  12. func New() *Instance {
  13. return &Instance{
  14. c: make(chan struct{}),
  15. }
  16. }
  17. // Done returns true if Close() is called.
  18. func (d *Instance) Done() bool {
  19. select {
  20. case <-d.Wait():
  21. return true
  22. default:
  23. return false
  24. }
  25. }
  26. // Wait returns a channel for waiting for done.
  27. func (d *Instance) Wait() <-chan struct{} {
  28. return d.c
  29. }
  30. // Close marks this Done 'done'. This method may be called multiple times. All calls after first call will have no effect on its status.
  31. func (d *Instance) Close() error {
  32. d.access.Lock()
  33. defer d.access.Unlock()
  34. if d.closed {
  35. return nil
  36. }
  37. d.closed = true
  38. close(d.c)
  39. return nil
  40. }