testcontext.go 693 B

12345678910111213141516171819202122232425262728293031323334
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. func main() {
  8. ctx, cancel := context.WithCancel(context.Background())
  9. //附加值
  10. valueCtx:=context.WithValue(ctx,key,"【监控1】")
  11. go watch(valueCtx)
  12. time.Sleep(10 * time.Second)
  13. fmt.Println("可以了,通知监控停止")
  14. cancel()
  15. //为了检测监控过是否停止,如果没有监控输出,就表示停止了
  16. time.Sleep(5 * time.Second)
  17. }
  18. func watch(ctx context.Context) {
  19. for {
  20. select {
  21. case <-ctx.Done():
  22. //取出值
  23. fmt.Println(ctx.Value(key),"监控退出,停止了...")
  24. return
  25. default:
  26. //取出值
  27. fmt.Println(ctx.Value(key),"goroutine监控中...")
  28. time.Sleep(2 * time.Second)
  29. }
  30. }
  31. }