go chan

go chan

func main() {
	baseCtx := context.Background()

	ctx := context.WithValue(baseCtx, "a", "b")

	go func(c context.Context) {
		fmt.Println(c.Value("a"))
	}(ctx)

	timeoutCtx, cancel := context.WithTimeout(baseCtx, 2*time.Second)
	defer cancel()

	go func(ctx context.Context) {
		// 超时时间
		ticker := time.NewTicker(3 * time.Second)

		for _ = range ticker.C {
			select {
			// 超时(大于ticker以后会超时)以后会Done
			case <-ctx.Done():
				fmt.Println("x")
				return
			default:
				fmt.Println("xxxx")
			}
		}
	}(timeoutCtx)

	time.Sleep(10 * time.Second)
}
posted @ 2022-06-07 01:13  taotaozh  阅读(80)  评论(0编辑  收藏  举报