实现说明
WithoutCancel 与取消原因隔离可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
child done is nil:、child err before cancel:、parent err:。
常见问题
运行「WithoutCancel 与取消原因隔离」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 child done is nil:、child err before cancel:、parent err: 标签标明各步骤。
核心语句
parent = context.WithValue(parent, jobID{}, "batch-42")
parent, cancel := context.WithCancelCause(context.Background())
child := context.WithoutCancel(parent)
代码示例
package main
import (
"context"
"errors"
"fmt"
)
type jobID struct{}
func main() {
// WithCancelCause:取消时可以携带一个具体原因
parent, cancel := context.WithCancelCause(context.Background())
parent = context.WithValue(parent, jobID{}, "batch-42")
// WithoutCancel 派生:保留 Value,但父级取消不会传播过来
child := context.WithoutCancel(parent)
fmt.Println("child done is nil:", child.Done() == nil)
fmt.Println("child err before cancel:", child.Err())
// 取消父级,带上真实原因
cancel(errors.New("disk full"))
// 父级:Err 是笼统的 Canceled,Cause 才携带传入的原因
fmt.Println("parent err:", parent.Err())
fmt.Println("parent cause:", context.Cause(parent))
// 子级:Err 恒为 nil,Value 依旧可读——善后逻辑不受取消竞态影响
fmt.Println("child err after cancel:", child.Err())
fmt.Println("child value after cancel:", child.Value(jobID{}))
}