1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package main
- import (
- "context"
- "flag"
- "fmt"
- lazyquiter "git.swzry.com/zry/go-lazy-quiter"
- "math/rand"
- "os"
- "time"
- )
- var quitch chan int
- var timeout int
- var PID int
- var ExtraMsg string
- func main() {
- flag.IntVar(&timeout, "t", 0, "Quit after specified milliseconds. 0 for unlimited.")
- flag.StringVar(&ExtraMsg, "m", "nya~~~~~~~~~~~~~~~~", "The message will be printed repeatedly.")
- flag.Parse()
- PID = os.Getpid()
- ctx, cncl := context.WithCancel(context.Background())
- lq := lazyquiter.NewLazyQuiter()
- quitch = make(chan int, 0)
- abortch := make(chan int, 0)
- go printing(ctx, quitch)
- go func() {
- lq.Wait()
- abortch <- 0
- }()
- if timeout > 0 {
- go func() {
- select {
- case <-time.After(time.Duration(timeout) * time.Millisecond):
- {
- AppPrint("execute ctx cancel by timeout.")
- cncl()
- }
- case <-abortch:
- {
- AppPrint("execute ctx cancel by user abort.")
- cncl()
- }
- }
- }()
- } else {
- go func() {
- <-abortch
- AppPrint("execute ctx cancel by user abort.")
- cncl()
- }()
- }
- AppPrint("main thread wait for done.")
- quitCode := <-quitch
- AppPrint(fmt.Sprint("main thread end, quit code: ", quitCode))
- os.Exit(quitCode)
- }
- func printing(ctx context.Context, okchan chan int) {
- LabelLoop:
- for {
- AppPrint(fmt.Sprint("msg print: ", ExtraMsg))
- jitter := rand.Int31n(1000)
- sltime := time.Duration(jitter+1000) * time.Millisecond
- time.Sleep(sltime)
- select {
- case <-ctx.Done():
- {
- break LabelLoop
- }
- default:
- continue LabelLoop
- }
- }
- AppPrint("printing goroutine end.")
- okchan <- 0
- }
- func AppPrint(text string) {
- tstr := time.Now().Format(time.RFC3339Nano)
- fmt.Printf("[test-app-a:%08d] <%s> %s\n", PID, tstr, text)
- }
|