cancel.go 1007 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package signal
  2. import (
  3. "sync"
  4. )
  5. // CancelSignal is a signal passed to goroutine, in order to cancel the goroutine on demand.
  6. type CancelSignal struct {
  7. cancel chan struct{}
  8. done sync.WaitGroup
  9. }
  10. // NewCloseSignal creates a new CancelSignal.
  11. func NewCloseSignal() *CancelSignal {
  12. return &CancelSignal{
  13. cancel: make(chan struct{}),
  14. }
  15. }
  16. func (v *CancelSignal) WaitThread() {
  17. v.done.Add(1)
  18. }
  19. // Cancel signals the goroutine to stop.
  20. func (v *CancelSignal) Cancel() {
  21. close(v.cancel)
  22. }
  23. func (v *CancelSignal) Cancelled() bool {
  24. select {
  25. case <-v.cancel:
  26. return true
  27. default:
  28. return false
  29. }
  30. }
  31. // WaitForCancel should be monitored by the goroutine for when to stop.
  32. func (v *CancelSignal) WaitForCancel() <-chan struct{} {
  33. return v.cancel
  34. }
  35. // FinishThread signals that current goroutine has finished.
  36. func (v *CancelSignal) FinishThread() {
  37. v.done.Done()
  38. }
  39. // WaitForDone is used by caller to wait for the goroutine finishes.
  40. func (v *CancelSignal) WaitForDone() {
  41. v.done.Wait()
  42. }