为什么 Go stdlib 使用互斥锁来读取上下文的错误字段?

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

}


眼眸繁星
浏览 125回答 1
1回答

FFIVE

原因之一应该是RWLock 性能不佳。锁的性能不取决于它提供的特性,它取决于底层的implementation. 虽然理论上RWLock可以提供更高的throughputs,但对于这种特定场景(改变一个微小的变量),Mutex可以提供更低的unnecessary overhead。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go