golang context WithTimeout 琐碎

func main() {
	parent ,cancel1 :=context.WithTimeout(context.Background(),time.Second*2)
	fmt.Println("起始时间。。。。。。,time0=", time.Now().Unix())
	watch(parent,"aa")
	for {
		select {
		case <-parent.Done():
			fmt.Println( "parent收到信号,退出,time=", time.Now().Unix())
			return
		default:
			//	fmt.Println(name, "goroutine监控中,time=", time.Now().Unix())
			time.Sleep(1 * time.Second)
		}
	}
}
func watch(ctx context.Context, name string) {
	ctx2 :=context.WithValue(ctx,"aa","aa")
	ctx2,cannel := context.WithTimeout(ctx,5*time.Second)//此时父ctx是2秒,子ctx是5秒
	defer cannel()
	for {
		select {
		case <-ctx2.Done():
			fmt.Println(name, "watch ctx2收到信号,退出,time2=", time.Now().Unix())
			return
		default:
		//	fmt.Println(name, "goroutine监控中,time=", time.Now().Unix())
			time.Sleep(1 * time.Second)
		}
	}
	fmt.Println(ctx2)
}

运行的结果是:
起始时间。。。。。。,time0= 1712829562
aa watch ctx2收到信号,监控退出,time2= 1712829564
parent收到信号,监控退出,time= 1712829564

若父的ctx的timeout到期了,比子ctx提前到期,则子的也会到期

func main() {
	parent ,cancel1 :=context.WithTimeout(context.Background(),time.Second*5)
	fmt.Println("起始时间。。。。。。,time0=", time.Now().Unix())
	watch(parent,"aa")
	for {
		select {
		case <-parent.Done():
			fmt.Println( "parent收到信号,退出,time=", time.Now().Unix())
			return
		default:
			//	fmt.Println(name, "goroutine监控中,time=", time.Now().Unix())
			time.Sleep(1 * time.Second)
		}
	}
	defer cancel1()
}
func watch(ctx context.Context, name string) {
	child,cannel := context.WithTimeout(ctx,2*time.Second)//此时父ctx是5秒,子ctx是2秒
	defer cannel()
	for {
		select {
		case <-child.Done():
			fmt.Println(name, "watch child收到信号,退出,time2=", time.Now().Unix())
			return
		default:
		//	fmt.Println(name, "goroutine监控中,time=", time.Now().Unix())
			time.Sleep(1 * time.Second)
		}
	}
	fmt.Println(ctx2)
}

起始时间。。。。。。,time0= 1712829658
aa watch ctx2收到信号,监控退出,time2= 1712829663
parent收到信号,监控退出,time= 1712829663
若子ctx的timeout到期了,比父ctx提前到期,则并不会影响到父
追源码能看到(应该这里的判断)
在这里插入图片描述

结论:

父ctx结束时,下面所有的子ctx都会结束。但是当前子ctx结束时,并不会影响到其父级的ctx

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值