代码示例
package main
import (
"context"
"fmt"
"time"
)
func main() {
parentCtxTimeout := 4
childCtxTimeout := 2
parentCtx, parentCancel := context.WithTimeout(context.Background(), time.Duration(parentCtxTimeout)*time.Second)
defer parentCancel()
childCtx, childCancel := context.WithTimeout(parentCtx, time.Duration(childCtxTimeout)*time.Second)
defer childCancel()
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("子级 context 超时")
}
}(childCtx)
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("父级 context 超时")
}
}(parentCtx)
time.Sleep(8 * time.Second)
}
总结
- 父级 context 超时时间>子级 context 超时时间,父级 context先超时,子级context后超时
- 父级 context 超时时间<子级 context 超时时间,子级 context随着父级 context超时而超时
- 父级 context 超时时间=子级 context 超时时间,子级 context先超时,父级context后超时