登录
首页 >  Golang >  Go问答

为何 Go stdlib 使用互斥锁保护读取上下文错误字段的操作?

来源:stackoverflow

时间:2024-02-14 18:09:19 453浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《为何 Go stdlib 使用互斥锁保护读取上下文错误字段的操作?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

go 标准库中有许多 context 接口的底层实现。例如, backgroundtodo 上下文由未公开的 emptyctx 类型支持,该类型本质上只是带有一些存根方法的 int (证明)。类似地,每次调用 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
}

正确答案


原因之一应该是 RWLock has poor performance

锁的性能并不取决于它提供的功能,而是取决于底层的 implementation。虽然理论上 RWLock 可以提供更高的 吞吐量,但对于这种特定场景(改变一个微小变量),Mutex 可以提供更低的 不必要的开销

理论要掌握,实操不能落!以上关于《为何 Go stdlib 使用互斥锁保护读取上下文错误字段的操作?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>