done.go 873 B

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