packagemainimport("fmt""time")funcmain(){stop:=make(chanbool)gofunc(){for{select{case<-stop:fmt.Println("got the stop channel")returndefault:fmt.Println("still working")time.Sleep(1*time.Second)}}}()time.Sleep(5*time.Second)fmt.Println("stop the gorutine")stop<-truetime.Sleep(5*time.Second)}
packagemainimport("context""fmt""time")funcmain(){ctx,cancel:=context.WithCancel(context.Background())gofunc(){for{select{case<-ctx.Done():fmt.Println("got the stop channel")returndefault:fmt.Println("still working")time.Sleep(1*time.Second)}}}()time.Sleep(5*time.Second)fmt.Println("stop the gorutine")cancel()time.Sleep(5*time.Second)}
packagemainimport("context""fmt""time")funcmain(){ctx,cancel:=context.WithCancel(context.Background())goworker(ctx,"node01")goworker(ctx,"node02")goworker(ctx,"node03")time.Sleep(5*time.Second)fmt.Println("stop the gorutine")cancel()time.Sleep(5*time.Second)}funcworker(ctxcontext.Context,namestring){for{select{case<-ctx.Done():fmt.Println(name,"got the stop channel")returndefault:fmt.Println(name,"still working")time.Sleep(1*time.Second)}}}