Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

context 基本使用

func TestTimeout(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	//1. 传递上下文
	go RequestA(ctx)

	time.Sleep(time.Second * 4)
	//#cancel 1.取消
	cancel()
	time.Sleep(time.Second * 10)
}

func RequestA(ctx context.Context) {
	// Do Something ...
	ctx = context.WithValue(ctx, "A", "RequestA")
	tic := time.NewTicker(time.Second * 2)
	// 2. 传递上下文
	go RequestB(ctx)
	for {
		select {
		case <-tic.C:
			//3. 开始转圈圈
			log.Println("A转圈圈")
		case <-ctx.Done():
			//#cancel. A结束
			log.Println("请求A ctx.Done")
			return
		}
	}
}

func RequestB(ctx context.Context) {
	// Do Something ...
	val := ctx.Value("A")
	log.Println("from A : ", val)
	ctx = context.WithValue(ctx, "B", "RequestB")
	tic := time.NewTicker(time.Second * 1)
	for {
		select {
		case <-tic.C:
			//4. 开始转圈圈 1秒1次
			log.Println("B转圈圈")
		case <-ctx.Done():
			//#cancel. B 结束
			log.Println("请求B ctx.Done")
			return
		}
	}
}