其他分享
首页 > 其他分享> > go chan

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)
}

标签:context,ctx,chan,baseCtx,func,go,ticker
来源: https://www.cnblogs.com/hsyw/p/16350343.html