亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Go stdlib 使用互斥鎖來讀取上下文的錯誤字段?

為什么 Go stdlib 使用互斥鎖來讀取上下文的錯誤字段?

Go
眼眸繁星 2023-01-03 15:48:43
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}
查看完整描述

1 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

原因之一應該是RWLock 性能不佳

鎖的性能不取決于它提供的特性,它取決于底層的implementation. 雖然理論上RWLock可以提供更高的throughputs,但對于這種特定場景(改變一個微小的變量),Mutex可以提供更低的unnecessary overhead


查看完整回答
反對 回復 2023-01-03
  • 1 回答
  • 0 關注
  • 110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號