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
GoroutineContextManagementwithTimeoutinGo:Parent-ChildRelationships
本文讨论了Go语言中Context和Timeout在函数`watch`中的应用,强调了父Context的超时如何影响子Context,以及当子Context先超时时,不会影响父Context的生命周期。
918

被折叠的 条评论
为什么被折叠?



