ContextGo 標(biāo)準(zhǔn)庫中有許多接口的底層實(shí)現(xiàn)。例如,Background和TODO上下文由未公開的emptyCtx類型支持,該類型本質(zhì)上只是int一些存根方法(proof)。類似地,每次調(diào)用都會(huì)context.WithCancel()返回該cancelCtx類型的一個(gè)實(shí)例,該實(shí)例已經(jīng)是具有一堆互斥保護(hù)屬性(證明)的適當(dāng)結(jié)構(gòu):// 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結(jié)構(gòu)使用互斥鎖而不是RWLock?例如,該Err()方法當(dāng)前獲得了一個(gè)完整的鎖,而它(可能)可能只使用了一個(gè)RLock:func (c *cancelCtx) Err() error { c.mu.Lock() err := c.err c.mu.Unlock() return err}
- 1 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)
0/150
提交
取消