main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. lazyquiter "git.swzry.com/zry/go-lazy-quiter"
  7. "math/rand"
  8. "os"
  9. "time"
  10. )
  11. var quitch chan int
  12. var timeout int
  13. var PID int
  14. var ExtraMsg string
  15. func main() {
  16. flag.IntVar(&timeout, "t", 0, "Quit after specified milliseconds. 0 for unlimited.")
  17. flag.StringVar(&ExtraMsg, "m", "nya~~~~~~~~~~~~~~~~", "The message will be printed repeatedly.")
  18. flag.Parse()
  19. PID = os.Getpid()
  20. ctx, cncl := context.WithCancel(context.Background())
  21. lq := lazyquiter.NewLazyQuiter()
  22. quitch = make(chan int, 0)
  23. abortch := make(chan int, 0)
  24. go printing(ctx, quitch)
  25. go func() {
  26. lq.Wait()
  27. abortch <- 0
  28. }()
  29. if timeout > 0 {
  30. go func() {
  31. select {
  32. case <-time.After(time.Duration(timeout) * time.Millisecond):
  33. {
  34. AppPrint("execute ctx cancel by timeout.")
  35. cncl()
  36. }
  37. case <-abortch:
  38. {
  39. AppPrint("execute ctx cancel by user abort.")
  40. cncl()
  41. }
  42. }
  43. }()
  44. } else {
  45. go func() {
  46. <-abortch
  47. AppPrint("execute ctx cancel by user abort.")
  48. cncl()
  49. }()
  50. }
  51. AppPrint("main thread wait for done.")
  52. quitCode := <-quitch
  53. AppPrint(fmt.Sprint("main thread end, quit code: ", quitCode))
  54. os.Exit(quitCode)
  55. }
  56. func printing(ctx context.Context, okchan chan int) {
  57. LabelLoop:
  58. for {
  59. AppPrint(fmt.Sprint("msg print: ", ExtraMsg))
  60. jitter := rand.Int31n(1000)
  61. sltime := time.Duration(jitter+1000) * time.Millisecond
  62. time.Sleep(sltime)
  63. select {
  64. case <-ctx.Done():
  65. {
  66. break LabelLoop
  67. }
  68. default:
  69. continue LabelLoop
  70. }
  71. }
  72. AppPrint("printing goroutine end.")
  73. okchan <- 0
  74. }
  75. func AppPrint(text string) {
  76. tstr := time.Now().Format(time.RFC3339Nano)
  77. fmt.Printf("[test-app-a:%08d] <%s> %s\n", PID, tstr, text)
  78. }