ContextGo 标准库中有许多接口的底层实现。例如,Background和TODO上下文由未公开的emptyCtx类型支持,该类型本质上只是int一些存根方法(proof)。类似地,每次调用都会context.WithCancel()返回该cancelCtx类型的一个实例,该实例已经是具有一堆互斥保护属性(证明)的适当结构:
// A cancelCtx can be canceled. When canceled, it also cancels any children
// that implement canceler.
type cancelCtx struct {
Context
mu sync.Mutex // protects following fields
done atomic.Value // of chan struct{}, created lazily, closed by first cancel call
children map[canceler]struct{} // set to nil by the first cancel call
err error // set to non-nil by the first cancel call
}
为什么该cancelCtx结构使用互斥锁而不是RWLock?例如,该Err()方法当前获得了一个完整的锁,而它(可能)可能只使用了一个RLock:
func (c *cancelCtx) Err() error {
c.mu.Lock()
err := c.err
c.mu.Unlock()
return err
}
FFIVE
相关分类