1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package main
import ( "context" "fmt" "time" )
func main() { ctx, cancel := context.WithCancel(context.Background()) valueCtx1 := context.WithValue(ctx, "key", "【监控1】") valueCtx2 := context.WithValue(ctx, "key", "【监控2】") valueCtx3 := context.WithValue(ctx, "key", "【监控3】") go watch(valueCtx1, "【监控1】") go watch(valueCtx2, "【监控2】") go watch(valueCtx3, "【监控3】")
time.Sleep(10 * time.Second) fmt.Println("可以了,通知监控停止") cancel() time.Sleep(5 * time.Second) }
func watch(ctx context.Context, name string) { go watch2(ctx, name+"1") for { select { case <-ctx.Done(): fmt.Println(name, ctx.Value("key"), "监控退出,停止了...") return default: fmt.Println(name, ctx.Value("key"), "goroutine监控中...") time.Sleep(2 * time.Second) } } } func watch2(ctx context.Context, name string) { for { select { case <-ctx.Done(): fmt.Println(name, "监控退出,停止了...") return default: fmt.Println(name, "goroutine监控中...") time.Sleep(2 * time.Second) } } }
|