main.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. lazyquiter "git.swzry.com/zry/go-lazy-quiter"
  6. tombv2 "gopkg.in/tomb.v2"
  7. "math/rand"
  8. "os"
  9. "time"
  10. )
  11. func main() {
  12. lq := lazyquiter.NewLazyQuiter()
  13. quitch := make(chan error, 0)
  14. tt := NewTask()
  15. tt.Start()
  16. go func() {
  17. lq.Wait()
  18. fmt.Println("[tomb-test-2023-0124-1301] stop task.")
  19. err := tt.Stop()
  20. quitch <- err
  21. }()
  22. fmt.Println("[tomb-test-2023-0124-1301] main thread wait for done.")
  23. err := <-quitch
  24. if err != nil {
  25. fmt.Println("[tomb-test-2023-0124-1301] main thread end with error:", err)
  26. } else {
  27. fmt.Println("[tomb-test-2023-0124-1301] main thread end with no error.")
  28. }
  29. }
  30. type TombedTask struct {
  31. tomb *tombv2.Tomb
  32. ctx context.Context
  33. }
  34. func NewTask() *TombedTask {
  35. tt := &TombedTask{}
  36. t, ctx := tombv2.WithContext(context.Background())
  37. tt.tomb = t
  38. tt.ctx = ctx
  39. return tt
  40. }
  41. func (t *TombedTask) task() error {
  42. pid := os.Getpid()
  43. tstr := time.Now().Format(time.RFC3339Nano)
  44. LabelLoop:
  45. for {
  46. fmt.Printf("[tomb-test-2023-0124-1301] pid=%d\ttime=%s\n", pid, tstr)
  47. jitter := rand.Int31n(1000)
  48. sltime := time.Duration(jitter+1000) * time.Millisecond
  49. time.Sleep(sltime)
  50. select {
  51. case <-t.tomb.Dying():
  52. {
  53. break LabelLoop
  54. }
  55. default:
  56. continue LabelLoop
  57. }
  58. }
  59. fmt.Println("[tomb-test-2023-0124-1301] printing task end.")
  60. return nil
  61. }
  62. func (t *TombedTask) Start() {
  63. t.tomb.Go(t.task)
  64. }
  65. func (t *TombedTask) Stop() error {
  66. t.tomb.Kill(nil)
  67. return t.tomb.Wait()
  68. }