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 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消